Sort includes for files gdb/[a-f]*.[chyl].
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2019 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
22 /* Standard C includes.  */
23 #include <ctype.h>
24
25 /* Local non-gdb includes.  */
26 #include "ada-lang.h"
27 #include "annotate.h"
28 #include "arch-utils.h"
29 #include "ax-gdb.h"
30 #include "block.h"
31 #include "breakpoint.h"
32 #include "cli/cli-script.h"
33 #include "cli/cli-style.h"
34 #include "cli/cli-utils.h"
35 #include "command.h"
36 #include "common/format.h"
37 #include "completer.h"
38 #include "continuations.h"
39 #include "dummy-frame.h"
40 #include "expression.h"
41 #include "filenames.h"
42 #include "frame.h"
43 #include "gdb-demangle.h"
44 #include "gdb_regex.h"
45 #include "gdbcmd.h"
46 #include "gdbcore.h"
47 #include "gdbthread.h"
48 #include "gdbtypes.h"
49 #include "hashtab.h"
50 #include "inferior.h"
51 #include "infrun.h"
52 #include "interps.h"
53 #include "jit.h"
54 #include "language.h"
55 #include "linespec.h"
56 #include "memattr.h"
57 #include "mi/mi-main.h"
58 #include "objfiles.h"
59 #include "observable.h"
60 #include "parser-defs.h"
61 #include "probe.h"
62 #include "skip.h"
63 #include "solib.h"
64 #include "solist.h"
65 #include "source.h"
66 #include "stack.h"
67 #include "symfile.h"
68 #include "symtab.h"
69 #include "target.h"
70 #include "thread-fsm.h"
71 #include "tid-parse.h"
72 #include "top.h"
73 #include "tracepoint.h"
74 #include "ui-out.h"
75 #include "valprint.h"
76 #include "value.h"
77
78 /* readline include files */
79 #include "readline/readline.h"
80 #include "readline/history.h"
81
82 /* readline defines this.  */
83 #undef savestring
84
85 #include "mi/mi-common.h"
86 #include "extension.h"
87 #include <algorithm>
88 #include "progspace-and-thread.h"
89 #include "common/array-view.h"
90 #include "common/gdb_optional.h"
91
92 /* Enums for exception-handling support.  */
93 enum exception_event_kind
94 {
95   EX_EVENT_THROW,
96   EX_EVENT_RETHROW,
97   EX_EVENT_CATCH
98 };
99
100 /* Prototypes for local functions.  */
101
102 static void map_breakpoint_numbers (const char *,
103                                     gdb::function_view<void (breakpoint *)>);
104
105 static void breakpoint_re_set_default (struct breakpoint *);
106
107 static void
108   create_sals_from_location_default (const struct event_location *location,
109                                      struct linespec_result *canonical,
110                                      enum bptype type_wanted);
111
112 static void create_breakpoints_sal_default (struct gdbarch *,
113                                             struct linespec_result *,
114                                             gdb::unique_xmalloc_ptr<char>,
115                                             gdb::unique_xmalloc_ptr<char>,
116                                             enum bptype,
117                                             enum bpdisp, int, int,
118                                             int,
119                                             const struct breakpoint_ops *,
120                                             int, int, int, unsigned);
121
122 static std::vector<symtab_and_line> decode_location_default
123   (struct breakpoint *b, const struct event_location *location,
124    struct program_space *search_pspace);
125
126 static int can_use_hardware_watchpoint
127     (const std::vector<value_ref_ptr> &vals);
128
129 static void mention (struct breakpoint *);
130
131 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
132                                                                enum bptype,
133                                                                const struct breakpoint_ops *);
134 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
135                                                        const struct symtab_and_line *);
136
137 /* This function is used in gdbtk sources and thus can not be made
138    static.  */
139 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
140                                        struct symtab_and_line,
141                                        enum bptype,
142                                        const struct breakpoint_ops *);
143
144 static struct breakpoint *
145   momentary_breakpoint_from_master (struct breakpoint *orig,
146                                     enum bptype type,
147                                     const struct breakpoint_ops *ops,
148                                     int loc_enabled);
149
150 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
151
152 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
153                                             CORE_ADDR bpaddr,
154                                             enum bptype bptype);
155
156 static void describe_other_breakpoints (struct gdbarch *,
157                                         struct program_space *, CORE_ADDR,
158                                         struct obj_section *, int);
159
160 static int watchpoint_locations_match (struct bp_location *loc1,
161                                        struct bp_location *loc2);
162
163 static int breakpoint_location_address_match (struct bp_location *bl,
164                                               const struct address_space *aspace,
165                                               CORE_ADDR addr);
166
167 static int breakpoint_location_address_range_overlap (struct bp_location *,
168                                                       const address_space *,
169                                                       CORE_ADDR, int);
170
171 static int remove_breakpoint (struct bp_location *);
172 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
173
174 static enum print_stop_action print_bp_stop_message (bpstat bs);
175
176 static int hw_breakpoint_used_count (void);
177
178 static int hw_watchpoint_use_count (struct breakpoint *);
179
180 static int hw_watchpoint_used_count_others (struct breakpoint *except,
181                                             enum bptype type,
182                                             int *other_type_used);
183
184 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
185                                     int count);
186
187 static void free_bp_location (struct bp_location *loc);
188 static void incref_bp_location (struct bp_location *loc);
189 static void decref_bp_location (struct bp_location **loc);
190
191 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
192
193 /* update_global_location_list's modes of operation wrt to whether to
194    insert locations now.  */
195 enum ugll_insert_mode
196 {
197   /* Don't insert any breakpoint locations into the inferior, only
198      remove already-inserted locations that no longer should be
199      inserted.  Functions that delete a breakpoint or breakpoints
200      should specify this mode, so that deleting a breakpoint doesn't
201      have the side effect of inserting the locations of other
202      breakpoints that are marked not-inserted, but should_be_inserted
203      returns true on them.
204
205      This behavior is useful is situations close to tear-down -- e.g.,
206      after an exec, while the target still has execution, but
207      breakpoint shadows of the previous executable image should *NOT*
208      be restored to the new image; or before detaching, where the
209      target still has execution and wants to delete breakpoints from
210      GDB's lists, and all breakpoints had already been removed from
211      the inferior.  */
212   UGLL_DONT_INSERT,
213
214   /* May insert breakpoints iff breakpoints_should_be_inserted_now
215      claims breakpoints should be inserted now.  */
216   UGLL_MAY_INSERT,
217
218   /* Insert locations now, irrespective of
219      breakpoints_should_be_inserted_now.  E.g., say all threads are
220      stopped right now, and the user did "continue".  We need to
221      insert breakpoints _before_ resuming the target, but
222      UGLL_MAY_INSERT wouldn't insert them, because
223      breakpoints_should_be_inserted_now returns false at that point,
224      as no thread is running yet.  */
225   UGLL_INSERT
226 };
227
228 static void update_global_location_list (enum ugll_insert_mode);
229
230 static void update_global_location_list_nothrow (enum ugll_insert_mode);
231
232 static int is_hardware_watchpoint (const struct breakpoint *bpt);
233
234 static void insert_breakpoint_locations (void);
235
236 static void trace_pass_command (const char *, int);
237
238 static void set_tracepoint_count (int num);
239
240 static int is_masked_watchpoint (const struct breakpoint *b);
241
242 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
243
244 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
245    otherwise.  */
246
247 static int strace_marker_p (struct breakpoint *b);
248
249 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
250    that are implemented on top of software or hardware breakpoints
251    (user breakpoints, internal and momentary breakpoints, etc.).  */
252 static struct breakpoint_ops bkpt_base_breakpoint_ops;
253
254 /* Internal breakpoints class type.  */
255 static struct breakpoint_ops internal_breakpoint_ops;
256
257 /* Momentary breakpoints class type.  */
258 static struct breakpoint_ops momentary_breakpoint_ops;
259
260 /* The breakpoint_ops structure to be used in regular user created
261    breakpoints.  */
262 struct breakpoint_ops bkpt_breakpoint_ops;
263
264 /* Breakpoints set on probes.  */
265 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
266
267 /* Dynamic printf class type.  */
268 struct breakpoint_ops dprintf_breakpoint_ops;
269
270 /* The style in which to perform a dynamic printf.  This is a user
271    option because different output options have different tradeoffs;
272    if GDB does the printing, there is better error handling if there
273    is a problem with any of the arguments, but using an inferior
274    function lets you have special-purpose printers and sending of
275    output to the same place as compiled-in print functions.  */
276
277 static const char dprintf_style_gdb[] = "gdb";
278 static const char dprintf_style_call[] = "call";
279 static const char dprintf_style_agent[] = "agent";
280 static const char *const dprintf_style_enums[] = {
281   dprintf_style_gdb,
282   dprintf_style_call,
283   dprintf_style_agent,
284   NULL
285 };
286 static const char *dprintf_style = dprintf_style_gdb;
287
288 /* The function to use for dynamic printf if the preferred style is to
289    call into the inferior.  The value is simply a string that is
290    copied into the command, so it can be anything that GDB can
291    evaluate to a callable address, not necessarily a function name.  */
292
293 static char *dprintf_function;
294
295 /* The channel to use for dynamic printf if the preferred style is to
296    call into the inferior; if a nonempty string, it will be passed to
297    the call as the first argument, with the format string as the
298    second.  As with the dprintf function, this can be anything that
299    GDB knows how to evaluate, so in addition to common choices like
300    "stderr", this could be an app-specific expression like
301    "mystreams[curlogger]".  */
302
303 static char *dprintf_channel;
304
305 /* True if dprintf commands should continue to operate even if GDB
306    has disconnected.  */
307 static int disconnected_dprintf = 1;
308
309 struct command_line *
310 breakpoint_commands (struct breakpoint *b)
311 {
312   return b->commands ? b->commands.get () : NULL;
313 }
314
315 /* Flag indicating that a command has proceeded the inferior past the
316    current breakpoint.  */
317
318 static int breakpoint_proceeded;
319
320 const char *
321 bpdisp_text (enum bpdisp disp)
322 {
323   /* NOTE: the following values are a part of MI protocol and
324      represent values of 'disp' field returned when inferior stops at
325      a breakpoint.  */
326   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
327
328   return bpdisps[(int) disp];
329 }
330
331 /* Prototypes for exported functions.  */
332 /* If FALSE, gdb will not use hardware support for watchpoints, even
333    if such is available.  */
334 static int can_use_hw_watchpoints;
335
336 static void
337 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
338                              struct cmd_list_element *c,
339                              const char *value)
340 {
341   fprintf_filtered (file,
342                     _("Debugger's willingness to use "
343                       "watchpoint hardware is %s.\n"),
344                     value);
345 }
346
347 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
348    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
349    for unrecognized breakpoint locations.
350    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
351 static enum auto_boolean pending_break_support;
352 static void
353 show_pending_break_support (struct ui_file *file, int from_tty,
354                             struct cmd_list_element *c,
355                             const char *value)
356 {
357   fprintf_filtered (file,
358                     _("Debugger's behavior regarding "
359                       "pending breakpoints is %s.\n"),
360                     value);
361 }
362
363 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
364    set with "break" but falling in read-only memory.
365    If 0, gdb will warn about such breakpoints, but won't automatically
366    use hardware breakpoints.  */
367 static int automatic_hardware_breakpoints;
368 static void
369 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
370                                      struct cmd_list_element *c,
371                                      const char *value)
372 {
373   fprintf_filtered (file,
374                     _("Automatic usage of hardware breakpoints is %s.\n"),
375                     value);
376 }
377
378 /* If on, GDB keeps breakpoints inserted even if the inferior is
379    stopped, and immediately inserts any new breakpoints as soon as
380    they're created.  If off (default), GDB keeps breakpoints off of
381    the target as long as possible.  That is, it delays inserting
382    breakpoints until the next resume, and removes them again when the
383    target fully stops.  This is a bit safer in case GDB crashes while
384    processing user input.  */
385 static int always_inserted_mode = 0;
386
387 static void
388 show_always_inserted_mode (struct ui_file *file, int from_tty,
389                      struct cmd_list_element *c, const char *value)
390 {
391   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
392                     value);
393 }
394
395 /* See breakpoint.h.  */
396
397 int
398 breakpoints_should_be_inserted_now (void)
399 {
400   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
401     {
402       /* If breakpoints are global, they should be inserted even if no
403          thread under gdb's control is running, or even if there are
404          no threads under GDB's control yet.  */
405       return 1;
406     }
407   else if (target_has_execution)
408     {
409       if (always_inserted_mode)
410         {
411           /* The user wants breakpoints inserted even if all threads
412              are stopped.  */
413           return 1;
414         }
415
416       if (threads_are_executing ())
417         return 1;
418
419       /* Don't remove breakpoints yet if, even though all threads are
420          stopped, we still have events to process.  */
421       for (thread_info *tp : all_non_exited_threads ())
422         if (tp->resumed
423             && tp->suspend.waitstatus_pending_p)
424           return 1;
425     }
426   return 0;
427 }
428
429 static const char condition_evaluation_both[] = "host or target";
430
431 /* Modes for breakpoint condition evaluation.  */
432 static const char condition_evaluation_auto[] = "auto";
433 static const char condition_evaluation_host[] = "host";
434 static const char condition_evaluation_target[] = "target";
435 static const char *const condition_evaluation_enums[] = {
436   condition_evaluation_auto,
437   condition_evaluation_host,
438   condition_evaluation_target,
439   NULL
440 };
441
442 /* Global that holds the current mode for breakpoint condition evaluation.  */
443 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
444
445 /* Global that we use to display information to the user (gets its value from
446    condition_evaluation_mode_1.  */
447 static const char *condition_evaluation_mode = condition_evaluation_auto;
448
449 /* Translate a condition evaluation mode MODE into either "host"
450    or "target".  This is used mostly to translate from "auto" to the
451    real setting that is being used.  It returns the translated
452    evaluation mode.  */
453
454 static const char *
455 translate_condition_evaluation_mode (const char *mode)
456 {
457   if (mode == condition_evaluation_auto)
458     {
459       if (target_supports_evaluation_of_breakpoint_conditions ())
460         return condition_evaluation_target;
461       else
462         return condition_evaluation_host;
463     }
464   else
465     return mode;
466 }
467
468 /* Discovers what condition_evaluation_auto translates to.  */
469
470 static const char *
471 breakpoint_condition_evaluation_mode (void)
472 {
473   return translate_condition_evaluation_mode (condition_evaluation_mode);
474 }
475
476 /* Return true if GDB should evaluate breakpoint conditions or false
477    otherwise.  */
478
479 static int
480 gdb_evaluates_breakpoint_condition_p (void)
481 {
482   const char *mode = breakpoint_condition_evaluation_mode ();
483
484   return (mode == condition_evaluation_host);
485 }
486
487 /* Are we executing breakpoint commands?  */
488 static int executing_breakpoint_commands;
489
490 /* Are overlay event breakpoints enabled? */
491 static int overlay_events_enabled;
492
493 /* See description in breakpoint.h. */
494 int target_exact_watchpoints = 0;
495
496 /* Walk the following statement or block through all breakpoints.
497    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
498    current breakpoint.  */
499
500 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
501
502 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
503         for (B = breakpoint_chain;      \
504              B ? (TMP=B->next, 1): 0;   \
505              B = TMP)
506
507 /* Similar iterator for the low-level breakpoints.  SAFE variant is
508    not provided so update_global_location_list must not be called
509    while executing the block of ALL_BP_LOCATIONS.  */
510
511 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
512         for (BP_TMP = bp_locations;                                     \
513              BP_TMP < bp_locations + bp_locations_count && (B = *BP_TMP);\
514              BP_TMP++)
515
516 /* Iterates through locations with address ADDRESS for the currently selected
517    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
518    to where the loop should start from.
519    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
520    appropriate location to start with.  */
521
522 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
523         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
524              BP_LOCP_TMP = BP_LOCP_START;                               \
525              BP_LOCP_START                                              \
526              && (BP_LOCP_TMP < bp_locations + bp_locations_count        \
527              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
528              BP_LOCP_TMP++)
529
530 /* Iterator for tracepoints only.  */
531
532 #define ALL_TRACEPOINTS(B)  \
533   for (B = breakpoint_chain; B; B = B->next)  \
534     if (is_tracepoint (B))
535
536 /* Chains of all breakpoints defined.  */
537
538 struct breakpoint *breakpoint_chain;
539
540 /* Array is sorted by bp_locations_compare - primarily by the ADDRESS.  */
541
542 static struct bp_location **bp_locations;
543
544 /* Number of elements of BP_LOCATIONS.  */
545
546 static unsigned bp_locations_count;
547
548 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
549    ADDRESS for the current elements of BP_LOCATIONS which get a valid
550    result from bp_location_has_shadow.  You can use it for roughly
551    limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
552    an address you need to read.  */
553
554 static CORE_ADDR bp_locations_placed_address_before_address_max;
555
556 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
557    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
558    BP_LOCATIONS which get a valid result from bp_location_has_shadow.
559    You can use it for roughly limiting the subrange of BP_LOCATIONS to
560    scan for shadow bytes for an address you need to read.  */
561
562 static CORE_ADDR bp_locations_shadow_len_after_address_max;
563
564 /* The locations that no longer correspond to any breakpoint, unlinked
565    from the bp_locations array, but for which a hit may still be
566    reported by a target.  */
567 static std::vector<bp_location *> moribund_locations;
568
569 /* Number of last breakpoint made.  */
570
571 static int breakpoint_count;
572
573 /* The value of `breakpoint_count' before the last command that
574    created breakpoints.  If the last (break-like) command created more
575    than one breakpoint, then the difference between BREAKPOINT_COUNT
576    and PREV_BREAKPOINT_COUNT is more than one.  */
577 static int prev_breakpoint_count;
578
579 /* Number of last tracepoint made.  */
580
581 static int tracepoint_count;
582
583 static struct cmd_list_element *breakpoint_set_cmdlist;
584 static struct cmd_list_element *breakpoint_show_cmdlist;
585 struct cmd_list_element *save_cmdlist;
586
587 /* See declaration at breakpoint.h.  */
588
589 struct breakpoint *
590 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
591                     void *user_data)
592 {
593   struct breakpoint *b = NULL;
594
595   ALL_BREAKPOINTS (b)
596     {
597       if (func (b, user_data) != 0)
598         break;
599     }
600
601   return b;
602 }
603
604 /* Return whether a breakpoint is an active enabled breakpoint.  */
605 static int
606 breakpoint_enabled (struct breakpoint *b)
607 {
608   return (b->enable_state == bp_enabled);
609 }
610
611 /* Set breakpoint count to NUM.  */
612
613 static void
614 set_breakpoint_count (int num)
615 {
616   prev_breakpoint_count = breakpoint_count;
617   breakpoint_count = num;
618   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
619 }
620
621 /* Used by `start_rbreak_breakpoints' below, to record the current
622    breakpoint count before "rbreak" creates any breakpoint.  */
623 static int rbreak_start_breakpoint_count;
624
625 /* Called at the start an "rbreak" command to record the first
626    breakpoint made.  */
627
628 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
629 {
630   rbreak_start_breakpoint_count = breakpoint_count;
631 }
632
633 /* Called at the end of an "rbreak" command to record the last
634    breakpoint made.  */
635
636 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
637 {
638   prev_breakpoint_count = rbreak_start_breakpoint_count;
639 }
640
641 /* Used in run_command to zero the hit count when a new run starts.  */
642
643 void
644 clear_breakpoint_hit_counts (void)
645 {
646   struct breakpoint *b;
647
648   ALL_BREAKPOINTS (b)
649     b->hit_count = 0;
650 }
651
652 \f
653 /* Return the breakpoint with the specified number, or NULL
654    if the number does not refer to an existing breakpoint.  */
655
656 struct breakpoint *
657 get_breakpoint (int num)
658 {
659   struct breakpoint *b;
660
661   ALL_BREAKPOINTS (b)
662     if (b->number == num)
663       return b;
664   
665   return NULL;
666 }
667
668 \f
669
670 /* Mark locations as "conditions have changed" in case the target supports
671    evaluating conditions on its side.  */
672
673 static void
674 mark_breakpoint_modified (struct breakpoint *b)
675 {
676   struct bp_location *loc;
677
678   /* This is only meaningful if the target is
679      evaluating conditions and if the user has
680      opted for condition evaluation on the target's
681      side.  */
682   if (gdb_evaluates_breakpoint_condition_p ()
683       || !target_supports_evaluation_of_breakpoint_conditions ())
684     return;
685
686   if (!is_breakpoint (b))
687     return;
688
689   for (loc = b->loc; loc; loc = loc->next)
690     loc->condition_changed = condition_modified;
691 }
692
693 /* Mark location as "conditions have changed" in case the target supports
694    evaluating conditions on its side.  */
695
696 static void
697 mark_breakpoint_location_modified (struct bp_location *loc)
698 {
699   /* This is only meaningful if the target is
700      evaluating conditions and if the user has
701      opted for condition evaluation on the target's
702      side.  */
703   if (gdb_evaluates_breakpoint_condition_p ()
704       || !target_supports_evaluation_of_breakpoint_conditions ())
705
706     return;
707
708   if (!is_breakpoint (loc->owner))
709     return;
710
711   loc->condition_changed = condition_modified;
712 }
713
714 /* Sets the condition-evaluation mode using the static global
715    condition_evaluation_mode.  */
716
717 static void
718 set_condition_evaluation_mode (const char *args, int from_tty,
719                                struct cmd_list_element *c)
720 {
721   const char *old_mode, *new_mode;
722
723   if ((condition_evaluation_mode_1 == condition_evaluation_target)
724       && !target_supports_evaluation_of_breakpoint_conditions ())
725     {
726       condition_evaluation_mode_1 = condition_evaluation_mode;
727       warning (_("Target does not support breakpoint condition evaluation.\n"
728                  "Using host evaluation mode instead."));
729       return;
730     }
731
732   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
733   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
734
735   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
736      settings was "auto".  */
737   condition_evaluation_mode = condition_evaluation_mode_1;
738
739   /* Only update the mode if the user picked a different one.  */
740   if (new_mode != old_mode)
741     {
742       struct bp_location *loc, **loc_tmp;
743       /* If the user switched to a different evaluation mode, we
744          need to synch the changes with the target as follows:
745
746          "host" -> "target": Send all (valid) conditions to the target.
747          "target" -> "host": Remove all the conditions from the target.
748       */
749
750       if (new_mode == condition_evaluation_target)
751         {
752           /* Mark everything modified and synch conditions with the
753              target.  */
754           ALL_BP_LOCATIONS (loc, loc_tmp)
755             mark_breakpoint_location_modified (loc);
756         }
757       else
758         {
759           /* Manually mark non-duplicate locations to synch conditions
760              with the target.  We do this to remove all the conditions the
761              target knows about.  */
762           ALL_BP_LOCATIONS (loc, loc_tmp)
763             if (is_breakpoint (loc->owner) && loc->inserted)
764               loc->needs_update = 1;
765         }
766
767       /* Do the update.  */
768       update_global_location_list (UGLL_MAY_INSERT);
769     }
770
771   return;
772 }
773
774 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
775    what "auto" is translating to.  */
776
777 static void
778 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
779                                 struct cmd_list_element *c, const char *value)
780 {
781   if (condition_evaluation_mode == condition_evaluation_auto)
782     fprintf_filtered (file,
783                       _("Breakpoint condition evaluation "
784                         "mode is %s (currently %s).\n"),
785                       value,
786                       breakpoint_condition_evaluation_mode ());
787   else
788     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
789                       value);
790 }
791
792 /* A comparison function for bp_location AP and BP that is used by
793    bsearch.  This comparison function only cares about addresses, unlike
794    the more general bp_locations_compare function.  */
795
796 static int
797 bp_locations_compare_addrs (const void *ap, const void *bp)
798 {
799   const struct bp_location *a = *(const struct bp_location **) ap;
800   const struct bp_location *b = *(const struct bp_location **) bp;
801
802   if (a->address == b->address)
803     return 0;
804   else
805     return ((a->address > b->address) - (a->address < b->address));
806 }
807
808 /* Helper function to skip all bp_locations with addresses
809    less than ADDRESS.  It returns the first bp_location that
810    is greater than or equal to ADDRESS.  If none is found, just
811    return NULL.  */
812
813 static struct bp_location **
814 get_first_locp_gte_addr (CORE_ADDR address)
815 {
816   struct bp_location dummy_loc;
817   struct bp_location *dummy_locp = &dummy_loc;
818   struct bp_location **locp_found = NULL;
819
820   /* Initialize the dummy location's address field.  */
821   dummy_loc.address = address;
822
823   /* Find a close match to the first location at ADDRESS.  */
824   locp_found = ((struct bp_location **)
825                 bsearch (&dummy_locp, bp_locations, bp_locations_count,
826                          sizeof (struct bp_location **),
827                          bp_locations_compare_addrs));
828
829   /* Nothing was found, nothing left to do.  */
830   if (locp_found == NULL)
831     return NULL;
832
833   /* We may have found a location that is at ADDRESS but is not the first in the
834      location's list.  Go backwards (if possible) and locate the first one.  */
835   while ((locp_found - 1) >= bp_locations
836          && (*(locp_found - 1))->address == address)
837     locp_found--;
838
839   return locp_found;
840 }
841
842 void
843 set_breakpoint_condition (struct breakpoint *b, const char *exp,
844                           int from_tty)
845 {
846   xfree (b->cond_string);
847   b->cond_string = NULL;
848
849   if (is_watchpoint (b))
850     {
851       struct watchpoint *w = (struct watchpoint *) b;
852
853       w->cond_exp.reset ();
854     }
855   else
856     {
857       struct bp_location *loc;
858
859       for (loc = b->loc; loc; loc = loc->next)
860         {
861           loc->cond.reset ();
862
863           /* No need to free the condition agent expression
864              bytecode (if we have one).  We will handle this
865              when we go through update_global_location_list.  */
866         }
867     }
868
869   if (*exp == 0)
870     {
871       if (from_tty)
872         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
873     }
874   else
875     {
876       const char *arg = exp;
877
878       /* I don't know if it matters whether this is the string the user
879          typed in or the decompiled expression.  */
880       b->cond_string = xstrdup (arg);
881       b->condition_not_parsed = 0;
882
883       if (is_watchpoint (b))
884         {
885           struct watchpoint *w = (struct watchpoint *) b;
886
887           innermost_block_tracker tracker;
888           arg = exp;
889           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
890           if (*arg)
891             error (_("Junk at end of expression"));
892           w->cond_exp_valid_block = tracker.block ();
893         }
894       else
895         {
896           struct bp_location *loc;
897
898           for (loc = b->loc; loc; loc = loc->next)
899             {
900               arg = exp;
901               loc->cond =
902                 parse_exp_1 (&arg, loc->address,
903                              block_for_pc (loc->address), 0);
904               if (*arg)
905                 error (_("Junk at end of expression"));
906             }
907         }
908     }
909   mark_breakpoint_modified (b);
910
911   gdb::observers::breakpoint_modified.notify (b);
912 }
913
914 /* Completion for the "condition" command.  */
915
916 static void
917 condition_completer (struct cmd_list_element *cmd,
918                      completion_tracker &tracker,
919                      const char *text, const char *word)
920 {
921   const char *space;
922
923   text = skip_spaces (text);
924   space = skip_to_space (text);
925   if (*space == '\0')
926     {
927       int len;
928       struct breakpoint *b;
929
930       if (text[0] == '$')
931         {
932           /* We don't support completion of history indices.  */
933           if (!isdigit (text[1]))
934             complete_internalvar (tracker, &text[1]);
935           return;
936         }
937
938       /* We're completing the breakpoint number.  */
939       len = strlen (text);
940
941       ALL_BREAKPOINTS (b)
942         {
943           char number[50];
944
945           xsnprintf (number, sizeof (number), "%d", b->number);
946
947           if (strncmp (number, text, len) == 0)
948             {
949               gdb::unique_xmalloc_ptr<char> copy (xstrdup (number));
950               tracker.add_completion (std::move (copy));
951             }
952         }
953
954       return;
955     }
956
957   /* We're completing the expression part.  */
958   text = skip_spaces (space);
959   expression_completer (cmd, tracker, text, word);
960 }
961
962 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
963
964 static void
965 condition_command (const char *arg, int from_tty)
966 {
967   struct breakpoint *b;
968   const char *p;
969   int bnum;
970
971   if (arg == 0)
972     error_no_arg (_("breakpoint number"));
973
974   p = arg;
975   bnum = get_number (&p);
976   if (bnum == 0)
977     error (_("Bad breakpoint argument: '%s'"), arg);
978
979   ALL_BREAKPOINTS (b)
980     if (b->number == bnum)
981       {
982         /* Check if this breakpoint has a "stop" method implemented in an
983            extension language.  This method and conditions entered into GDB
984            from the CLI are mutually exclusive.  */
985         const struct extension_language_defn *extlang
986           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
987
988         if (extlang != NULL)
989           {
990             error (_("Only one stop condition allowed.  There is currently"
991                      " a %s stop condition defined for this breakpoint."),
992                    ext_lang_capitalized_name (extlang));
993           }
994         set_breakpoint_condition (b, p, from_tty);
995
996         if (is_breakpoint (b))
997           update_global_location_list (UGLL_MAY_INSERT);
998
999         return;
1000       }
1001
1002   error (_("No breakpoint number %d."), bnum);
1003 }
1004
1005 /* Check that COMMAND do not contain commands that are suitable
1006    only for tracepoints and not suitable for ordinary breakpoints.
1007    Throw if any such commands is found.  */
1008
1009 static void
1010 check_no_tracepoint_commands (struct command_line *commands)
1011 {
1012   struct command_line *c;
1013
1014   for (c = commands; c; c = c->next)
1015     {
1016       if (c->control_type == while_stepping_control)
1017         error (_("The 'while-stepping' command can "
1018                  "only be used for tracepoints"));
1019
1020       check_no_tracepoint_commands (c->body_list_0.get ());
1021       check_no_tracepoint_commands (c->body_list_1.get ());
1022
1023       /* Not that command parsing removes leading whitespace and comment
1024          lines and also empty lines.  So, we only need to check for
1025          command directly.  */
1026       if (strstr (c->line, "collect ") == c->line)
1027         error (_("The 'collect' command can only be used for tracepoints"));
1028
1029       if (strstr (c->line, "teval ") == c->line)
1030         error (_("The 'teval' command can only be used for tracepoints"));
1031     }
1032 }
1033
1034 struct longjmp_breakpoint : public breakpoint
1035 {
1036   ~longjmp_breakpoint () override;
1037 };
1038
1039 /* Encapsulate tests for different types of tracepoints.  */
1040
1041 static bool
1042 is_tracepoint_type (bptype type)
1043 {
1044   return (type == bp_tracepoint
1045           || type == bp_fast_tracepoint
1046           || type == bp_static_tracepoint);
1047 }
1048
1049 static bool
1050 is_longjmp_type (bptype type)
1051 {
1052   return type == bp_longjmp || type == bp_exception;
1053 }
1054
1055 int
1056 is_tracepoint (const struct breakpoint *b)
1057 {
1058   return is_tracepoint_type (b->type);
1059 }
1060
1061 /* Factory function to create an appropriate instance of breakpoint given
1062    TYPE.  */
1063
1064 static std::unique_ptr<breakpoint>
1065 new_breakpoint_from_type (bptype type)
1066 {
1067   breakpoint *b;
1068
1069   if (is_tracepoint_type (type))
1070     b = new tracepoint ();
1071   else if (is_longjmp_type (type))
1072     b = new longjmp_breakpoint ();
1073   else
1074     b = new breakpoint ();
1075
1076   return std::unique_ptr<breakpoint> (b);
1077 }
1078
1079 /* A helper function that validates that COMMANDS are valid for a
1080    breakpoint.  This function will throw an exception if a problem is
1081    found.  */
1082
1083 static void
1084 validate_commands_for_breakpoint (struct breakpoint *b,
1085                                   struct command_line *commands)
1086 {
1087   if (is_tracepoint (b))
1088     {
1089       struct tracepoint *t = (struct tracepoint *) b;
1090       struct command_line *c;
1091       struct command_line *while_stepping = 0;
1092
1093       /* Reset the while-stepping step count.  The previous commands
1094          might have included a while-stepping action, while the new
1095          ones might not.  */
1096       t->step_count = 0;
1097
1098       /* We need to verify that each top-level element of commands is
1099          valid for tracepoints, that there's at most one
1100          while-stepping element, and that the while-stepping's body
1101          has valid tracing commands excluding nested while-stepping.
1102          We also need to validate the tracepoint action line in the
1103          context of the tracepoint --- validate_actionline actually
1104          has side effects, like setting the tracepoint's
1105          while-stepping STEP_COUNT, in addition to checking if the
1106          collect/teval actions parse and make sense in the
1107          tracepoint's context.  */
1108       for (c = commands; c; c = c->next)
1109         {
1110           if (c->control_type == while_stepping_control)
1111             {
1112               if (b->type == bp_fast_tracepoint)
1113                 error (_("The 'while-stepping' command "
1114                          "cannot be used for fast tracepoint"));
1115               else if (b->type == bp_static_tracepoint)
1116                 error (_("The 'while-stepping' command "
1117                          "cannot be used for static tracepoint"));
1118
1119               if (while_stepping)
1120                 error (_("The 'while-stepping' command "
1121                          "can be used only once"));
1122               else
1123                 while_stepping = c;
1124             }
1125
1126           validate_actionline (c->line, b);
1127         }
1128       if (while_stepping)
1129         {
1130           struct command_line *c2;
1131
1132           gdb_assert (while_stepping->body_list_1 == nullptr);
1133           c2 = while_stepping->body_list_0.get ();
1134           for (; c2; c2 = c2->next)
1135             {
1136               if (c2->control_type == while_stepping_control)
1137                 error (_("The 'while-stepping' command cannot be nested"));
1138             }
1139         }
1140     }
1141   else
1142     {
1143       check_no_tracepoint_commands (commands);
1144     }
1145 }
1146
1147 /* Return a vector of all the static tracepoints set at ADDR.  The
1148    caller is responsible for releasing the vector.  */
1149
1150 std::vector<breakpoint *>
1151 static_tracepoints_here (CORE_ADDR addr)
1152 {
1153   struct breakpoint *b;
1154   std::vector<breakpoint *> found;
1155   struct bp_location *loc;
1156
1157   ALL_BREAKPOINTS (b)
1158     if (b->type == bp_static_tracepoint)
1159       {
1160         for (loc = b->loc; loc; loc = loc->next)
1161           if (loc->address == addr)
1162             found.push_back (b);
1163       }
1164
1165   return found;
1166 }
1167
1168 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1169    validate that only allowed commands are included.  */
1170
1171 void
1172 breakpoint_set_commands (struct breakpoint *b, 
1173                          counted_command_line &&commands)
1174 {
1175   validate_commands_for_breakpoint (b, commands.get ());
1176
1177   b->commands = std::move (commands);
1178   gdb::observers::breakpoint_modified.notify (b);
1179 }
1180
1181 /* Set the internal `silent' flag on the breakpoint.  Note that this
1182    is not the same as the "silent" that may appear in the breakpoint's
1183    commands.  */
1184
1185 void
1186 breakpoint_set_silent (struct breakpoint *b, int silent)
1187 {
1188   int old_silent = b->silent;
1189
1190   b->silent = silent;
1191   if (old_silent != silent)
1192     gdb::observers::breakpoint_modified.notify (b);
1193 }
1194
1195 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1196    breakpoint work for any thread.  */
1197
1198 void
1199 breakpoint_set_thread (struct breakpoint *b, int thread)
1200 {
1201   int old_thread = b->thread;
1202
1203   b->thread = thread;
1204   if (old_thread != thread)
1205     gdb::observers::breakpoint_modified.notify (b);
1206 }
1207
1208 /* Set the task for this breakpoint.  If TASK is 0, make the
1209    breakpoint work for any task.  */
1210
1211 void
1212 breakpoint_set_task (struct breakpoint *b, int task)
1213 {
1214   int old_task = b->task;
1215
1216   b->task = task;
1217   if (old_task != task)
1218     gdb::observers::breakpoint_modified.notify (b);
1219 }
1220
1221 static void
1222 commands_command_1 (const char *arg, int from_tty,
1223                     struct command_line *control)
1224 {
1225   counted_command_line cmd;
1226   /* cmd_read will be true once we have read cmd.  Note that cmd might still be
1227      NULL after the call to read_command_lines if the user provides an empty
1228      list of command by just typing "end".  */
1229   bool cmd_read = false;
1230
1231   std::string new_arg;
1232
1233   if (arg == NULL || !*arg)
1234     {
1235       if (breakpoint_count - prev_breakpoint_count > 1)
1236         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1237                                  breakpoint_count);
1238       else if (breakpoint_count > 0)
1239         new_arg = string_printf ("%d", breakpoint_count);
1240       arg = new_arg.c_str ();
1241     }
1242
1243   map_breakpoint_numbers
1244     (arg, [&] (breakpoint *b)
1245      {
1246        if (!cmd_read)
1247          {
1248            gdb_assert (cmd == NULL);
1249            if (control != NULL)
1250              cmd = control->body_list_0;
1251            else
1252              {
1253                std::string str
1254                  = string_printf (_("Type commands for breakpoint(s) "
1255                                     "%s, one per line."),
1256                                   arg);
1257
1258                auto do_validate = [=] (const char *line)
1259                                   {
1260                                     validate_actionline (line, b);
1261                                   };
1262                gdb::function_view<void (const char *)> validator;
1263                if (is_tracepoint (b))
1264                  validator = do_validate;
1265
1266                cmd = read_command_lines (str.c_str (), from_tty, 1, validator);
1267              }
1268            cmd_read = true;
1269          }
1270
1271        /* If a breakpoint was on the list more than once, we don't need to
1272           do anything.  */
1273        if (b->commands != cmd)
1274          {
1275            validate_commands_for_breakpoint (b, cmd.get ());
1276            b->commands = cmd;
1277            gdb::observers::breakpoint_modified.notify (b);
1278          }
1279      });
1280 }
1281
1282 static void
1283 commands_command (const char *arg, int from_tty)
1284 {
1285   commands_command_1 (arg, from_tty, NULL);
1286 }
1287
1288 /* Like commands_command, but instead of reading the commands from
1289    input stream, takes them from an already parsed command structure.
1290
1291    This is used by cli-script.c to DTRT with breakpoint commands
1292    that are part of if and while bodies.  */
1293 enum command_control_type
1294 commands_from_control_command (const char *arg, struct command_line *cmd)
1295 {
1296   commands_command_1 (arg, 0, cmd);
1297   return simple_control;
1298 }
1299
1300 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1301
1302 static int
1303 bp_location_has_shadow (struct bp_location *bl)
1304 {
1305   if (bl->loc_type != bp_loc_software_breakpoint)
1306     return 0;
1307   if (!bl->inserted)
1308     return 0;
1309   if (bl->target_info.shadow_len == 0)
1310     /* BL isn't valid, or doesn't shadow memory.  */
1311     return 0;
1312   return 1;
1313 }
1314
1315 /* Update BUF, which is LEN bytes read from the target address
1316    MEMADDR, by replacing a memory breakpoint with its shadowed
1317    contents.
1318
1319    If READBUF is not NULL, this buffer must not overlap with the of
1320    the breakpoint location's shadow_contents buffer.  Otherwise, a
1321    failed assertion internal error will be raised.  */
1322
1323 static void
1324 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1325                             const gdb_byte *writebuf_org,
1326                             ULONGEST memaddr, LONGEST len,
1327                             struct bp_target_info *target_info,
1328                             struct gdbarch *gdbarch)
1329 {
1330   /* Now do full processing of the found relevant range of elements.  */
1331   CORE_ADDR bp_addr = 0;
1332   int bp_size = 0;
1333   int bptoffset = 0;
1334
1335   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1336                                  current_program_space->aspace, 0))
1337     {
1338       /* The breakpoint is inserted in a different address space.  */
1339       return;
1340     }
1341
1342   /* Addresses and length of the part of the breakpoint that
1343      we need to copy.  */
1344   bp_addr = target_info->placed_address;
1345   bp_size = target_info->shadow_len;
1346
1347   if (bp_addr + bp_size <= memaddr)
1348     {
1349       /* The breakpoint is entirely before the chunk of memory we are
1350          reading.  */
1351       return;
1352     }
1353
1354   if (bp_addr >= memaddr + len)
1355     {
1356       /* The breakpoint is entirely after the chunk of memory we are
1357          reading.  */
1358       return;
1359     }
1360
1361   /* Offset within shadow_contents.  */
1362   if (bp_addr < memaddr)
1363     {
1364       /* Only copy the second part of the breakpoint.  */
1365       bp_size -= memaddr - bp_addr;
1366       bptoffset = memaddr - bp_addr;
1367       bp_addr = memaddr;
1368     }
1369
1370   if (bp_addr + bp_size > memaddr + len)
1371     {
1372       /* Only copy the first part of the breakpoint.  */
1373       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1374     }
1375
1376   if (readbuf != NULL)
1377     {
1378       /* Verify that the readbuf buffer does not overlap with the
1379          shadow_contents buffer.  */
1380       gdb_assert (target_info->shadow_contents >= readbuf + len
1381                   || readbuf >= (target_info->shadow_contents
1382                                  + target_info->shadow_len));
1383
1384       /* Update the read buffer with this inserted breakpoint's
1385          shadow.  */
1386       memcpy (readbuf + bp_addr - memaddr,
1387               target_info->shadow_contents + bptoffset, bp_size);
1388     }
1389   else
1390     {
1391       const unsigned char *bp;
1392       CORE_ADDR addr = target_info->reqstd_address;
1393       int placed_size;
1394
1395       /* Update the shadow with what we want to write to memory.  */
1396       memcpy (target_info->shadow_contents + bptoffset,
1397               writebuf_org + bp_addr - memaddr, bp_size);
1398
1399       /* Determine appropriate breakpoint contents and size for this
1400          address.  */
1401       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1402
1403       /* Update the final write buffer with this inserted
1404          breakpoint's INSN.  */
1405       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1406     }
1407 }
1408
1409 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1410    by replacing any memory breakpoints with their shadowed contents.
1411
1412    If READBUF is not NULL, this buffer must not overlap with any of
1413    the breakpoint location's shadow_contents buffers.  Otherwise,
1414    a failed assertion internal error will be raised.
1415
1416    The range of shadowed area by each bp_location is:
1417      bl->address - bp_locations_placed_address_before_address_max
1418      up to bl->address + bp_locations_shadow_len_after_address_max
1419    The range we were requested to resolve shadows for is:
1420      memaddr ... memaddr + len
1421    Thus the safe cutoff boundaries for performance optimization are
1422      memaddr + len <= (bl->address
1423                        - bp_locations_placed_address_before_address_max)
1424    and:
1425      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1426
1427 void
1428 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1429                         const gdb_byte *writebuf_org,
1430                         ULONGEST memaddr, LONGEST len)
1431 {
1432   /* Left boundary, right boundary and median element of our binary
1433      search.  */
1434   unsigned bc_l, bc_r, bc;
1435
1436   /* Find BC_L which is a leftmost element which may affect BUF
1437      content.  It is safe to report lower value but a failure to
1438      report higher one.  */
1439
1440   bc_l = 0;
1441   bc_r = bp_locations_count;
1442   while (bc_l + 1 < bc_r)
1443     {
1444       struct bp_location *bl;
1445
1446       bc = (bc_l + bc_r) / 2;
1447       bl = bp_locations[bc];
1448
1449       /* Check first BL->ADDRESS will not overflow due to the added
1450          constant.  Then advance the left boundary only if we are sure
1451          the BC element can in no way affect the BUF content (MEMADDR
1452          to MEMADDR + LEN range).
1453
1454          Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1455          offset so that we cannot miss a breakpoint with its shadow
1456          range tail still reaching MEMADDR.  */
1457
1458       if ((bl->address + bp_locations_shadow_len_after_address_max
1459            >= bl->address)
1460           && (bl->address + bp_locations_shadow_len_after_address_max
1461               <= memaddr))
1462         bc_l = bc;
1463       else
1464         bc_r = bc;
1465     }
1466
1467   /* Due to the binary search above, we need to make sure we pick the
1468      first location that's at BC_L's address.  E.g., if there are
1469      multiple locations at the same address, BC_L may end up pointing
1470      at a duplicate location, and miss the "master"/"inserted"
1471      location.  Say, given locations L1, L2 and L3 at addresses A and
1472      B:
1473
1474       L1@A, L2@A, L3@B, ...
1475
1476      BC_L could end up pointing at location L2, while the "master"
1477      location could be L1.  Since the `loc->inserted' flag is only set
1478      on "master" locations, we'd forget to restore the shadow of L1
1479      and L2.  */
1480   while (bc_l > 0
1481          && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1482     bc_l--;
1483
1484   /* Now do full processing of the found relevant range of elements.  */
1485
1486   for (bc = bc_l; bc < bp_locations_count; bc++)
1487   {
1488     struct bp_location *bl = bp_locations[bc];
1489
1490     /* bp_location array has BL->OWNER always non-NULL.  */
1491     if (bl->owner->type == bp_none)
1492       warning (_("reading through apparently deleted breakpoint #%d?"),
1493                bl->owner->number);
1494
1495     /* Performance optimization: any further element can no longer affect BUF
1496        content.  */
1497
1498     if (bl->address >= bp_locations_placed_address_before_address_max
1499         && memaddr + len <= (bl->address
1500                              - bp_locations_placed_address_before_address_max))
1501       break;
1502
1503     if (!bp_location_has_shadow (bl))
1504       continue;
1505
1506     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1507                                 memaddr, len, &bl->target_info, bl->gdbarch);
1508   }
1509 }
1510
1511 \f
1512
1513 /* Return true if BPT is either a software breakpoint or a hardware
1514    breakpoint.  */
1515
1516 int
1517 is_breakpoint (const struct breakpoint *bpt)
1518 {
1519   return (bpt->type == bp_breakpoint
1520           || bpt->type == bp_hardware_breakpoint
1521           || bpt->type == bp_dprintf);
1522 }
1523
1524 /* Return true if BPT is of any hardware watchpoint kind.  */
1525
1526 static int
1527 is_hardware_watchpoint (const struct breakpoint *bpt)
1528 {
1529   return (bpt->type == bp_hardware_watchpoint
1530           || bpt->type == bp_read_watchpoint
1531           || bpt->type == bp_access_watchpoint);
1532 }
1533
1534 /* Return true if BPT is of any watchpoint kind, hardware or
1535    software.  */
1536
1537 int
1538 is_watchpoint (const struct breakpoint *bpt)
1539 {
1540   return (is_hardware_watchpoint (bpt)
1541           || bpt->type == bp_watchpoint);
1542 }
1543
1544 /* Returns true if the current thread and its running state are safe
1545    to evaluate or update watchpoint B.  Watchpoints on local
1546    expressions need to be evaluated in the context of the thread that
1547    was current when the watchpoint was created, and, that thread needs
1548    to be stopped to be able to select the correct frame context.
1549    Watchpoints on global expressions can be evaluated on any thread,
1550    and in any state.  It is presently left to the target allowing
1551    memory accesses when threads are running.  */
1552
1553 static int
1554 watchpoint_in_thread_scope (struct watchpoint *b)
1555 {
1556   return (b->pspace == current_program_space
1557           && (b->watchpoint_thread == null_ptid
1558               || (inferior_ptid == b->watchpoint_thread
1559                   && !inferior_thread ()->executing)));
1560 }
1561
1562 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1563    associated bp_watchpoint_scope breakpoint.  */
1564
1565 static void
1566 watchpoint_del_at_next_stop (struct watchpoint *w)
1567 {
1568   if (w->related_breakpoint != w)
1569     {
1570       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1571       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1572       w->related_breakpoint->disposition = disp_del_at_next_stop;
1573       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1574       w->related_breakpoint = w;
1575     }
1576   w->disposition = disp_del_at_next_stop;
1577 }
1578
1579 /* Extract a bitfield value from value VAL using the bit parameters contained in
1580    watchpoint W.  */
1581
1582 static struct value *
1583 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1584 {
1585   struct value *bit_val;
1586
1587   if (val == NULL)
1588     return NULL;
1589
1590   bit_val = allocate_value (value_type (val));
1591
1592   unpack_value_bitfield (bit_val,
1593                          w->val_bitpos,
1594                          w->val_bitsize,
1595                          value_contents_for_printing (val),
1596                          value_offset (val),
1597                          val);
1598
1599   return bit_val;
1600 }
1601
1602 /* Allocate a dummy location and add it to B, which must be a software
1603    watchpoint.  This is required because even if a software watchpoint
1604    is not watching any memory, bpstat_stop_status requires a location
1605    to be able to report stops.  */
1606
1607 static void
1608 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1609                                             struct program_space *pspace)
1610 {
1611   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1612
1613   b->loc = allocate_bp_location (b);
1614   b->loc->pspace = pspace;
1615   b->loc->address = -1;
1616   b->loc->length = -1;
1617 }
1618
1619 /* Returns true if B is a software watchpoint that is not watching any
1620    memory (e.g., "watch $pc").  */
1621
1622 static int
1623 is_no_memory_software_watchpoint (struct breakpoint *b)
1624 {
1625   return (b->type == bp_watchpoint
1626           && b->loc != NULL
1627           && b->loc->next == NULL
1628           && b->loc->address == -1
1629           && b->loc->length == -1);
1630 }
1631
1632 /* Assuming that B is a watchpoint:
1633    - Reparse watchpoint expression, if REPARSE is non-zero
1634    - Evaluate expression and store the result in B->val
1635    - Evaluate the condition if there is one, and store the result
1636      in b->loc->cond.
1637    - Update the list of values that must be watched in B->loc.
1638
1639    If the watchpoint disposition is disp_del_at_next_stop, then do
1640    nothing.  If this is local watchpoint that is out of scope, delete
1641    it.
1642
1643    Even with `set breakpoint always-inserted on' the watchpoints are
1644    removed + inserted on each stop here.  Normal breakpoints must
1645    never be removed because they might be missed by a running thread
1646    when debugging in non-stop mode.  On the other hand, hardware
1647    watchpoints (is_hardware_watchpoint; processed here) are specific
1648    to each LWP since they are stored in each LWP's hardware debug
1649    registers.  Therefore, such LWP must be stopped first in order to
1650    be able to modify its hardware watchpoints.
1651
1652    Hardware watchpoints must be reset exactly once after being
1653    presented to the user.  It cannot be done sooner, because it would
1654    reset the data used to present the watchpoint hit to the user.  And
1655    it must not be done later because it could display the same single
1656    watchpoint hit during multiple GDB stops.  Note that the latter is
1657    relevant only to the hardware watchpoint types bp_read_watchpoint
1658    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1659    not user-visible - its hit is suppressed if the memory content has
1660    not changed.
1661
1662    The following constraints influence the location where we can reset
1663    hardware watchpoints:
1664
1665    * target_stopped_by_watchpoint and target_stopped_data_address are
1666      called several times when GDB stops.
1667
1668    [linux] 
1669    * Multiple hardware watchpoints can be hit at the same time,
1670      causing GDB to stop.  GDB only presents one hardware watchpoint
1671      hit at a time as the reason for stopping, and all the other hits
1672      are presented later, one after the other, each time the user
1673      requests the execution to be resumed.  Execution is not resumed
1674      for the threads still having pending hit event stored in
1675      LWP_INFO->STATUS.  While the watchpoint is already removed from
1676      the inferior on the first stop the thread hit event is kept being
1677      reported from its cached value by linux_nat_stopped_data_address
1678      until the real thread resume happens after the watchpoint gets
1679      presented and thus its LWP_INFO->STATUS gets reset.
1680
1681    Therefore the hardware watchpoint hit can get safely reset on the
1682    watchpoint removal from inferior.  */
1683
1684 static void
1685 update_watchpoint (struct watchpoint *b, int reparse)
1686 {
1687   int within_current_scope;
1688   struct frame_id saved_frame_id;
1689   int frame_saved;
1690
1691   /* If this is a local watchpoint, we only want to check if the
1692      watchpoint frame is in scope if the current thread is the thread
1693      that was used to create the watchpoint.  */
1694   if (!watchpoint_in_thread_scope (b))
1695     return;
1696
1697   if (b->disposition == disp_del_at_next_stop)
1698     return;
1699  
1700   frame_saved = 0;
1701
1702   /* Determine if the watchpoint is within scope.  */
1703   if (b->exp_valid_block == NULL)
1704     within_current_scope = 1;
1705   else
1706     {
1707       struct frame_info *fi = get_current_frame ();
1708       struct gdbarch *frame_arch = get_frame_arch (fi);
1709       CORE_ADDR frame_pc = get_frame_pc (fi);
1710
1711       /* If we're at a point where the stack has been destroyed
1712          (e.g. in a function epilogue), unwinding may not work
1713          properly. Do not attempt to recreate locations at this
1714          point.  See similar comments in watchpoint_check.  */
1715       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1716         return;
1717
1718       /* Save the current frame's ID so we can restore it after
1719          evaluating the watchpoint expression on its own frame.  */
1720       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1721          took a frame parameter, so that we didn't have to change the
1722          selected frame.  */
1723       frame_saved = 1;
1724       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1725
1726       fi = frame_find_by_id (b->watchpoint_frame);
1727       within_current_scope = (fi != NULL);
1728       if (within_current_scope)
1729         select_frame (fi);
1730     }
1731
1732   /* We don't free locations.  They are stored in the bp_location array
1733      and update_global_location_list will eventually delete them and
1734      remove breakpoints if needed.  */
1735   b->loc = NULL;
1736
1737   if (within_current_scope && reparse)
1738     {
1739       const char *s;
1740
1741       b->exp.reset ();
1742       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1743       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1744       /* If the meaning of expression itself changed, the old value is
1745          no longer relevant.  We don't want to report a watchpoint hit
1746          to the user when the old value and the new value may actually
1747          be completely different objects.  */
1748       b->val = NULL;
1749       b->val_valid = 0;
1750
1751       /* Note that unlike with breakpoints, the watchpoint's condition
1752          expression is stored in the breakpoint object, not in the
1753          locations (re)created below.  */
1754       if (b->cond_string != NULL)
1755         {
1756           b->cond_exp.reset ();
1757
1758           s = b->cond_string;
1759           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1760         }
1761     }
1762
1763   /* If we failed to parse the expression, for example because
1764      it refers to a global variable in a not-yet-loaded shared library,
1765      don't try to insert watchpoint.  We don't automatically delete
1766      such watchpoint, though, since failure to parse expression
1767      is different from out-of-scope watchpoint.  */
1768   if (!target_has_execution)
1769     {
1770       /* Without execution, memory can't change.  No use to try and
1771          set watchpoint locations.  The watchpoint will be reset when
1772          the target gains execution, through breakpoint_re_set.  */
1773       if (!can_use_hw_watchpoints)
1774         {
1775           if (b->ops->works_in_software_mode (b))
1776             b->type = bp_watchpoint;
1777           else
1778             error (_("Can't set read/access watchpoint when "
1779                      "hardware watchpoints are disabled."));
1780         }
1781     }
1782   else if (within_current_scope && b->exp)
1783     {
1784       int pc = 0;
1785       std::vector<value_ref_ptr> val_chain;
1786       struct value *v, *result;
1787       struct program_space *frame_pspace;
1788
1789       fetch_subexp_value (b->exp.get (), &pc, &v, &result, &val_chain, 0);
1790
1791       /* Avoid setting b->val if it's already set.  The meaning of
1792          b->val is 'the last value' user saw, and we should update
1793          it only if we reported that last value to user.  As it
1794          happens, the code that reports it updates b->val directly.
1795          We don't keep track of the memory value for masked
1796          watchpoints.  */
1797       if (!b->val_valid && !is_masked_watchpoint (b))
1798         {
1799           if (b->val_bitsize != 0)
1800             v = extract_bitfield_from_watchpoint_value (b, v);
1801           b->val = release_value (v);
1802           b->val_valid = 1;
1803         }
1804
1805       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1806
1807       /* Look at each value on the value chain.  */
1808       gdb_assert (!val_chain.empty ());
1809       for (const value_ref_ptr &iter : val_chain)
1810         {
1811           v = iter.get ();
1812
1813           /* If it's a memory location, and GDB actually needed
1814              its contents to evaluate the expression, then we
1815              must watch it.  If the first value returned is
1816              still lazy, that means an error occurred reading it;
1817              watch it anyway in case it becomes readable.  */
1818           if (VALUE_LVAL (v) == lval_memory
1819               && (v == val_chain[0] || ! value_lazy (v)))
1820             {
1821               struct type *vtype = check_typedef (value_type (v));
1822
1823               /* We only watch structs and arrays if user asked
1824                  for it explicitly, never if they just happen to
1825                  appear in the middle of some value chain.  */
1826               if (v == result
1827                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1828                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1829                 {
1830                   CORE_ADDR addr;
1831                   enum target_hw_bp_type type;
1832                   struct bp_location *loc, **tmp;
1833                   int bitpos = 0, bitsize = 0;
1834
1835                   if (value_bitsize (v) != 0)
1836                     {
1837                       /* Extract the bit parameters out from the bitfield
1838                          sub-expression.  */
1839                       bitpos = value_bitpos (v);
1840                       bitsize = value_bitsize (v);
1841                     }
1842                   else if (v == result && b->val_bitsize != 0)
1843                     {
1844                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1845                         lvalue whose bit parameters are saved in the fields
1846                         VAL_BITPOS and VAL_BITSIZE.  */
1847                       bitpos = b->val_bitpos;
1848                       bitsize = b->val_bitsize;
1849                     }
1850
1851                   addr = value_address (v);
1852                   if (bitsize != 0)
1853                     {
1854                       /* Skip the bytes that don't contain the bitfield.  */
1855                       addr += bitpos / 8;
1856                     }
1857
1858                   type = hw_write;
1859                   if (b->type == bp_read_watchpoint)
1860                     type = hw_read;
1861                   else if (b->type == bp_access_watchpoint)
1862                     type = hw_access;
1863
1864                   loc = allocate_bp_location (b);
1865                   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
1866                     ;
1867                   *tmp = loc;
1868                   loc->gdbarch = get_type_arch (value_type (v));
1869
1870                   loc->pspace = frame_pspace;
1871                   loc->address = address_significant (loc->gdbarch, addr);
1872
1873                   if (bitsize != 0)
1874                     {
1875                       /* Just cover the bytes that make up the bitfield.  */
1876                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
1877                     }
1878                   else
1879                     loc->length = TYPE_LENGTH (value_type (v));
1880
1881                   loc->watchpoint_type = type;
1882                 }
1883             }
1884         }
1885
1886       /* Change the type of breakpoint between hardware assisted or
1887          an ordinary watchpoint depending on the hardware support
1888          and free hardware slots.  REPARSE is set when the inferior
1889          is started.  */
1890       if (reparse)
1891         {
1892           int reg_cnt;
1893           enum bp_loc_type loc_type;
1894           struct bp_location *bl;
1895
1896           reg_cnt = can_use_hardware_watchpoint (val_chain);
1897
1898           if (reg_cnt)
1899             {
1900               int i, target_resources_ok, other_type_used;
1901               enum bptype type;
1902
1903               /* Use an exact watchpoint when there's only one memory region to be
1904                  watched, and only one debug register is needed to watch it.  */
1905               b->exact = target_exact_watchpoints && reg_cnt == 1;
1906
1907               /* We need to determine how many resources are already
1908                  used for all other hardware watchpoints plus this one
1909                  to see if we still have enough resources to also fit
1910                  this watchpoint in as well.  */
1911
1912               /* If this is a software watchpoint, we try to turn it
1913                  to a hardware one -- count resources as if B was of
1914                  hardware watchpoint type.  */
1915               type = b->type;
1916               if (type == bp_watchpoint)
1917                 type = bp_hardware_watchpoint;
1918
1919               /* This watchpoint may or may not have been placed on
1920                  the list yet at this point (it won't be in the list
1921                  if we're trying to create it for the first time,
1922                  through watch_command), so always account for it
1923                  manually.  */
1924
1925               /* Count resources used by all watchpoints except B.  */
1926               i = hw_watchpoint_used_count_others (b, type, &other_type_used);
1927
1928               /* Add in the resources needed for B.  */
1929               i += hw_watchpoint_use_count (b);
1930
1931               target_resources_ok
1932                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1933               if (target_resources_ok <= 0)
1934                 {
1935                   int sw_mode = b->ops->works_in_software_mode (b);
1936
1937                   if (target_resources_ok == 0 && !sw_mode)
1938                     error (_("Target does not support this type of "
1939                              "hardware watchpoint."));
1940                   else if (target_resources_ok < 0 && !sw_mode)
1941                     error (_("There are not enough available hardware "
1942                              "resources for this watchpoint."));
1943
1944                   /* Downgrade to software watchpoint.  */
1945                   b->type = bp_watchpoint;
1946                 }
1947               else
1948                 {
1949                   /* If this was a software watchpoint, we've just
1950                      found we have enough resources to turn it to a
1951                      hardware watchpoint.  Otherwise, this is a
1952                      nop.  */
1953                   b->type = type;
1954                 }
1955             }
1956           else if (!b->ops->works_in_software_mode (b))
1957             {
1958               if (!can_use_hw_watchpoints)
1959                 error (_("Can't set read/access watchpoint when "
1960                          "hardware watchpoints are disabled."));
1961               else
1962                 error (_("Expression cannot be implemented with "
1963                          "read/access watchpoint."));
1964             }
1965           else
1966             b->type = bp_watchpoint;
1967
1968           loc_type = (b->type == bp_watchpoint? bp_loc_other
1969                       : bp_loc_hardware_watchpoint);
1970           for (bl = b->loc; bl; bl = bl->next)
1971             bl->loc_type = loc_type;
1972         }
1973
1974       /* If a software watchpoint is not watching any memory, then the
1975          above left it without any location set up.  But,
1976          bpstat_stop_status requires a location to be able to report
1977          stops, so make sure there's at least a dummy one.  */
1978       if (b->type == bp_watchpoint && b->loc == NULL)
1979         software_watchpoint_add_no_memory_location (b, frame_pspace);
1980     }
1981   else if (!within_current_scope)
1982     {
1983       printf_filtered (_("\
1984 Watchpoint %d deleted because the program has left the block\n\
1985 in which its expression is valid.\n"),
1986                        b->number);
1987       watchpoint_del_at_next_stop (b);
1988     }
1989
1990   /* Restore the selected frame.  */
1991   if (frame_saved)
1992     select_frame (frame_find_by_id (saved_frame_id));
1993 }
1994
1995
1996 /* Returns 1 iff breakpoint location should be
1997    inserted in the inferior.  We don't differentiate the type of BL's owner
1998    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1999    breakpoint_ops is not defined, because in insert_bp_location,
2000    tracepoint's insert_location will not be called.  */
2001 static int
2002 should_be_inserted (struct bp_location *bl)
2003 {
2004   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2005     return 0;
2006
2007   if (bl->owner->disposition == disp_del_at_next_stop)
2008     return 0;
2009
2010   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2011     return 0;
2012
2013   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2014     return 0;
2015
2016   /* This is set for example, when we're attached to the parent of a
2017      vfork, and have detached from the child.  The child is running
2018      free, and we expect it to do an exec or exit, at which point the
2019      OS makes the parent schedulable again (and the target reports
2020      that the vfork is done).  Until the child is done with the shared
2021      memory region, do not insert breakpoints in the parent, otherwise
2022      the child could still trip on the parent's breakpoints.  Since
2023      the parent is blocked anyway, it won't miss any breakpoint.  */
2024   if (bl->pspace->breakpoints_not_allowed)
2025     return 0;
2026
2027   /* Don't insert a breakpoint if we're trying to step past its
2028      location, except if the breakpoint is a single-step breakpoint,
2029      and the breakpoint's thread is the thread which is stepping past
2030      a breakpoint.  */
2031   if ((bl->loc_type == bp_loc_software_breakpoint
2032        || bl->loc_type == bp_loc_hardware_breakpoint)
2033       && stepping_past_instruction_at (bl->pspace->aspace,
2034                                        bl->address)
2035       /* The single-step breakpoint may be inserted at the location
2036          we're trying to step if the instruction branches to itself.
2037          However, the instruction won't be executed at all and it may
2038          break the semantics of the instruction, for example, the
2039          instruction is a conditional branch or updates some flags.
2040          We can't fix it unless GDB is able to emulate the instruction
2041          or switch to displaced stepping.  */
2042       && !(bl->owner->type == bp_single_step
2043            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2044     {
2045       if (debug_infrun)
2046         {
2047           fprintf_unfiltered (gdb_stdlog,
2048                               "infrun: skipping breakpoint: "
2049                               "stepping past insn at: %s\n",
2050                               paddress (bl->gdbarch, bl->address));
2051         }
2052       return 0;
2053     }
2054
2055   /* Don't insert watchpoints if we're trying to step past the
2056      instruction that triggered one.  */
2057   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2058       && stepping_past_nonsteppable_watchpoint ())
2059     {
2060       if (debug_infrun)
2061         {
2062           fprintf_unfiltered (gdb_stdlog,
2063                               "infrun: stepping past non-steppable watchpoint. "
2064                               "skipping watchpoint at %s:%d\n",
2065                               paddress (bl->gdbarch, bl->address),
2066                               bl->length);
2067         }
2068       return 0;
2069     }
2070
2071   return 1;
2072 }
2073
2074 /* Same as should_be_inserted but does the check assuming
2075    that the location is not duplicated.  */
2076
2077 static int
2078 unduplicated_should_be_inserted (struct bp_location *bl)
2079 {
2080   int result;
2081   const int save_duplicate = bl->duplicate;
2082
2083   bl->duplicate = 0;
2084   result = should_be_inserted (bl);
2085   bl->duplicate = save_duplicate;
2086   return result;
2087 }
2088
2089 /* Parses a conditional described by an expression COND into an
2090    agent expression bytecode suitable for evaluation
2091    by the bytecode interpreter.  Return NULL if there was
2092    any error during parsing.  */
2093
2094 static agent_expr_up
2095 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2096 {
2097   if (cond == NULL)
2098     return NULL;
2099
2100   agent_expr_up aexpr;
2101
2102   /* We don't want to stop processing, so catch any errors
2103      that may show up.  */
2104   TRY
2105     {
2106       aexpr = gen_eval_for_expr (scope, cond);
2107     }
2108
2109   CATCH (ex, RETURN_MASK_ERROR)
2110     {
2111       /* If we got here, it means the condition could not be parsed to a valid
2112          bytecode expression and thus can't be evaluated on the target's side.
2113          It's no use iterating through the conditions.  */
2114     }
2115   END_CATCH
2116
2117   /* We have a valid agent expression.  */
2118   return aexpr;
2119 }
2120
2121 /* Based on location BL, create a list of breakpoint conditions to be
2122    passed on to the target.  If we have duplicated locations with different
2123    conditions, we will add such conditions to the list.  The idea is that the
2124    target will evaluate the list of conditions and will only notify GDB when
2125    one of them is true.  */
2126
2127 static void
2128 build_target_condition_list (struct bp_location *bl)
2129 {
2130   struct bp_location **locp = NULL, **loc2p;
2131   int null_condition_or_parse_error = 0;
2132   int modified = bl->needs_update;
2133   struct bp_location *loc;
2134
2135   /* Release conditions left over from a previous insert.  */
2136   bl->target_info.conditions.clear ();
2137
2138   /* This is only meaningful if the target is
2139      evaluating conditions and if the user has
2140      opted for condition evaluation on the target's
2141      side.  */
2142   if (gdb_evaluates_breakpoint_condition_p ()
2143       || !target_supports_evaluation_of_breakpoint_conditions ())
2144     return;
2145
2146   /* Do a first pass to check for locations with no assigned
2147      conditions or conditions that fail to parse to a valid agent expression
2148      bytecode.  If any of these happen, then it's no use to send conditions
2149      to the target since this location will always trigger and generate a
2150      response back to GDB.  */
2151   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2152     {
2153       loc = (*loc2p);
2154       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2155         {
2156           if (modified)
2157             {
2158               /* Re-parse the conditions since something changed.  In that
2159                  case we already freed the condition bytecodes (see
2160                  force_breakpoint_reinsertion).  We just
2161                  need to parse the condition to bytecodes again.  */
2162               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2163                                                         loc->cond.get ());
2164             }
2165
2166           /* If we have a NULL bytecode expression, it means something
2167              went wrong or we have a null condition expression.  */
2168           if (!loc->cond_bytecode)
2169             {
2170               null_condition_or_parse_error = 1;
2171               break;
2172             }
2173         }
2174     }
2175
2176   /* If any of these happened, it means we will have to evaluate the conditions
2177      for the location's address on gdb's side.  It is no use keeping bytecodes
2178      for all the other duplicate locations, thus we free all of them here.
2179
2180      This is so we have a finer control over which locations' conditions are
2181      being evaluated by GDB or the remote stub.  */
2182   if (null_condition_or_parse_error)
2183     {
2184       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2185         {
2186           loc = (*loc2p);
2187           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2188             {
2189               /* Only go as far as the first NULL bytecode is
2190                  located.  */
2191               if (!loc->cond_bytecode)
2192                 return;
2193
2194               loc->cond_bytecode.reset ();
2195             }
2196         }
2197     }
2198
2199   /* No NULL conditions or failed bytecode generation.  Build a condition list
2200      for this location's address.  */
2201   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2202     {
2203       loc = (*loc2p);
2204       if (loc->cond
2205           && is_breakpoint (loc->owner)
2206           && loc->pspace->num == bl->pspace->num
2207           && loc->owner->enable_state == bp_enabled
2208           && loc->enabled)
2209         {
2210           /* Add the condition to the vector.  This will be used later
2211              to send the conditions to the target.  */
2212           bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2213         }
2214     }
2215
2216   return;
2217 }
2218
2219 /* Parses a command described by string CMD into an agent expression
2220    bytecode suitable for evaluation by the bytecode interpreter.
2221    Return NULL if there was any error during parsing.  */
2222
2223 static agent_expr_up
2224 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2225 {
2226   const char *cmdrest;
2227   const char *format_start, *format_end;
2228   struct gdbarch *gdbarch = get_current_arch ();
2229
2230   if (cmd == NULL)
2231     return NULL;
2232
2233   cmdrest = cmd;
2234
2235   if (*cmdrest == ',')
2236     ++cmdrest;
2237   cmdrest = skip_spaces (cmdrest);
2238
2239   if (*cmdrest++ != '"')
2240     error (_("No format string following the location"));
2241
2242   format_start = cmdrest;
2243
2244   format_pieces fpieces (&cmdrest);
2245
2246   format_end = cmdrest;
2247
2248   if (*cmdrest++ != '"')
2249     error (_("Bad format string, non-terminated '\"'."));
2250   
2251   cmdrest = skip_spaces (cmdrest);
2252
2253   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2254     error (_("Invalid argument syntax"));
2255
2256   if (*cmdrest == ',')
2257     cmdrest++;
2258   cmdrest = skip_spaces (cmdrest);
2259
2260   /* For each argument, make an expression.  */
2261
2262   std::vector<struct expression *> argvec;
2263   while (*cmdrest != '\0')
2264     {
2265       const char *cmd1;
2266
2267       cmd1 = cmdrest;
2268       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2269       argvec.push_back (expr.release ());
2270       cmdrest = cmd1;
2271       if (*cmdrest == ',')
2272         ++cmdrest;
2273     }
2274
2275   agent_expr_up aexpr;
2276
2277   /* We don't want to stop processing, so catch any errors
2278      that may show up.  */
2279   TRY
2280     {
2281       aexpr = gen_printf (scope, gdbarch, 0, 0,
2282                           format_start, format_end - format_start,
2283                           argvec.size (), argvec.data ());
2284     }
2285   CATCH (ex, RETURN_MASK_ERROR)
2286     {
2287       /* If we got here, it means the command could not be parsed to a valid
2288          bytecode expression and thus can't be evaluated on the target's side.
2289          It's no use iterating through the other commands.  */
2290     }
2291   END_CATCH
2292
2293   /* We have a valid agent expression, return it.  */
2294   return aexpr;
2295 }
2296
2297 /* Based on location BL, create a list of breakpoint commands to be
2298    passed on to the target.  If we have duplicated locations with
2299    different commands, we will add any such to the list.  */
2300
2301 static void
2302 build_target_command_list (struct bp_location *bl)
2303 {
2304   struct bp_location **locp = NULL, **loc2p;
2305   int null_command_or_parse_error = 0;
2306   int modified = bl->needs_update;
2307   struct bp_location *loc;
2308
2309   /* Clear commands left over from a previous insert.  */
2310   bl->target_info.tcommands.clear ();
2311
2312   if (!target_can_run_breakpoint_commands ())
2313     return;
2314
2315   /* For now, limit to agent-style dprintf breakpoints.  */
2316   if (dprintf_style != dprintf_style_agent)
2317     return;
2318
2319   /* For now, if we have any duplicate location that isn't a dprintf,
2320      don't install the target-side commands, as that would make the
2321      breakpoint not be reported to the core, and we'd lose
2322      control.  */
2323   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2324     {
2325       loc = (*loc2p);
2326       if (is_breakpoint (loc->owner)
2327           && loc->pspace->num == bl->pspace->num
2328           && loc->owner->type != bp_dprintf)
2329         return;
2330     }
2331
2332   /* Do a first pass to check for locations with no assigned
2333      conditions or conditions that fail to parse to a valid agent expression
2334      bytecode.  If any of these happen, then it's no use to send conditions
2335      to the target since this location will always trigger and generate a
2336      response back to GDB.  */
2337   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2338     {
2339       loc = (*loc2p);
2340       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2341         {
2342           if (modified)
2343             {
2344               /* Re-parse the commands since something changed.  In that
2345                  case we already freed the command bytecodes (see
2346                  force_breakpoint_reinsertion).  We just
2347                  need to parse the command to bytecodes again.  */
2348               loc->cmd_bytecode
2349                 = parse_cmd_to_aexpr (bl->address,
2350                                       loc->owner->extra_string);
2351             }
2352
2353           /* If we have a NULL bytecode expression, it means something
2354              went wrong or we have a null command expression.  */
2355           if (!loc->cmd_bytecode)
2356             {
2357               null_command_or_parse_error = 1;
2358               break;
2359             }
2360         }
2361     }
2362
2363   /* If anything failed, then we're not doing target-side commands,
2364      and so clean up.  */
2365   if (null_command_or_parse_error)
2366     {
2367       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2368         {
2369           loc = (*loc2p);
2370           if (is_breakpoint (loc->owner)
2371               && loc->pspace->num == bl->pspace->num)
2372             {
2373               /* Only go as far as the first NULL bytecode is
2374                  located.  */
2375               if (loc->cmd_bytecode == NULL)
2376                 return;
2377
2378               loc->cmd_bytecode.reset ();
2379             }
2380         }
2381     }
2382
2383   /* No NULL commands or failed bytecode generation.  Build a command list
2384      for this location's address.  */
2385   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2386     {
2387       loc = (*loc2p);
2388       if (loc->owner->extra_string
2389           && is_breakpoint (loc->owner)
2390           && loc->pspace->num == bl->pspace->num
2391           && loc->owner->enable_state == bp_enabled
2392           && loc->enabled)
2393         {
2394           /* Add the command to the vector.  This will be used later
2395              to send the commands to the target.  */
2396           bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2397         }
2398     }
2399
2400   bl->target_info.persist = 0;
2401   /* Maybe flag this location as persistent.  */
2402   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2403     bl->target_info.persist = 1;
2404 }
2405
2406 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2407    of breakpoint according to ADDR except single-step breakpoint.
2408    Get the kind of single-step breakpoint according to the current
2409    registers state.  */
2410
2411 static int
2412 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2413 {
2414   if (bl->owner->type == bp_single_step)
2415     {
2416       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2417       struct regcache *regcache;
2418
2419       regcache = get_thread_regcache (thr);
2420
2421       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2422                                                          regcache, addr);
2423     }
2424   else
2425     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2426 }
2427
2428 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2429    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2430    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2431    Returns 0 for success, 1 if the bp_location type is not supported or
2432    -1 for failure.
2433
2434    NOTE drow/2003-09-09: This routine could be broken down to an
2435    object-style method for each breakpoint or catchpoint type.  */
2436 static int
2437 insert_bp_location (struct bp_location *bl,
2438                     struct ui_file *tmp_error_stream,
2439                     int *disabled_breaks,
2440                     int *hw_breakpoint_error,
2441                     int *hw_bp_error_explained_already)
2442 {
2443   gdb_exception bp_excpt = exception_none;
2444
2445   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2446     return 0;
2447
2448   /* Note we don't initialize bl->target_info, as that wipes out
2449      the breakpoint location's shadow_contents if the breakpoint
2450      is still inserted at that location.  This in turn breaks
2451      target_read_memory which depends on these buffers when
2452      a memory read is requested at the breakpoint location:
2453      Once the target_info has been wiped, we fail to see that
2454      we have a breakpoint inserted at that address and thus
2455      read the breakpoint instead of returning the data saved in
2456      the breakpoint location's shadow contents.  */
2457   bl->target_info.reqstd_address = bl->address;
2458   bl->target_info.placed_address_space = bl->pspace->aspace;
2459   bl->target_info.length = bl->length;
2460
2461   /* When working with target-side conditions, we must pass all the conditions
2462      for the same breakpoint address down to the target since GDB will not
2463      insert those locations.  With a list of breakpoint conditions, the target
2464      can decide when to stop and notify GDB.  */
2465
2466   if (is_breakpoint (bl->owner))
2467     {
2468       build_target_condition_list (bl);
2469       build_target_command_list (bl);
2470       /* Reset the modification marker.  */
2471       bl->needs_update = 0;
2472     }
2473
2474   if (bl->loc_type == bp_loc_software_breakpoint
2475       || bl->loc_type == bp_loc_hardware_breakpoint)
2476     {
2477       if (bl->owner->type != bp_hardware_breakpoint)
2478         {
2479           /* If the explicitly specified breakpoint type
2480              is not hardware breakpoint, check the memory map to see
2481              if the breakpoint address is in read only memory or not.
2482
2483              Two important cases are:
2484              - location type is not hardware breakpoint, memory
2485              is readonly.  We change the type of the location to
2486              hardware breakpoint.
2487              - location type is hardware breakpoint, memory is
2488              read-write.  This means we've previously made the
2489              location hardware one, but then the memory map changed,
2490              so we undo.
2491              
2492              When breakpoints are removed, remove_breakpoints will use
2493              location types we've just set here, the only possible
2494              problem is that memory map has changed during running
2495              program, but it's not going to work anyway with current
2496              gdb.  */
2497           struct mem_region *mr 
2498             = lookup_mem_region (bl->target_info.reqstd_address);
2499           
2500           if (mr)
2501             {
2502               if (automatic_hardware_breakpoints)
2503                 {
2504                   enum bp_loc_type new_type;
2505                   
2506                   if (mr->attrib.mode != MEM_RW)
2507                     new_type = bp_loc_hardware_breakpoint;
2508                   else 
2509                     new_type = bp_loc_software_breakpoint;
2510                   
2511                   if (new_type != bl->loc_type)
2512                     {
2513                       static int said = 0;
2514
2515                       bl->loc_type = new_type;
2516                       if (!said)
2517                         {
2518                           fprintf_filtered (gdb_stdout,
2519                                             _("Note: automatically using "
2520                                               "hardware breakpoints for "
2521                                               "read-only addresses.\n"));
2522                           said = 1;
2523                         }
2524                     }
2525                 }
2526               else if (bl->loc_type == bp_loc_software_breakpoint
2527                        && mr->attrib.mode != MEM_RW)
2528                 {
2529                   fprintf_unfiltered (tmp_error_stream,
2530                                       _("Cannot insert breakpoint %d.\n"
2531                                         "Cannot set software breakpoint "
2532                                         "at read-only address %s\n"),
2533                                       bl->owner->number,
2534                                       paddress (bl->gdbarch, bl->address));
2535                   return 1;
2536                 }
2537             }
2538         }
2539         
2540       /* First check to see if we have to handle an overlay.  */
2541       if (overlay_debugging == ovly_off
2542           || bl->section == NULL
2543           || !(section_is_overlay (bl->section)))
2544         {
2545           /* No overlay handling: just set the breakpoint.  */
2546           TRY
2547             {
2548               int val;
2549
2550               val = bl->owner->ops->insert_location (bl);
2551               if (val)
2552                 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2553             }
2554           CATCH (e, RETURN_MASK_ALL)
2555             {
2556               bp_excpt = e;
2557             }
2558           END_CATCH
2559         }
2560       else
2561         {
2562           /* This breakpoint is in an overlay section.
2563              Shall we set a breakpoint at the LMA?  */
2564           if (!overlay_events_enabled)
2565             {
2566               /* Yes -- overlay event support is not active, 
2567                  so we must try to set a breakpoint at the LMA.
2568                  This will not work for a hardware breakpoint.  */
2569               if (bl->loc_type == bp_loc_hardware_breakpoint)
2570                 warning (_("hardware breakpoint %d not supported in overlay!"),
2571                          bl->owner->number);
2572               else
2573                 {
2574                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2575                                                              bl->section);
2576                   /* Set a software (trap) breakpoint at the LMA.  */
2577                   bl->overlay_target_info = bl->target_info;
2578                   bl->overlay_target_info.reqstd_address = addr;
2579
2580                   /* No overlay handling: just set the breakpoint.  */
2581                   TRY
2582                     {
2583                       int val;
2584
2585                       bl->overlay_target_info.kind
2586                         = breakpoint_kind (bl, &addr);
2587                       bl->overlay_target_info.placed_address = addr;
2588                       val = target_insert_breakpoint (bl->gdbarch,
2589                                                       &bl->overlay_target_info);
2590                       if (val)
2591                         bp_excpt
2592                           = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2593                     }
2594                   CATCH (e, RETURN_MASK_ALL)
2595                     {
2596                       bp_excpt = e;
2597                     }
2598                   END_CATCH
2599
2600                   if (bp_excpt.reason != 0)
2601                     fprintf_unfiltered (tmp_error_stream,
2602                                         "Overlay breakpoint %d "
2603                                         "failed: in ROM?\n",
2604                                         bl->owner->number);
2605                 }
2606             }
2607           /* Shall we set a breakpoint at the VMA? */
2608           if (section_is_mapped (bl->section))
2609             {
2610               /* Yes.  This overlay section is mapped into memory.  */
2611               TRY
2612                 {
2613                   int val;
2614
2615                   val = bl->owner->ops->insert_location (bl);
2616                   if (val)
2617                     bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2618                 }
2619               CATCH (e, RETURN_MASK_ALL)
2620                 {
2621                   bp_excpt = e;
2622                 }
2623               END_CATCH
2624             }
2625           else
2626             {
2627               /* No.  This breakpoint will not be inserted.  
2628                  No error, but do not mark the bp as 'inserted'.  */
2629               return 0;
2630             }
2631         }
2632
2633       if (bp_excpt.reason != 0)
2634         {
2635           /* Can't set the breakpoint.  */
2636
2637           /* In some cases, we might not be able to insert a
2638              breakpoint in a shared library that has already been
2639              removed, but we have not yet processed the shlib unload
2640              event.  Unfortunately, some targets that implement
2641              breakpoint insertion themselves can't tell why the
2642              breakpoint insertion failed (e.g., the remote target
2643              doesn't define error codes), so we must treat generic
2644              errors as memory errors.  */
2645           if (bp_excpt.reason == RETURN_ERROR
2646               && (bp_excpt.error == GENERIC_ERROR
2647                   || bp_excpt.error == MEMORY_ERROR)
2648               && bl->loc_type == bp_loc_software_breakpoint
2649               && (solib_name_from_address (bl->pspace, bl->address)
2650                   || shared_objfile_contains_address_p (bl->pspace,
2651                                                         bl->address)))
2652             {
2653               /* See also: disable_breakpoints_in_shlibs.  */
2654               bl->shlib_disabled = 1;
2655               gdb::observers::breakpoint_modified.notify (bl->owner);
2656               if (!*disabled_breaks)
2657                 {
2658                   fprintf_unfiltered (tmp_error_stream, 
2659                                       "Cannot insert breakpoint %d.\n", 
2660                                       bl->owner->number);
2661                   fprintf_unfiltered (tmp_error_stream, 
2662                                       "Temporarily disabling shared "
2663                                       "library breakpoints:\n");
2664                 }
2665               *disabled_breaks = 1;
2666               fprintf_unfiltered (tmp_error_stream,
2667                                   "breakpoint #%d\n", bl->owner->number);
2668               return 0;
2669             }
2670           else
2671             {
2672               if (bl->loc_type == bp_loc_hardware_breakpoint)
2673                 {
2674                   *hw_breakpoint_error = 1;
2675                   *hw_bp_error_explained_already = bp_excpt.message != NULL;
2676                   fprintf_unfiltered (tmp_error_stream,
2677                                       "Cannot insert hardware breakpoint %d%s",
2678                                       bl->owner->number,
2679                                       bp_excpt.message ? ":" : ".\n");
2680                   if (bp_excpt.message != NULL)
2681                     fprintf_unfiltered (tmp_error_stream, "%s.\n",
2682                                         bp_excpt.message);
2683                 }
2684               else
2685                 {
2686                   if (bp_excpt.message == NULL)
2687                     {
2688                       std::string message
2689                         = memory_error_message (TARGET_XFER_E_IO,
2690                                                 bl->gdbarch, bl->address);
2691
2692                       fprintf_unfiltered (tmp_error_stream,
2693                                           "Cannot insert breakpoint %d.\n"
2694                                           "%s\n",
2695                                           bl->owner->number, message.c_str ());
2696                     }
2697                   else
2698                     {
2699                       fprintf_unfiltered (tmp_error_stream,
2700                                           "Cannot insert breakpoint %d: %s\n",
2701                                           bl->owner->number,
2702                                           bp_excpt.message);
2703                     }
2704                 }
2705               return 1;
2706
2707             }
2708         }
2709       else
2710         bl->inserted = 1;
2711
2712       return 0;
2713     }
2714
2715   else if (bl->loc_type == bp_loc_hardware_watchpoint
2716            /* NOTE drow/2003-09-08: This state only exists for removing
2717               watchpoints.  It's not clear that it's necessary...  */
2718            && bl->owner->disposition != disp_del_at_next_stop)
2719     {
2720       int val;
2721
2722       gdb_assert (bl->owner->ops != NULL
2723                   && bl->owner->ops->insert_location != NULL);
2724
2725       val = bl->owner->ops->insert_location (bl);
2726
2727       /* If trying to set a read-watchpoint, and it turns out it's not
2728          supported, try emulating one with an access watchpoint.  */
2729       if (val == 1 && bl->watchpoint_type == hw_read)
2730         {
2731           struct bp_location *loc, **loc_temp;
2732
2733           /* But don't try to insert it, if there's already another
2734              hw_access location that would be considered a duplicate
2735              of this one.  */
2736           ALL_BP_LOCATIONS (loc, loc_temp)
2737             if (loc != bl
2738                 && loc->watchpoint_type == hw_access
2739                 && watchpoint_locations_match (bl, loc))
2740               {
2741                 bl->duplicate = 1;
2742                 bl->inserted = 1;
2743                 bl->target_info = loc->target_info;
2744                 bl->watchpoint_type = hw_access;
2745                 val = 0;
2746                 break;
2747               }
2748
2749           if (val == 1)
2750             {
2751               bl->watchpoint_type = hw_access;
2752               val = bl->owner->ops->insert_location (bl);
2753
2754               if (val)
2755                 /* Back to the original value.  */
2756                 bl->watchpoint_type = hw_read;
2757             }
2758         }
2759
2760       bl->inserted = (val == 0);
2761     }
2762
2763   else if (bl->owner->type == bp_catchpoint)
2764     {
2765       int val;
2766
2767       gdb_assert (bl->owner->ops != NULL
2768                   && bl->owner->ops->insert_location != NULL);
2769
2770       val = bl->owner->ops->insert_location (bl);
2771       if (val)
2772         {
2773           bl->owner->enable_state = bp_disabled;
2774
2775           if (val == 1)
2776             warning (_("\
2777 Error inserting catchpoint %d: Your system does not support this type\n\
2778 of catchpoint."), bl->owner->number);
2779           else
2780             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2781         }
2782
2783       bl->inserted = (val == 0);
2784
2785       /* We've already printed an error message if there was a problem
2786          inserting this catchpoint, and we've disabled the catchpoint,
2787          so just return success.  */
2788       return 0;
2789     }
2790
2791   return 0;
2792 }
2793
2794 /* This function is called when program space PSPACE is about to be
2795    deleted.  It takes care of updating breakpoints to not reference
2796    PSPACE anymore.  */
2797
2798 void
2799 breakpoint_program_space_exit (struct program_space *pspace)
2800 {
2801   struct breakpoint *b, *b_temp;
2802   struct bp_location *loc, **loc_temp;
2803
2804   /* Remove any breakpoint that was set through this program space.  */
2805   ALL_BREAKPOINTS_SAFE (b, b_temp)
2806     {
2807       if (b->pspace == pspace)
2808         delete_breakpoint (b);
2809     }
2810
2811   /* Breakpoints set through other program spaces could have locations
2812      bound to PSPACE as well.  Remove those.  */
2813   ALL_BP_LOCATIONS (loc, loc_temp)
2814     {
2815       struct bp_location *tmp;
2816
2817       if (loc->pspace == pspace)
2818         {
2819           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2820           if (loc->owner->loc == loc)
2821             loc->owner->loc = loc->next;
2822           else
2823             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2824               if (tmp->next == loc)
2825                 {
2826                   tmp->next = loc->next;
2827                   break;
2828                 }
2829         }
2830     }
2831
2832   /* Now update the global location list to permanently delete the
2833      removed locations above.  */
2834   update_global_location_list (UGLL_DONT_INSERT);
2835 }
2836
2837 /* Make sure all breakpoints are inserted in inferior.
2838    Throws exception on any error.
2839    A breakpoint that is already inserted won't be inserted
2840    again, so calling this function twice is safe.  */
2841 void
2842 insert_breakpoints (void)
2843 {
2844   struct breakpoint *bpt;
2845
2846   ALL_BREAKPOINTS (bpt)
2847     if (is_hardware_watchpoint (bpt))
2848       {
2849         struct watchpoint *w = (struct watchpoint *) bpt;
2850
2851         update_watchpoint (w, 0 /* don't reparse.  */);
2852       }
2853
2854   /* Updating watchpoints creates new locations, so update the global
2855      location list.  Explicitly tell ugll to insert locations and
2856      ignore breakpoints_always_inserted_mode.  */
2857   update_global_location_list (UGLL_INSERT);
2858 }
2859
2860 /* Invoke CALLBACK for each of bp_location.  */
2861
2862 void
2863 iterate_over_bp_locations (walk_bp_location_callback callback)
2864 {
2865   struct bp_location *loc, **loc_tmp;
2866
2867   ALL_BP_LOCATIONS (loc, loc_tmp)
2868     {
2869       callback (loc, NULL);
2870     }
2871 }
2872
2873 /* This is used when we need to synch breakpoint conditions between GDB and the
2874    target.  It is the case with deleting and disabling of breakpoints when using
2875    always-inserted mode.  */
2876
2877 static void
2878 update_inserted_breakpoint_locations (void)
2879 {
2880   struct bp_location *bl, **blp_tmp;
2881   int error_flag = 0;
2882   int val = 0;
2883   int disabled_breaks = 0;
2884   int hw_breakpoint_error = 0;
2885   int hw_bp_details_reported = 0;
2886
2887   string_file tmp_error_stream;
2888
2889   /* Explicitly mark the warning -- this will only be printed if
2890      there was an error.  */
2891   tmp_error_stream.puts ("Warning:\n");
2892
2893   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2894
2895   ALL_BP_LOCATIONS (bl, blp_tmp)
2896     {
2897       /* We only want to update software breakpoints and hardware
2898          breakpoints.  */
2899       if (!is_breakpoint (bl->owner))
2900         continue;
2901
2902       /* We only want to update locations that are already inserted
2903          and need updating.  This is to avoid unwanted insertion during
2904          deletion of breakpoints.  */
2905       if (!bl->inserted || !bl->needs_update)
2906         continue;
2907
2908       switch_to_program_space_and_thread (bl->pspace);
2909
2910       /* For targets that support global breakpoints, there's no need
2911          to select an inferior to insert breakpoint to.  In fact, even
2912          if we aren't attached to any process yet, we should still
2913          insert breakpoints.  */
2914       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2915           && inferior_ptid == null_ptid)
2916         continue;
2917
2918       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2919                                     &hw_breakpoint_error, &hw_bp_details_reported);
2920       if (val)
2921         error_flag = val;
2922     }
2923
2924   if (error_flag)
2925     {
2926       target_terminal::ours_for_output ();
2927       error_stream (tmp_error_stream);
2928     }
2929 }
2930
2931 /* Used when starting or continuing the program.  */
2932
2933 static void
2934 insert_breakpoint_locations (void)
2935 {
2936   struct breakpoint *bpt;
2937   struct bp_location *bl, **blp_tmp;
2938   int error_flag = 0;
2939   int val = 0;
2940   int disabled_breaks = 0;
2941   int hw_breakpoint_error = 0;
2942   int hw_bp_error_explained_already = 0;
2943
2944   string_file tmp_error_stream;
2945
2946   /* Explicitly mark the warning -- this will only be printed if
2947      there was an error.  */
2948   tmp_error_stream.puts ("Warning:\n");
2949
2950   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2951
2952   ALL_BP_LOCATIONS (bl, blp_tmp)
2953     {
2954       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2955         continue;
2956
2957       /* There is no point inserting thread-specific breakpoints if
2958          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2959          has BL->OWNER always non-NULL.  */
2960       if (bl->owner->thread != -1
2961           && !valid_global_thread_id (bl->owner->thread))
2962         continue;
2963
2964       switch_to_program_space_and_thread (bl->pspace);
2965
2966       /* For targets that support global breakpoints, there's no need
2967          to select an inferior to insert breakpoint to.  In fact, even
2968          if we aren't attached to any process yet, we should still
2969          insert breakpoints.  */
2970       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2971           && inferior_ptid == null_ptid)
2972         continue;
2973
2974       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2975                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
2976       if (val)
2977         error_flag = val;
2978     }
2979
2980   /* If we failed to insert all locations of a watchpoint, remove
2981      them, as half-inserted watchpoint is of limited use.  */
2982   ALL_BREAKPOINTS (bpt)  
2983     {
2984       int some_failed = 0;
2985       struct bp_location *loc;
2986
2987       if (!is_hardware_watchpoint (bpt))
2988         continue;
2989
2990       if (!breakpoint_enabled (bpt))
2991         continue;
2992
2993       if (bpt->disposition == disp_del_at_next_stop)
2994         continue;
2995       
2996       for (loc = bpt->loc; loc; loc = loc->next)
2997         if (!loc->inserted && should_be_inserted (loc))
2998           {
2999             some_failed = 1;
3000             break;
3001           }
3002       if (some_failed)
3003         {
3004           for (loc = bpt->loc; loc; loc = loc->next)
3005             if (loc->inserted)
3006               remove_breakpoint (loc);
3007
3008           hw_breakpoint_error = 1;
3009           tmp_error_stream.printf ("Could not insert "
3010                                    "hardware watchpoint %d.\n",
3011                                    bpt->number);
3012           error_flag = -1;
3013         }
3014     }
3015
3016   if (error_flag)
3017     {
3018       /* If a hardware breakpoint or watchpoint was inserted, add a
3019          message about possibly exhausted resources.  */
3020       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3021         {
3022           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3023 You may have requested too many hardware breakpoints/watchpoints.\n");
3024         }
3025       target_terminal::ours_for_output ();
3026       error_stream (tmp_error_stream);
3027     }
3028 }
3029
3030 /* Used when the program stops.
3031    Returns zero if successful, or non-zero if there was a problem
3032    removing a breakpoint location.  */
3033
3034 int
3035 remove_breakpoints (void)
3036 {
3037   struct bp_location *bl, **blp_tmp;
3038   int val = 0;
3039
3040   ALL_BP_LOCATIONS (bl, blp_tmp)
3041   {
3042     if (bl->inserted && !is_tracepoint (bl->owner))
3043       val |= remove_breakpoint (bl);
3044   }
3045   return val;
3046 }
3047
3048 /* When a thread exits, remove breakpoints that are related to
3049    that thread.  */
3050
3051 static void
3052 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3053 {
3054   struct breakpoint *b, *b_tmp;
3055
3056   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3057     {
3058       if (b->thread == tp->global_num && user_breakpoint_p (b))
3059         {
3060           b->disposition = disp_del_at_next_stop;
3061
3062           printf_filtered (_("\
3063 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3064                            b->number, print_thread_id (tp));
3065
3066           /* Hide it from the user.  */
3067           b->number = 0;
3068        }
3069     }
3070 }
3071
3072 /* Remove breakpoints of inferior INF.  */
3073
3074 int
3075 remove_breakpoints_inf (inferior *inf)
3076 {
3077   struct bp_location *bl, **blp_tmp;
3078   int val;
3079
3080   ALL_BP_LOCATIONS (bl, blp_tmp)
3081   {
3082     if (bl->pspace != inf->pspace)
3083       continue;
3084
3085     if (bl->inserted && !bl->target_info.persist)
3086       {
3087         val = remove_breakpoint (bl);
3088         if (val != 0)
3089           return val;
3090       }
3091   }
3092   return 0;
3093 }
3094
3095 static int internal_breakpoint_number = -1;
3096
3097 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3098    If INTERNAL is non-zero, the breakpoint number will be populated
3099    from internal_breakpoint_number and that variable decremented.
3100    Otherwise the breakpoint number will be populated from
3101    breakpoint_count and that value incremented.  Internal breakpoints
3102    do not set the internal var bpnum.  */
3103 static void
3104 set_breakpoint_number (int internal, struct breakpoint *b)
3105 {
3106   if (internal)
3107     b->number = internal_breakpoint_number--;
3108   else
3109     {
3110       set_breakpoint_count (breakpoint_count + 1);
3111       b->number = breakpoint_count;
3112     }
3113 }
3114
3115 static struct breakpoint *
3116 create_internal_breakpoint (struct gdbarch *gdbarch,
3117                             CORE_ADDR address, enum bptype type,
3118                             const struct breakpoint_ops *ops)
3119 {
3120   symtab_and_line sal;
3121   sal.pc = address;
3122   sal.section = find_pc_overlay (sal.pc);
3123   sal.pspace = current_program_space;
3124
3125   breakpoint *b = set_raw_breakpoint (gdbarch, sal, type, ops);
3126   b->number = internal_breakpoint_number--;
3127   b->disposition = disp_donttouch;
3128
3129   return b;
3130 }
3131
3132 static const char *const longjmp_names[] =
3133   {
3134     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3135   };
3136 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3137
3138 /* Per-objfile data private to breakpoint.c.  */
3139 struct breakpoint_objfile_data
3140 {
3141   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3142   struct bound_minimal_symbol overlay_msym {};
3143
3144   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3145   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES] {};
3146
3147   /* True if we have looked for longjmp probes.  */
3148   int longjmp_searched = 0;
3149
3150   /* SystemTap probe points for longjmp (if any).  These are non-owning
3151      references.  */
3152   std::vector<probe *> longjmp_probes;
3153
3154   /* Minimal symbol for "std::terminate()" (if any).  */
3155   struct bound_minimal_symbol terminate_msym {};
3156
3157   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3158   struct bound_minimal_symbol exception_msym {};
3159
3160   /* True if we have looked for exception probes.  */
3161   int exception_searched = 0;
3162
3163   /* SystemTap probe points for unwinding (if any).  These are non-owning
3164      references.  */
3165   std::vector<probe *> exception_probes;
3166 };
3167
3168 static const struct objfile_data *breakpoint_objfile_key;
3169
3170 /* Minimal symbol not found sentinel.  */
3171 static struct minimal_symbol msym_not_found;
3172
3173 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3174
3175 static int
3176 msym_not_found_p (const struct minimal_symbol *msym)
3177 {
3178   return msym == &msym_not_found;
3179 }
3180
3181 /* Return per-objfile data needed by breakpoint.c.
3182    Allocate the data if necessary.  */
3183
3184 static struct breakpoint_objfile_data *
3185 get_breakpoint_objfile_data (struct objfile *objfile)
3186 {
3187   struct breakpoint_objfile_data *bp_objfile_data;
3188
3189   bp_objfile_data = ((struct breakpoint_objfile_data *)
3190                      objfile_data (objfile, breakpoint_objfile_key));
3191   if (bp_objfile_data == NULL)
3192     {
3193       bp_objfile_data = new breakpoint_objfile_data ();
3194       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3195     }
3196   return bp_objfile_data;
3197 }
3198
3199 static void
3200 free_breakpoint_objfile_data (struct objfile *obj, void *data)
3201 {
3202   struct breakpoint_objfile_data *bp_objfile_data
3203     = (struct breakpoint_objfile_data *) data;
3204
3205   delete bp_objfile_data;
3206 }
3207
3208 static void
3209 create_overlay_event_breakpoint (void)
3210 {
3211   const char *const func_name = "_ovly_debug_event";
3212
3213   for (objfile *objfile : current_program_space->objfiles ())
3214     {
3215       struct breakpoint *b;
3216       struct breakpoint_objfile_data *bp_objfile_data;
3217       CORE_ADDR addr;
3218       struct explicit_location explicit_loc;
3219
3220       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3221
3222       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3223         continue;
3224
3225       if (bp_objfile_data->overlay_msym.minsym == NULL)
3226         {
3227           struct bound_minimal_symbol m;
3228
3229           m = lookup_minimal_symbol_text (func_name, objfile);
3230           if (m.minsym == NULL)
3231             {
3232               /* Avoid future lookups in this objfile.  */
3233               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3234               continue;
3235             }
3236           bp_objfile_data->overlay_msym = m;
3237         }
3238
3239       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3240       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3241                                       bp_overlay_event,
3242                                       &internal_breakpoint_ops);
3243       initialize_explicit_location (&explicit_loc);
3244       explicit_loc.function_name = ASTRDUP (func_name);
3245       b->location = new_explicit_location (&explicit_loc);
3246
3247       if (overlay_debugging == ovly_auto)
3248         {
3249           b->enable_state = bp_enabled;
3250           overlay_events_enabled = 1;
3251         }
3252       else
3253        {
3254          b->enable_state = bp_disabled;
3255          overlay_events_enabled = 0;
3256        }
3257     }
3258 }
3259
3260 static void
3261 create_longjmp_master_breakpoint (void)
3262 {
3263   struct program_space *pspace;
3264
3265   scoped_restore_current_program_space restore_pspace;
3266
3267   ALL_PSPACES (pspace)
3268   {
3269     set_current_program_space (pspace);
3270
3271     for (objfile *objfile : current_program_space->objfiles ())
3272       {
3273         int i;
3274         struct gdbarch *gdbarch;
3275         struct breakpoint_objfile_data *bp_objfile_data;
3276
3277         gdbarch = get_objfile_arch (objfile);
3278
3279         bp_objfile_data = get_breakpoint_objfile_data (objfile);
3280
3281         if (!bp_objfile_data->longjmp_searched)
3282           {
3283             std::vector<probe *> ret
3284               = find_probes_in_objfile (objfile, "libc", "longjmp");
3285
3286             if (!ret.empty ())
3287               {
3288                 /* We are only interested in checking one element.  */
3289                 probe *p = ret[0];
3290
3291                 if (!p->can_evaluate_arguments ())
3292                   {
3293                     /* We cannot use the probe interface here, because it does
3294                        not know how to evaluate arguments.  */
3295                     ret.clear ();
3296                   }
3297               }
3298             bp_objfile_data->longjmp_probes = ret;
3299             bp_objfile_data->longjmp_searched = 1;
3300           }
3301
3302         if (!bp_objfile_data->longjmp_probes.empty ())
3303           {
3304             for (probe *p : bp_objfile_data->longjmp_probes)
3305               {
3306                 struct breakpoint *b;
3307
3308                 b = create_internal_breakpoint (gdbarch,
3309                                                 p->get_relocated_address (objfile),
3310                                                 bp_longjmp_master,
3311                                                 &internal_breakpoint_ops);
3312                 b->location = new_probe_location ("-probe-stap libc:longjmp");
3313                 b->enable_state = bp_disabled;
3314               }
3315
3316             continue;
3317           }
3318
3319         if (!gdbarch_get_longjmp_target_p (gdbarch))
3320           continue;
3321
3322         for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3323           {
3324             struct breakpoint *b;
3325             const char *func_name;
3326             CORE_ADDR addr;
3327             struct explicit_location explicit_loc;
3328
3329             if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3330               continue;
3331
3332             func_name = longjmp_names[i];
3333             if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3334               {
3335                 struct bound_minimal_symbol m;
3336
3337                 m = lookup_minimal_symbol_text (func_name, objfile);
3338                 if (m.minsym == NULL)
3339                   {
3340                     /* Prevent future lookups in this objfile.  */
3341                     bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3342                     continue;
3343                   }
3344                 bp_objfile_data->longjmp_msym[i] = m;
3345               }
3346
3347             addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3348             b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3349                                             &internal_breakpoint_ops);
3350             initialize_explicit_location (&explicit_loc);
3351             explicit_loc.function_name = ASTRDUP (func_name);
3352             b->location = new_explicit_location (&explicit_loc);
3353             b->enable_state = bp_disabled;
3354           }
3355       }
3356   }
3357 }
3358
3359 /* Create a master std::terminate breakpoint.  */
3360 static void
3361 create_std_terminate_master_breakpoint (void)
3362 {
3363   struct program_space *pspace;
3364   const char *const func_name = "std::terminate()";
3365
3366   scoped_restore_current_program_space restore_pspace;
3367
3368   ALL_PSPACES (pspace)
3369   {
3370     CORE_ADDR addr;
3371
3372     set_current_program_space (pspace);
3373
3374     for (objfile *objfile : current_program_space->objfiles ())
3375       {
3376         struct breakpoint *b;
3377         struct breakpoint_objfile_data *bp_objfile_data;
3378         struct explicit_location explicit_loc;
3379
3380         bp_objfile_data = get_breakpoint_objfile_data (objfile);
3381
3382         if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3383           continue;
3384
3385         if (bp_objfile_data->terminate_msym.minsym == NULL)
3386           {
3387             struct bound_minimal_symbol m;
3388
3389             m = lookup_minimal_symbol (func_name, NULL, objfile);
3390             if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3391                                      && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3392               {
3393                 /* Prevent future lookups in this objfile.  */
3394                 bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3395                 continue;
3396               }
3397             bp_objfile_data->terminate_msym = m;
3398           }
3399
3400         addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3401         b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3402                                         bp_std_terminate_master,
3403                                         &internal_breakpoint_ops);
3404         initialize_explicit_location (&explicit_loc);
3405         explicit_loc.function_name = ASTRDUP (func_name);
3406         b->location = new_explicit_location (&explicit_loc);
3407         b->enable_state = bp_disabled;
3408       }
3409   }
3410 }
3411
3412 /* Install a master breakpoint on the unwinder's debug hook.  */
3413
3414 static void
3415 create_exception_master_breakpoint (void)
3416 {
3417   const char *const func_name = "_Unwind_DebugHook";
3418
3419   for (objfile *objfile : current_program_space->objfiles ())
3420     {
3421       struct breakpoint *b;
3422       struct gdbarch *gdbarch;
3423       struct breakpoint_objfile_data *bp_objfile_data;
3424       CORE_ADDR addr;
3425       struct explicit_location explicit_loc;
3426
3427       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3428
3429       /* We prefer the SystemTap probe point if it exists.  */
3430       if (!bp_objfile_data->exception_searched)
3431         {
3432           std::vector<probe *> ret
3433             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3434
3435           if (!ret.empty ())
3436             {
3437               /* We are only interested in checking one element.  */
3438               probe *p = ret[0];
3439
3440               if (!p->can_evaluate_arguments ())
3441                 {
3442                   /* We cannot use the probe interface here, because it does
3443                      not know how to evaluate arguments.  */
3444                   ret.clear ();
3445                 }
3446             }
3447           bp_objfile_data->exception_probes = ret;
3448           bp_objfile_data->exception_searched = 1;
3449         }
3450
3451       if (!bp_objfile_data->exception_probes.empty ())
3452         {
3453           gdbarch = get_objfile_arch (objfile);
3454
3455           for (probe *p : bp_objfile_data->exception_probes)
3456             {
3457               b = create_internal_breakpoint (gdbarch,
3458                                               p->get_relocated_address (objfile),
3459                                               bp_exception_master,
3460                                               &internal_breakpoint_ops);
3461               b->location = new_probe_location ("-probe-stap libgcc:unwind");
3462               b->enable_state = bp_disabled;
3463             }
3464
3465           continue;
3466         }
3467
3468       /* Otherwise, try the hook function.  */
3469
3470       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3471         continue;
3472
3473       gdbarch = get_objfile_arch (objfile);
3474
3475       if (bp_objfile_data->exception_msym.minsym == NULL)
3476         {
3477           struct bound_minimal_symbol debug_hook;
3478
3479           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3480           if (debug_hook.minsym == NULL)
3481             {
3482               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3483               continue;
3484             }
3485
3486           bp_objfile_data->exception_msym = debug_hook;
3487         }
3488
3489       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3490       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3491                                                  current_top_target ());
3492       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3493                                       &internal_breakpoint_ops);
3494       initialize_explicit_location (&explicit_loc);
3495       explicit_loc.function_name = ASTRDUP (func_name);
3496       b->location = new_explicit_location (&explicit_loc);
3497       b->enable_state = bp_disabled;
3498     }
3499 }
3500
3501 /* Does B have a location spec?  */
3502
3503 static int
3504 breakpoint_event_location_empty_p (const struct breakpoint *b)
3505 {
3506   return b->location != NULL && event_location_empty_p (b->location.get ());
3507 }
3508
3509 void
3510 update_breakpoints_after_exec (void)
3511 {
3512   struct breakpoint *b, *b_tmp;
3513   struct bp_location *bploc, **bplocp_tmp;
3514
3515   /* We're about to delete breakpoints from GDB's lists.  If the
3516      INSERTED flag is true, GDB will try to lift the breakpoints by
3517      writing the breakpoints' "shadow contents" back into memory.  The
3518      "shadow contents" are NOT valid after an exec, so GDB should not
3519      do that.  Instead, the target is responsible from marking
3520      breakpoints out as soon as it detects an exec.  We don't do that
3521      here instead, because there may be other attempts to delete
3522      breakpoints after detecting an exec and before reaching here.  */
3523   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3524     if (bploc->pspace == current_program_space)
3525       gdb_assert (!bploc->inserted);
3526
3527   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3528   {
3529     if (b->pspace != current_program_space)
3530       continue;
3531
3532     /* Solib breakpoints must be explicitly reset after an exec().  */
3533     if (b->type == bp_shlib_event)
3534       {
3535         delete_breakpoint (b);
3536         continue;
3537       }
3538
3539     /* JIT breakpoints must be explicitly reset after an exec().  */
3540     if (b->type == bp_jit_event)
3541       {
3542         delete_breakpoint (b);
3543         continue;
3544       }
3545
3546     /* Thread event breakpoints must be set anew after an exec(),
3547        as must overlay event and longjmp master breakpoints.  */
3548     if (b->type == bp_thread_event || b->type == bp_overlay_event
3549         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3550         || b->type == bp_exception_master)
3551       {
3552         delete_breakpoint (b);
3553         continue;
3554       }
3555
3556     /* Step-resume breakpoints are meaningless after an exec().  */
3557     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3558       {
3559         delete_breakpoint (b);
3560         continue;
3561       }
3562
3563     /* Just like single-step breakpoints.  */
3564     if (b->type == bp_single_step)
3565       {
3566         delete_breakpoint (b);
3567         continue;
3568       }
3569
3570     /* Longjmp and longjmp-resume breakpoints are also meaningless
3571        after an exec.  */
3572     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3573         || b->type == bp_longjmp_call_dummy
3574         || b->type == bp_exception || b->type == bp_exception_resume)
3575       {
3576         delete_breakpoint (b);
3577         continue;
3578       }
3579
3580     if (b->type == bp_catchpoint)
3581       {
3582         /* For now, none of the bp_catchpoint breakpoints need to
3583            do anything at this point.  In the future, if some of
3584            the catchpoints need to something, we will need to add
3585            a new method, and call this method from here.  */
3586         continue;
3587       }
3588
3589     /* bp_finish is a special case.  The only way we ought to be able
3590        to see one of these when an exec() has happened, is if the user
3591        caught a vfork, and then said "finish".  Ordinarily a finish just
3592        carries them to the call-site of the current callee, by setting
3593        a temporary bp there and resuming.  But in this case, the finish
3594        will carry them entirely through the vfork & exec.
3595
3596        We don't want to allow a bp_finish to remain inserted now.  But
3597        we can't safely delete it, 'cause finish_command has a handle to
3598        the bp on a bpstat, and will later want to delete it.  There's a
3599        chance (and I've seen it happen) that if we delete the bp_finish
3600        here, that its storage will get reused by the time finish_command
3601        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3602        We really must allow finish_command to delete a bp_finish.
3603
3604        In the absence of a general solution for the "how do we know
3605        it's safe to delete something others may have handles to?"
3606        problem, what we'll do here is just uninsert the bp_finish, and
3607        let finish_command delete it.
3608
3609        (We know the bp_finish is "doomed" in the sense that it's
3610        momentary, and will be deleted as soon as finish_command sees
3611        the inferior stopped.  So it doesn't matter that the bp's
3612        address is probably bogus in the new a.out, unlike e.g., the
3613        solib breakpoints.)  */
3614
3615     if (b->type == bp_finish)
3616       {
3617         continue;
3618       }
3619
3620     /* Without a symbolic address, we have little hope of the
3621        pre-exec() address meaning the same thing in the post-exec()
3622        a.out.  */
3623     if (breakpoint_event_location_empty_p (b))
3624       {
3625         delete_breakpoint (b);
3626         continue;
3627       }
3628   }
3629 }
3630
3631 int
3632 detach_breakpoints (ptid_t ptid)
3633 {
3634   struct bp_location *bl, **blp_tmp;
3635   int val = 0;
3636   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3637   struct inferior *inf = current_inferior ();
3638
3639   if (ptid.pid () == inferior_ptid.pid ())
3640     error (_("Cannot detach breakpoints of inferior_ptid"));
3641
3642   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3643   inferior_ptid = ptid;
3644   ALL_BP_LOCATIONS (bl, blp_tmp)
3645   {
3646     if (bl->pspace != inf->pspace)
3647       continue;
3648
3649     /* This function must physically remove breakpoints locations
3650        from the specified ptid, without modifying the breakpoint
3651        package's state.  Locations of type bp_loc_other are only
3652        maintained at GDB side.  So, there is no need to remove
3653        these bp_loc_other locations.  Moreover, removing these
3654        would modify the breakpoint package's state.  */
3655     if (bl->loc_type == bp_loc_other)
3656       continue;
3657
3658     if (bl->inserted)
3659       val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3660   }
3661
3662   return val;
3663 }
3664
3665 /* Remove the breakpoint location BL from the current address space.
3666    Note that this is used to detach breakpoints from a child fork.
3667    When we get here, the child isn't in the inferior list, and neither
3668    do we have objects to represent its address space --- we should
3669    *not* look at bl->pspace->aspace here.  */
3670
3671 static int
3672 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3673 {
3674   int val;
3675
3676   /* BL is never in moribund_locations by our callers.  */
3677   gdb_assert (bl->owner != NULL);
3678
3679   /* The type of none suggests that owner is actually deleted.
3680      This should not ever happen.  */
3681   gdb_assert (bl->owner->type != bp_none);
3682
3683   if (bl->loc_type == bp_loc_software_breakpoint
3684       || bl->loc_type == bp_loc_hardware_breakpoint)
3685     {
3686       /* "Normal" instruction breakpoint: either the standard
3687          trap-instruction bp (bp_breakpoint), or a
3688          bp_hardware_breakpoint.  */
3689
3690       /* First check to see if we have to handle an overlay.  */
3691       if (overlay_debugging == ovly_off
3692           || bl->section == NULL
3693           || !(section_is_overlay (bl->section)))
3694         {
3695           /* No overlay handling: just remove the breakpoint.  */
3696
3697           /* If we're trying to uninsert a memory breakpoint that we
3698              know is set in a dynamic object that is marked
3699              shlib_disabled, then either the dynamic object was
3700              removed with "remove-symbol-file" or with
3701              "nosharedlibrary".  In the former case, we don't know
3702              whether another dynamic object might have loaded over the
3703              breakpoint's address -- the user might well let us know
3704              about it next with add-symbol-file (the whole point of
3705              add-symbol-file is letting the user manually maintain a
3706              list of dynamically loaded objects).  If we have the
3707              breakpoint's shadow memory, that is, this is a software
3708              breakpoint managed by GDB, check whether the breakpoint
3709              is still inserted in memory, to avoid overwriting wrong
3710              code with stale saved shadow contents.  Note that HW
3711              breakpoints don't have shadow memory, as they're
3712              implemented using a mechanism that is not dependent on
3713              being able to modify the target's memory, and as such
3714              they should always be removed.  */
3715           if (bl->shlib_disabled
3716               && bl->target_info.shadow_len != 0
3717               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3718             val = 0;
3719           else
3720             val = bl->owner->ops->remove_location (bl, reason);
3721         }
3722       else
3723         {
3724           /* This breakpoint is in an overlay section.
3725              Did we set a breakpoint at the LMA?  */
3726           if (!overlay_events_enabled)
3727               {
3728                 /* Yes -- overlay event support is not active, so we
3729                    should have set a breakpoint at the LMA.  Remove it.  
3730                 */
3731                 /* Ignore any failures: if the LMA is in ROM, we will
3732                    have already warned when we failed to insert it.  */
3733                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3734                   target_remove_hw_breakpoint (bl->gdbarch,
3735                                                &bl->overlay_target_info);
3736                 else
3737                   target_remove_breakpoint (bl->gdbarch,
3738                                             &bl->overlay_target_info,
3739                                             reason);
3740               }
3741           /* Did we set a breakpoint at the VMA? 
3742              If so, we will have marked the breakpoint 'inserted'.  */
3743           if (bl->inserted)
3744             {
3745               /* Yes -- remove it.  Previously we did not bother to
3746                  remove the breakpoint if the section had been
3747                  unmapped, but let's not rely on that being safe.  We
3748                  don't know what the overlay manager might do.  */
3749
3750               /* However, we should remove *software* breakpoints only
3751                  if the section is still mapped, or else we overwrite
3752                  wrong code with the saved shadow contents.  */
3753               if (bl->loc_type == bp_loc_hardware_breakpoint
3754                   || section_is_mapped (bl->section))
3755                 val = bl->owner->ops->remove_location (bl, reason);
3756               else
3757                 val = 0;
3758             }
3759           else
3760             {
3761               /* No -- not inserted, so no need to remove.  No error.  */
3762               val = 0;
3763             }
3764         }
3765
3766       /* In some cases, we might not be able to remove a breakpoint in
3767          a shared library that has already been removed, but we have
3768          not yet processed the shlib unload event.  Similarly for an
3769          unloaded add-symbol-file object - the user might not yet have
3770          had the chance to remove-symbol-file it.  shlib_disabled will
3771          be set if the library/object has already been removed, but
3772          the breakpoint hasn't been uninserted yet, e.g., after
3773          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3774          always-inserted mode.  */
3775       if (val
3776           && (bl->loc_type == bp_loc_software_breakpoint
3777               && (bl->shlib_disabled
3778                   || solib_name_from_address (bl->pspace, bl->address)
3779                   || shared_objfile_contains_address_p (bl->pspace,
3780                                                         bl->address))))
3781         val = 0;
3782
3783       if (val)
3784         return val;
3785       bl->inserted = (reason == DETACH_BREAKPOINT);
3786     }
3787   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3788     {
3789       gdb_assert (bl->owner->ops != NULL
3790                   && bl->owner->ops->remove_location != NULL);
3791
3792       bl->inserted = (reason == DETACH_BREAKPOINT);
3793       bl->owner->ops->remove_location (bl, reason);
3794
3795       /* Failure to remove any of the hardware watchpoints comes here.  */
3796       if (reason == REMOVE_BREAKPOINT && bl->inserted)
3797         warning (_("Could not remove hardware watchpoint %d."),
3798                  bl->owner->number);
3799     }
3800   else if (bl->owner->type == bp_catchpoint
3801            && breakpoint_enabled (bl->owner)
3802            && !bl->duplicate)
3803     {
3804       gdb_assert (bl->owner->ops != NULL
3805                   && bl->owner->ops->remove_location != NULL);
3806
3807       val = bl->owner->ops->remove_location (bl, reason);
3808       if (val)
3809         return val;
3810
3811       bl->inserted = (reason == DETACH_BREAKPOINT);
3812     }
3813
3814   return 0;
3815 }
3816
3817 static int
3818 remove_breakpoint (struct bp_location *bl)
3819 {
3820   /* BL is never in moribund_locations by our callers.  */
3821   gdb_assert (bl->owner != NULL);
3822
3823   /* The type of none suggests that owner is actually deleted.
3824      This should not ever happen.  */
3825   gdb_assert (bl->owner->type != bp_none);
3826
3827   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3828
3829   switch_to_program_space_and_thread (bl->pspace);
3830
3831   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
3832 }
3833
3834 /* Clear the "inserted" flag in all breakpoints.  */
3835
3836 void
3837 mark_breakpoints_out (void)
3838 {
3839   struct bp_location *bl, **blp_tmp;
3840
3841   ALL_BP_LOCATIONS (bl, blp_tmp)
3842     if (bl->pspace == current_program_space)
3843       bl->inserted = 0;
3844 }
3845
3846 /* Clear the "inserted" flag in all breakpoints and delete any
3847    breakpoints which should go away between runs of the program.
3848
3849    Plus other such housekeeping that has to be done for breakpoints
3850    between runs.
3851
3852    Note: this function gets called at the end of a run (by
3853    generic_mourn_inferior) and when a run begins (by
3854    init_wait_for_inferior).  */
3855
3856
3857
3858 void
3859 breakpoint_init_inferior (enum inf_context context)
3860 {
3861   struct breakpoint *b, *b_tmp;
3862   struct program_space *pspace = current_program_space;
3863
3864   /* If breakpoint locations are shared across processes, then there's
3865      nothing to do.  */
3866   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3867     return;
3868
3869   mark_breakpoints_out ();
3870
3871   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3872   {
3873     if (b->loc && b->loc->pspace != pspace)
3874       continue;
3875
3876     switch (b->type)
3877       {
3878       case bp_call_dummy:
3879       case bp_longjmp_call_dummy:
3880
3881         /* If the call dummy breakpoint is at the entry point it will
3882            cause problems when the inferior is rerun, so we better get
3883            rid of it.  */
3884
3885       case bp_watchpoint_scope:
3886
3887         /* Also get rid of scope breakpoints.  */
3888
3889       case bp_shlib_event:
3890
3891         /* Also remove solib event breakpoints.  Their addresses may
3892            have changed since the last time we ran the program.
3893            Actually we may now be debugging against different target;
3894            and so the solib backend that installed this breakpoint may
3895            not be used in by the target.  E.g.,
3896
3897            (gdb) file prog-linux
3898            (gdb) run               # native linux target
3899            ...
3900            (gdb) kill
3901            (gdb) file prog-win.exe
3902            (gdb) tar rem :9999     # remote Windows gdbserver.
3903         */
3904
3905       case bp_step_resume:
3906
3907         /* Also remove step-resume breakpoints.  */
3908
3909       case bp_single_step:
3910
3911         /* Also remove single-step breakpoints.  */
3912
3913         delete_breakpoint (b);
3914         break;
3915
3916       case bp_watchpoint:
3917       case bp_hardware_watchpoint:
3918       case bp_read_watchpoint:
3919       case bp_access_watchpoint:
3920         {
3921           struct watchpoint *w = (struct watchpoint *) b;
3922
3923           /* Likewise for watchpoints on local expressions.  */
3924           if (w->exp_valid_block != NULL)
3925             delete_breakpoint (b);
3926           else
3927             {
3928               /* Get rid of existing locations, which are no longer
3929                  valid.  New ones will be created in
3930                  update_watchpoint, when the inferior is restarted.
3931                  The next update_global_location_list call will
3932                  garbage collect them.  */
3933               b->loc = NULL;
3934
3935               if (context == inf_starting)
3936                 {
3937                   /* Reset val field to force reread of starting value in
3938                      insert_breakpoints.  */
3939                   w->val.reset (nullptr);
3940                   w->val_valid = 0;
3941                 }
3942             }
3943         }
3944         break;
3945       default:
3946         break;
3947       }
3948   }
3949
3950   /* Get rid of the moribund locations.  */
3951   for (bp_location *bl : moribund_locations)
3952     decref_bp_location (&bl);
3953   moribund_locations.clear ();
3954 }
3955
3956 /* These functions concern about actual breakpoints inserted in the
3957    target --- to e.g. check if we need to do decr_pc adjustment or if
3958    we need to hop over the bkpt --- so we check for address space
3959    match, not program space.  */
3960
3961 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3962    exists at PC.  It returns ordinary_breakpoint_here if it's an
3963    ordinary breakpoint, or permanent_breakpoint_here if it's a
3964    permanent breakpoint.
3965    - When continuing from a location with an ordinary breakpoint, we
3966      actually single step once before calling insert_breakpoints.
3967    - When continuing from a location with a permanent breakpoint, we
3968      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3969      the target, to advance the PC past the breakpoint.  */
3970
3971 enum breakpoint_here
3972 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
3973 {
3974   struct bp_location *bl, **blp_tmp;
3975   int any_breakpoint_here = 0;
3976
3977   ALL_BP_LOCATIONS (bl, blp_tmp)
3978     {
3979       if (bl->loc_type != bp_loc_software_breakpoint
3980           && bl->loc_type != bp_loc_hardware_breakpoint)
3981         continue;
3982
3983       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3984       if ((breakpoint_enabled (bl->owner)
3985            || bl->permanent)
3986           && breakpoint_location_address_match (bl, aspace, pc))
3987         {
3988           if (overlay_debugging 
3989               && section_is_overlay (bl->section)
3990               && !section_is_mapped (bl->section))
3991             continue;           /* unmapped overlay -- can't be a match */
3992           else if (bl->permanent)
3993             return permanent_breakpoint_here;
3994           else
3995             any_breakpoint_here = 1;
3996         }
3997     }
3998
3999   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4000 }
4001
4002 /* See breakpoint.h.  */
4003
4004 int
4005 breakpoint_in_range_p (const address_space *aspace,
4006                        CORE_ADDR addr, ULONGEST len)
4007 {
4008   struct bp_location *bl, **blp_tmp;
4009
4010   ALL_BP_LOCATIONS (bl, blp_tmp)
4011     {
4012       if (bl->loc_type != bp_loc_software_breakpoint
4013           && bl->loc_type != bp_loc_hardware_breakpoint)
4014         continue;
4015
4016       if ((breakpoint_enabled (bl->owner)
4017            || bl->permanent)
4018           && breakpoint_location_address_range_overlap (bl, aspace,
4019                                                         addr, len))
4020         {
4021           if (overlay_debugging
4022               && section_is_overlay (bl->section)
4023               && !section_is_mapped (bl->section))
4024             {
4025               /* Unmapped overlay -- can't be a match.  */
4026               continue;
4027             }
4028
4029           return 1;
4030         }
4031     }
4032
4033   return 0;
4034 }
4035
4036 /* Return true if there's a moribund breakpoint at PC.  */
4037
4038 int
4039 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4040 {
4041   for (bp_location *loc : moribund_locations)
4042     if (breakpoint_location_address_match (loc, aspace, pc))
4043       return 1;
4044
4045   return 0;
4046 }
4047
4048 /* Returns non-zero iff BL is inserted at PC, in address space
4049    ASPACE.  */
4050
4051 static int
4052 bp_location_inserted_here_p (struct bp_location *bl,
4053                              const address_space *aspace, CORE_ADDR pc)
4054 {
4055   if (bl->inserted
4056       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4057                                    aspace, pc))
4058     {
4059       if (overlay_debugging
4060           && section_is_overlay (bl->section)
4061           && !section_is_mapped (bl->section))
4062         return 0;               /* unmapped overlay -- can't be a match */
4063       else
4064         return 1;
4065     }
4066   return 0;
4067 }
4068
4069 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4070
4071 int
4072 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4073 {
4074   struct bp_location **blp, **blp_tmp = NULL;
4075
4076   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4077     {
4078       struct bp_location *bl = *blp;
4079
4080       if (bl->loc_type != bp_loc_software_breakpoint
4081           && bl->loc_type != bp_loc_hardware_breakpoint)
4082         continue;
4083
4084       if (bp_location_inserted_here_p (bl, aspace, pc))
4085         return 1;
4086     }
4087   return 0;
4088 }
4089
4090 /* This function returns non-zero iff there is a software breakpoint
4091    inserted at PC.  */
4092
4093 int
4094 software_breakpoint_inserted_here_p (const address_space *aspace,
4095                                      CORE_ADDR pc)
4096 {
4097   struct bp_location **blp, **blp_tmp = NULL;
4098
4099   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4100     {
4101       struct bp_location *bl = *blp;
4102
4103       if (bl->loc_type != bp_loc_software_breakpoint)
4104         continue;
4105
4106       if (bp_location_inserted_here_p (bl, aspace, pc))
4107         return 1;
4108     }
4109
4110   return 0;
4111 }
4112
4113 /* See breakpoint.h.  */
4114
4115 int
4116 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4117                                      CORE_ADDR pc)
4118 {
4119   struct bp_location **blp, **blp_tmp = NULL;
4120
4121   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4122     {
4123       struct bp_location *bl = *blp;
4124
4125       if (bl->loc_type != bp_loc_hardware_breakpoint)
4126         continue;
4127
4128       if (bp_location_inserted_here_p (bl, aspace, pc))
4129         return 1;
4130     }
4131
4132   return 0;
4133 }
4134
4135 int
4136 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4137                                        CORE_ADDR addr, ULONGEST len)
4138 {
4139   struct breakpoint *bpt;
4140
4141   ALL_BREAKPOINTS (bpt)
4142     {
4143       struct bp_location *loc;
4144
4145       if (bpt->type != bp_hardware_watchpoint
4146           && bpt->type != bp_access_watchpoint)
4147         continue;
4148
4149       if (!breakpoint_enabled (bpt))
4150         continue;
4151
4152       for (loc = bpt->loc; loc; loc = loc->next)
4153         if (loc->pspace->aspace == aspace && loc->inserted)
4154           {
4155             CORE_ADDR l, h;
4156
4157             /* Check for intersection.  */
4158             l = std::max<CORE_ADDR> (loc->address, addr);
4159             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4160             if (l < h)
4161               return 1;
4162           }
4163     }
4164   return 0;
4165 }
4166 \f
4167
4168 /* bpstat stuff.  External routines' interfaces are documented
4169    in breakpoint.h.  */
4170
4171 int
4172 is_catchpoint (struct breakpoint *ep)
4173 {
4174   return (ep->type == bp_catchpoint);
4175 }
4176
4177 /* Frees any storage that is part of a bpstat.  Does not walk the
4178    'next' chain.  */
4179
4180 bpstats::~bpstats ()
4181 {
4182   if (bp_location_at != NULL)
4183     decref_bp_location (&bp_location_at);
4184 }
4185
4186 /* Clear a bpstat so that it says we are not at any breakpoint.
4187    Also free any storage that is part of a bpstat.  */
4188
4189 void
4190 bpstat_clear (bpstat *bsp)
4191 {
4192   bpstat p;
4193   bpstat q;
4194
4195   if (bsp == 0)
4196     return;
4197   p = *bsp;
4198   while (p != NULL)
4199     {
4200       q = p->next;
4201       delete p;
4202       p = q;
4203     }
4204   *bsp = NULL;
4205 }
4206
4207 bpstats::bpstats (const bpstats &other)
4208   : next (NULL),
4209     bp_location_at (other.bp_location_at),
4210     breakpoint_at (other.breakpoint_at),
4211     commands (other.commands),
4212     print (other.print),
4213     stop (other.stop),
4214     print_it (other.print_it)
4215 {
4216   if (other.old_val != NULL)
4217     old_val = release_value (value_copy (other.old_val.get ()));
4218   incref_bp_location (bp_location_at);
4219 }
4220
4221 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4222    is part of the bpstat is copied as well.  */
4223
4224 bpstat
4225 bpstat_copy (bpstat bs)
4226 {
4227   bpstat p = NULL;
4228   bpstat tmp;
4229   bpstat retval = NULL;
4230
4231   if (bs == NULL)
4232     return bs;
4233
4234   for (; bs != NULL; bs = bs->next)
4235     {
4236       tmp = new bpstats (*bs);
4237
4238       if (p == NULL)
4239         /* This is the first thing in the chain.  */
4240         retval = tmp;
4241       else
4242         p->next = tmp;
4243       p = tmp;
4244     }
4245   p->next = NULL;
4246   return retval;
4247 }
4248
4249 /* Find the bpstat associated with this breakpoint.  */
4250
4251 bpstat
4252 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4253 {
4254   if (bsp == NULL)
4255     return NULL;
4256
4257   for (; bsp != NULL; bsp = bsp->next)
4258     {
4259       if (bsp->breakpoint_at == breakpoint)
4260         return bsp;
4261     }
4262   return NULL;
4263 }
4264
4265 /* See breakpoint.h.  */
4266
4267 int
4268 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4269 {
4270   for (; bsp != NULL; bsp = bsp->next)
4271     {
4272       if (bsp->breakpoint_at == NULL)
4273         {
4274           /* A moribund location can never explain a signal other than
4275              GDB_SIGNAL_TRAP.  */
4276           if (sig == GDB_SIGNAL_TRAP)
4277             return 1;
4278         }
4279       else
4280         {
4281           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4282                                                         sig))
4283             return 1;
4284         }
4285     }
4286
4287   return 0;
4288 }
4289
4290 /* Put in *NUM the breakpoint number of the first breakpoint we are
4291    stopped at.  *BSP upon return is a bpstat which points to the
4292    remaining breakpoints stopped at (but which is not guaranteed to be
4293    good for anything but further calls to bpstat_num).
4294
4295    Return 0 if passed a bpstat which does not indicate any breakpoints.
4296    Return -1 if stopped at a breakpoint that has been deleted since
4297    we set it.
4298    Return 1 otherwise.  */
4299
4300 int
4301 bpstat_num (bpstat *bsp, int *num)
4302 {
4303   struct breakpoint *b;
4304
4305   if ((*bsp) == NULL)
4306     return 0;                   /* No more breakpoint values */
4307
4308   /* We assume we'll never have several bpstats that correspond to a
4309      single breakpoint -- otherwise, this function might return the
4310      same number more than once and this will look ugly.  */
4311   b = (*bsp)->breakpoint_at;
4312   *bsp = (*bsp)->next;
4313   if (b == NULL)
4314     return -1;                  /* breakpoint that's been deleted since */
4315
4316   *num = b->number;             /* We have its number */
4317   return 1;
4318 }
4319
4320 /* See breakpoint.h.  */
4321
4322 void
4323 bpstat_clear_actions (void)
4324 {
4325   bpstat bs;
4326
4327   if (inferior_ptid == null_ptid)
4328     return;
4329
4330   thread_info *tp = inferior_thread ();
4331   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4332     {
4333       bs->commands = NULL;
4334       bs->old_val.reset (nullptr);
4335     }
4336 }
4337
4338 /* Called when a command is about to proceed the inferior.  */
4339
4340 static void
4341 breakpoint_about_to_proceed (void)
4342 {
4343   if (inferior_ptid != null_ptid)
4344     {
4345       struct thread_info *tp = inferior_thread ();
4346
4347       /* Allow inferior function calls in breakpoint commands to not
4348          interrupt the command list.  When the call finishes
4349          successfully, the inferior will be standing at the same
4350          breakpoint as if nothing happened.  */
4351       if (tp->control.in_infcall)
4352         return;
4353     }
4354
4355   breakpoint_proceeded = 1;
4356 }
4357
4358 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4359    or its equivalent.  */
4360
4361 static int
4362 command_line_is_silent (struct command_line *cmd)
4363 {
4364   return cmd && (strcmp ("silent", cmd->line) == 0);
4365 }
4366
4367 /* Execute all the commands associated with all the breakpoints at
4368    this location.  Any of these commands could cause the process to
4369    proceed beyond this point, etc.  We look out for such changes by
4370    checking the global "breakpoint_proceeded" after each command.
4371
4372    Returns true if a breakpoint command resumed the inferior.  In that
4373    case, it is the caller's responsibility to recall it again with the
4374    bpstat of the current thread.  */
4375
4376 static int
4377 bpstat_do_actions_1 (bpstat *bsp)
4378 {
4379   bpstat bs;
4380   int again = 0;
4381
4382   /* Avoid endless recursion if a `source' command is contained
4383      in bs->commands.  */
4384   if (executing_breakpoint_commands)
4385     return 0;
4386
4387   scoped_restore save_executing
4388     = make_scoped_restore (&executing_breakpoint_commands, 1);
4389
4390   scoped_restore preventer = prevent_dont_repeat ();
4391
4392   /* This pointer will iterate over the list of bpstat's.  */
4393   bs = *bsp;
4394
4395   breakpoint_proceeded = 0;
4396   for (; bs != NULL; bs = bs->next)
4397     {
4398       struct command_line *cmd = NULL;
4399
4400       /* Take ownership of the BSP's command tree, if it has one.
4401
4402          The command tree could legitimately contain commands like
4403          'step' and 'next', which call clear_proceed_status, which
4404          frees stop_bpstat's command tree.  To make sure this doesn't
4405          free the tree we're executing out from under us, we need to
4406          take ownership of the tree ourselves.  Since a given bpstat's
4407          commands are only executed once, we don't need to copy it; we
4408          can clear the pointer in the bpstat, and make sure we free
4409          the tree when we're done.  */
4410       counted_command_line ccmd = bs->commands;
4411       bs->commands = NULL;
4412       if (ccmd != NULL)
4413         cmd = ccmd.get ();
4414       if (command_line_is_silent (cmd))
4415         {
4416           /* The action has been already done by bpstat_stop_status.  */
4417           cmd = cmd->next;
4418         }
4419
4420       while (cmd != NULL)
4421         {
4422           execute_control_command (cmd);
4423
4424           if (breakpoint_proceeded)
4425             break;
4426           else
4427             cmd = cmd->next;
4428         }
4429
4430       if (breakpoint_proceeded)
4431         {
4432           if (current_ui->async)
4433             /* If we are in async mode, then the target might be still
4434                running, not stopped at any breakpoint, so nothing for
4435                us to do here -- just return to the event loop.  */
4436             ;
4437           else
4438             /* In sync mode, when execute_control_command returns
4439                we're already standing on the next breakpoint.
4440                Breakpoint commands for that stop were not run, since
4441                execute_command does not run breakpoint commands --
4442                only command_line_handler does, but that one is not
4443                involved in execution of breakpoint commands.  So, we
4444                can now execute breakpoint commands.  It should be
4445                noted that making execute_command do bpstat actions is
4446                not an option -- in this case we'll have recursive
4447                invocation of bpstat for each breakpoint with a
4448                command, and can easily blow up GDB stack.  Instead, we
4449                return true, which will trigger the caller to recall us
4450                with the new stop_bpstat.  */
4451             again = 1;
4452           break;
4453         }
4454     }
4455   return again;
4456 }
4457
4458 /* Helper for bpstat_do_actions.  Get the current thread, if there's
4459    one, is alive and has execution.  Return NULL otherwise.  */
4460
4461 static thread_info *
4462 get_bpstat_thread ()
4463 {
4464   if (inferior_ptid == null_ptid || !target_has_execution)
4465     return NULL;
4466
4467   thread_info *tp = inferior_thread ();
4468   if (tp->state == THREAD_EXITED || tp->executing)
4469     return NULL;
4470   return tp;
4471 }
4472
4473 void
4474 bpstat_do_actions (void)
4475 {
4476   auto cleanup_if_error = make_scope_exit (bpstat_clear_actions);
4477   thread_info *tp;
4478
4479   /* Do any commands attached to breakpoint we are stopped at.  */
4480   while ((tp = get_bpstat_thread ()) != NULL)
4481     {
4482       /* Since in sync mode, bpstat_do_actions may resume the
4483          inferior, and only return when it is stopped at the next
4484          breakpoint, we keep doing breakpoint actions until it returns
4485          false to indicate the inferior was not resumed.  */
4486       if (!bpstat_do_actions_1 (&tp->control.stop_bpstat))
4487         break;
4488     }
4489
4490   cleanup_if_error.release ();
4491 }
4492
4493 /* Print out the (old or new) value associated with a watchpoint.  */
4494
4495 static void
4496 watchpoint_value_print (struct value *val, struct ui_file *stream)
4497 {
4498   if (val == NULL)
4499     fprintf_unfiltered (stream, _("<unreadable>"));
4500   else
4501     {
4502       struct value_print_options opts;
4503       get_user_print_options (&opts);
4504       value_print (val, stream, &opts);
4505     }
4506 }
4507
4508 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4509    debugging multiple threads.  */
4510
4511 void
4512 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4513 {
4514   if (uiout->is_mi_like_p ())
4515     return;
4516
4517   uiout->text ("\n");
4518
4519   if (show_thread_that_caused_stop ())
4520     {
4521       const char *name;
4522       struct thread_info *thr = inferior_thread ();
4523
4524       uiout->text ("Thread ");
4525       uiout->field_fmt ("thread-id", "%s", print_thread_id (thr));
4526
4527       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4528       if (name != NULL)
4529         {
4530           uiout->text (" \"");
4531           uiout->field_fmt ("name", "%s", name);
4532           uiout->text ("\"");
4533         }
4534
4535       uiout->text (" hit ");
4536     }
4537 }
4538
4539 /* Generic routine for printing messages indicating why we
4540    stopped.  The behavior of this function depends on the value
4541    'print_it' in the bpstat structure.  Under some circumstances we
4542    may decide not to print anything here and delegate the task to
4543    normal_stop().  */
4544
4545 static enum print_stop_action
4546 print_bp_stop_message (bpstat bs)
4547 {
4548   switch (bs->print_it)
4549     {
4550     case print_it_noop:
4551       /* Nothing should be printed for this bpstat entry.  */
4552       return PRINT_UNKNOWN;
4553       break;
4554
4555     case print_it_done:
4556       /* We still want to print the frame, but we already printed the
4557          relevant messages.  */
4558       return PRINT_SRC_AND_LOC;
4559       break;
4560
4561     case print_it_normal:
4562       {
4563         struct breakpoint *b = bs->breakpoint_at;
4564
4565         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4566            which has since been deleted.  */
4567         if (b == NULL)
4568           return PRINT_UNKNOWN;
4569
4570         /* Normal case.  Call the breakpoint's print_it method.  */
4571         return b->ops->print_it (bs);
4572       }
4573       break;
4574
4575     default:
4576       internal_error (__FILE__, __LINE__,
4577                       _("print_bp_stop_message: unrecognized enum value"));
4578       break;
4579     }
4580 }
4581
4582 /* A helper function that prints a shared library stopped event.  */
4583
4584 static void
4585 print_solib_event (int is_catchpoint)
4586 {
4587   bool any_deleted = !current_program_space->deleted_solibs.empty ();
4588   bool any_added = !current_program_space->added_solibs.empty ();
4589
4590   if (!is_catchpoint)
4591     {
4592       if (any_added || any_deleted)
4593         current_uiout->text (_("Stopped due to shared library event:\n"));
4594       else
4595         current_uiout->text (_("Stopped due to shared library event (no "
4596                                "libraries added or removed)\n"));
4597     }
4598
4599   if (current_uiout->is_mi_like_p ())
4600     current_uiout->field_string ("reason",
4601                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4602
4603   if (any_deleted)
4604     {
4605       current_uiout->text (_("  Inferior unloaded "));
4606       ui_out_emit_list list_emitter (current_uiout, "removed");
4607       for (int ix = 0; ix < current_program_space->deleted_solibs.size (); ix++)
4608         {
4609           const std::string &name = current_program_space->deleted_solibs[ix];
4610
4611           if (ix > 0)
4612             current_uiout->text ("    ");
4613           current_uiout->field_string ("library", name);
4614           current_uiout->text ("\n");
4615         }
4616     }
4617
4618   if (any_added)
4619     {
4620       current_uiout->text (_("  Inferior loaded "));
4621       ui_out_emit_list list_emitter (current_uiout, "added");
4622       bool first = true;
4623       for (so_list *iter : current_program_space->added_solibs)
4624         {
4625           if (!first)
4626             current_uiout->text ("    ");
4627           first = false;
4628           current_uiout->field_string ("library", iter->so_name);
4629           current_uiout->text ("\n");
4630         }
4631     }
4632 }
4633
4634 /* Print a message indicating what happened.  This is called from
4635    normal_stop().  The input to this routine is the head of the bpstat
4636    list - a list of the eventpoints that caused this stop.  KIND is
4637    the target_waitkind for the stopping event.  This
4638    routine calls the generic print routine for printing a message
4639    about reasons for stopping.  This will print (for example) the
4640    "Breakpoint n," part of the output.  The return value of this
4641    routine is one of:
4642
4643    PRINT_UNKNOWN: Means we printed nothing.
4644    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4645    code to print the location.  An example is 
4646    "Breakpoint 1, " which should be followed by
4647    the location.
4648    PRINT_SRC_ONLY: Means we printed something, but there is no need
4649    to also print the location part of the message.
4650    An example is the catch/throw messages, which
4651    don't require a location appended to the end.
4652    PRINT_NOTHING: We have done some printing and we don't need any 
4653    further info to be printed.  */
4654
4655 enum print_stop_action
4656 bpstat_print (bpstat bs, int kind)
4657 {
4658   enum print_stop_action val;
4659
4660   /* Maybe another breakpoint in the chain caused us to stop.
4661      (Currently all watchpoints go on the bpstat whether hit or not.
4662      That probably could (should) be changed, provided care is taken
4663      with respect to bpstat_explains_signal).  */
4664   for (; bs; bs = bs->next)
4665     {
4666       val = print_bp_stop_message (bs);
4667       if (val == PRINT_SRC_ONLY 
4668           || val == PRINT_SRC_AND_LOC 
4669           || val == PRINT_NOTHING)
4670         return val;
4671     }
4672
4673   /* If we had hit a shared library event breakpoint,
4674      print_bp_stop_message would print out this message.  If we hit an
4675      OS-level shared library event, do the same thing.  */
4676   if (kind == TARGET_WAITKIND_LOADED)
4677     {
4678       print_solib_event (0);
4679       return PRINT_NOTHING;
4680     }
4681
4682   /* We reached the end of the chain, or we got a null BS to start
4683      with and nothing was printed.  */
4684   return PRINT_UNKNOWN;
4685 }
4686
4687 /* Evaluate the boolean expression EXP and return the result.  */
4688
4689 static bool
4690 breakpoint_cond_eval (expression *exp)
4691 {
4692   struct value *mark = value_mark ();
4693   bool res = value_true (evaluate_expression (exp));
4694
4695   value_free_to_mark (mark);
4696   return res;
4697 }
4698
4699 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4700
4701 bpstats::bpstats (struct bp_location *bl, bpstat **bs_link_pointer)
4702   : next (NULL),
4703     bp_location_at (bl),
4704     breakpoint_at (bl->owner),
4705     commands (NULL),
4706     print (0),
4707     stop (0),
4708     print_it (print_it_normal)
4709 {
4710   incref_bp_location (bl);
4711   **bs_link_pointer = this;
4712   *bs_link_pointer = &next;
4713 }
4714
4715 bpstats::bpstats ()
4716   : next (NULL),
4717     bp_location_at (NULL),
4718     breakpoint_at (NULL),
4719     commands (NULL),
4720     print (0),
4721     stop (0),
4722     print_it (print_it_normal)
4723 {
4724 }
4725 \f
4726 /* The target has stopped with waitstatus WS.  Check if any hardware
4727    watchpoints have triggered, according to the target.  */
4728
4729 int
4730 watchpoints_triggered (struct target_waitstatus *ws)
4731 {
4732   bool stopped_by_watchpoint = target_stopped_by_watchpoint ();
4733   CORE_ADDR addr;
4734   struct breakpoint *b;
4735
4736   if (!stopped_by_watchpoint)
4737     {
4738       /* We were not stopped by a watchpoint.  Mark all watchpoints
4739          as not triggered.  */
4740       ALL_BREAKPOINTS (b)
4741         if (is_hardware_watchpoint (b))
4742           {
4743             struct watchpoint *w = (struct watchpoint *) b;
4744
4745             w->watchpoint_triggered = watch_triggered_no;
4746           }
4747
4748       return 0;
4749     }
4750
4751   if (!target_stopped_data_address (current_top_target (), &addr))
4752     {
4753       /* We were stopped by a watchpoint, but we don't know where.
4754          Mark all watchpoints as unknown.  */
4755       ALL_BREAKPOINTS (b)
4756         if (is_hardware_watchpoint (b))
4757           {
4758             struct watchpoint *w = (struct watchpoint *) b;
4759
4760             w->watchpoint_triggered = watch_triggered_unknown;
4761           }
4762
4763       return 1;
4764     }
4765
4766   /* The target could report the data address.  Mark watchpoints
4767      affected by this data address as triggered, and all others as not
4768      triggered.  */
4769
4770   ALL_BREAKPOINTS (b)
4771     if (is_hardware_watchpoint (b))
4772       {
4773         struct watchpoint *w = (struct watchpoint *) b;
4774         struct bp_location *loc;
4775
4776         w->watchpoint_triggered = watch_triggered_no;
4777         for (loc = b->loc; loc; loc = loc->next)
4778           {
4779             if (is_masked_watchpoint (b))
4780               {
4781                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4782                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4783
4784                 if (newaddr == start)
4785                   {
4786                     w->watchpoint_triggered = watch_triggered_yes;
4787                     break;
4788                   }
4789               }
4790             /* Exact match not required.  Within range is sufficient.  */
4791             else if (target_watchpoint_addr_within_range (current_top_target (),
4792                                                          addr, loc->address,
4793                                                          loc->length))
4794               {
4795                 w->watchpoint_triggered = watch_triggered_yes;
4796                 break;
4797               }
4798           }
4799       }
4800
4801   return 1;
4802 }
4803
4804 /* Possible return values for watchpoint_check.  */
4805 enum wp_check_result
4806   {
4807     /* The watchpoint has been deleted.  */
4808     WP_DELETED = 1,
4809
4810     /* The value has changed.  */
4811     WP_VALUE_CHANGED = 2,
4812
4813     /* The value has not changed.  */
4814     WP_VALUE_NOT_CHANGED = 3,
4815
4816     /* Ignore this watchpoint, no matter if the value changed or not.  */
4817     WP_IGNORE = 4,
4818   };
4819
4820 #define BP_TEMPFLAG 1
4821 #define BP_HARDWAREFLAG 2
4822
4823 /* Evaluate watchpoint condition expression and check if its value
4824    changed.  */
4825
4826 static wp_check_result
4827 watchpoint_check (bpstat bs)
4828 {
4829   struct watchpoint *b;
4830   struct frame_info *fr;
4831   int within_current_scope;
4832
4833   /* BS is built from an existing struct breakpoint.  */
4834   gdb_assert (bs->breakpoint_at != NULL);
4835   b = (struct watchpoint *) bs->breakpoint_at;
4836
4837   /* If this is a local watchpoint, we only want to check if the
4838      watchpoint frame is in scope if the current thread is the thread
4839      that was used to create the watchpoint.  */
4840   if (!watchpoint_in_thread_scope (b))
4841     return WP_IGNORE;
4842
4843   if (b->exp_valid_block == NULL)
4844     within_current_scope = 1;
4845   else
4846     {
4847       struct frame_info *frame = get_current_frame ();
4848       struct gdbarch *frame_arch = get_frame_arch (frame);
4849       CORE_ADDR frame_pc = get_frame_pc (frame);
4850
4851       /* stack_frame_destroyed_p() returns a non-zero value if we're
4852          still in the function but the stack frame has already been
4853          invalidated.  Since we can't rely on the values of local
4854          variables after the stack has been destroyed, we are treating
4855          the watchpoint in that state as `not changed' without further
4856          checking.  Don't mark watchpoints as changed if the current
4857          frame is in an epilogue - even if they are in some other
4858          frame, our view of the stack is likely to be wrong and
4859          frame_find_by_id could error out.  */
4860       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
4861         return WP_IGNORE;
4862
4863       fr = frame_find_by_id (b->watchpoint_frame);
4864       within_current_scope = (fr != NULL);
4865
4866       /* If we've gotten confused in the unwinder, we might have
4867          returned a frame that can't describe this variable.  */
4868       if (within_current_scope)
4869         {
4870           struct symbol *function;
4871
4872           function = get_frame_function (fr);
4873           if (function == NULL
4874               || !contained_in (b->exp_valid_block,
4875                                 SYMBOL_BLOCK_VALUE (function)))
4876             within_current_scope = 0;
4877         }
4878
4879       if (within_current_scope)
4880         /* If we end up stopping, the current frame will get selected
4881            in normal_stop.  So this call to select_frame won't affect
4882            the user.  */
4883         select_frame (fr);
4884     }
4885
4886   if (within_current_scope)
4887     {
4888       /* We use value_{,free_to_}mark because it could be a *long*
4889          time before we return to the command level and call
4890          free_all_values.  We can't call free_all_values because we
4891          might be in the middle of evaluating a function call.  */
4892
4893       int pc = 0;
4894       struct value *mark;
4895       struct value *new_val;
4896
4897       if (is_masked_watchpoint (b))
4898         /* Since we don't know the exact trigger address (from
4899            stopped_data_address), just tell the user we've triggered
4900            a mask watchpoint.  */
4901         return WP_VALUE_CHANGED;
4902
4903       mark = value_mark ();
4904       fetch_subexp_value (b->exp.get (), &pc, &new_val, NULL, NULL, 0);
4905
4906       if (b->val_bitsize != 0)
4907         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
4908
4909       /* We use value_equal_contents instead of value_equal because
4910          the latter coerces an array to a pointer, thus comparing just
4911          the address of the array instead of its contents.  This is
4912          not what we want.  */
4913       if ((b->val != NULL) != (new_val != NULL)
4914           || (b->val != NULL && !value_equal_contents (b->val.get (),
4915                                                        new_val)))
4916         {
4917           bs->old_val = b->val;
4918           b->val = release_value (new_val);
4919           b->val_valid = 1;
4920           if (new_val != NULL)
4921             value_free_to_mark (mark);
4922           return WP_VALUE_CHANGED;
4923         }
4924       else
4925         {
4926           /* Nothing changed.  */
4927           value_free_to_mark (mark);
4928           return WP_VALUE_NOT_CHANGED;
4929         }
4930     }
4931   else
4932     {
4933       /* This seems like the only logical thing to do because
4934          if we temporarily ignored the watchpoint, then when
4935          we reenter the block in which it is valid it contains
4936          garbage (in the case of a function, it may have two
4937          garbage values, one before and one after the prologue).
4938          So we can't even detect the first assignment to it and
4939          watch after that (since the garbage may or may not equal
4940          the first value assigned).  */
4941       /* We print all the stop information in
4942          breakpoint_ops->print_it, but in this case, by the time we
4943          call breakpoint_ops->print_it this bp will be deleted
4944          already.  So we have no choice but print the information
4945          here.  */
4946
4947       SWITCH_THRU_ALL_UIS ()
4948         {
4949           struct ui_out *uiout = current_uiout;
4950
4951           if (uiout->is_mi_like_p ())
4952             uiout->field_string
4953               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4954           uiout->text ("\nWatchpoint ");
4955           uiout->field_int ("wpnum", b->number);
4956           uiout->text (" deleted because the program has left the block in\n"
4957                        "which its expression is valid.\n");
4958         }
4959
4960       /* Make sure the watchpoint's commands aren't executed.  */
4961       b->commands = NULL;
4962       watchpoint_del_at_next_stop (b);
4963
4964       return WP_DELETED;
4965     }
4966 }
4967
4968 /* Return true if it looks like target has stopped due to hitting
4969    breakpoint location BL.  This function does not check if we should
4970    stop, only if BL explains the stop.  */
4971
4972 static int
4973 bpstat_check_location (const struct bp_location *bl,
4974                        const address_space *aspace, CORE_ADDR bp_addr,
4975                        const struct target_waitstatus *ws)
4976 {
4977   struct breakpoint *b = bl->owner;
4978
4979   /* BL is from an existing breakpoint.  */
4980   gdb_assert (b != NULL);
4981
4982   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4983 }
4984
4985 /* Determine if the watched values have actually changed, and we
4986    should stop.  If not, set BS->stop to 0.  */
4987
4988 static void
4989 bpstat_check_watchpoint (bpstat bs)
4990 {
4991   const struct bp_location *bl;
4992   struct watchpoint *b;
4993
4994   /* BS is built for existing struct breakpoint.  */
4995   bl = bs->bp_location_at;
4996   gdb_assert (bl != NULL);
4997   b = (struct watchpoint *) bs->breakpoint_at;
4998   gdb_assert (b != NULL);
4999
5000     {
5001       int must_check_value = 0;
5002       
5003       if (b->type == bp_watchpoint)
5004         /* For a software watchpoint, we must always check the
5005            watched value.  */
5006         must_check_value = 1;
5007       else if (b->watchpoint_triggered == watch_triggered_yes)
5008         /* We have a hardware watchpoint (read, write, or access)
5009            and the target earlier reported an address watched by
5010            this watchpoint.  */
5011         must_check_value = 1;
5012       else if (b->watchpoint_triggered == watch_triggered_unknown
5013                && b->type == bp_hardware_watchpoint)
5014         /* We were stopped by a hardware watchpoint, but the target could
5015            not report the data address.  We must check the watchpoint's
5016            value.  Access and read watchpoints are out of luck; without
5017            a data address, we can't figure it out.  */
5018         must_check_value = 1;
5019
5020       if (must_check_value)
5021         {
5022           wp_check_result e;
5023
5024           TRY
5025             {
5026               e = watchpoint_check (bs);
5027             }
5028           CATCH (ex, RETURN_MASK_ALL)
5029             {
5030               exception_fprintf (gdb_stderr, ex,
5031                                  "Error evaluating expression "
5032                                  "for watchpoint %d\n",
5033                                  b->number);
5034
5035               SWITCH_THRU_ALL_UIS ()
5036                 {
5037                   printf_filtered (_("Watchpoint %d deleted.\n"),
5038                                    b->number);
5039                 }
5040               watchpoint_del_at_next_stop (b);
5041               e = WP_DELETED;
5042             }
5043           END_CATCH
5044
5045           switch (e)
5046             {
5047             case WP_DELETED:
5048               /* We've already printed what needs to be printed.  */
5049               bs->print_it = print_it_done;
5050               /* Stop.  */
5051               break;
5052             case WP_IGNORE:
5053               bs->print_it = print_it_noop;
5054               bs->stop = 0;
5055               break;
5056             case WP_VALUE_CHANGED:
5057               if (b->type == bp_read_watchpoint)
5058                 {
5059                   /* There are two cases to consider here:
5060
5061                      1. We're watching the triggered memory for reads.
5062                      In that case, trust the target, and always report
5063                      the watchpoint hit to the user.  Even though
5064                      reads don't cause value changes, the value may
5065                      have changed since the last time it was read, and
5066                      since we're not trapping writes, we will not see
5067                      those, and as such we should ignore our notion of
5068                      old value.
5069
5070                      2. We're watching the triggered memory for both
5071                      reads and writes.  There are two ways this may
5072                      happen:
5073
5074                      2.1. This is a target that can't break on data
5075                      reads only, but can break on accesses (reads or
5076                      writes), such as e.g., x86.  We detect this case
5077                      at the time we try to insert read watchpoints.
5078
5079                      2.2. Otherwise, the target supports read
5080                      watchpoints, but, the user set an access or write
5081                      watchpoint watching the same memory as this read
5082                      watchpoint.
5083
5084                      If we're watching memory writes as well as reads,
5085                      ignore watchpoint hits when we find that the
5086                      value hasn't changed, as reads don't cause
5087                      changes.  This still gives false positives when
5088                      the program writes the same value to memory as
5089                      what there was already in memory (we will confuse
5090                      it for a read), but it's much better than
5091                      nothing.  */
5092
5093                   int other_write_watchpoint = 0;
5094
5095                   if (bl->watchpoint_type == hw_read)
5096                     {
5097                       struct breakpoint *other_b;
5098
5099                       ALL_BREAKPOINTS (other_b)
5100                         if (other_b->type == bp_hardware_watchpoint
5101                             || other_b->type == bp_access_watchpoint)
5102                           {
5103                             struct watchpoint *other_w =
5104                               (struct watchpoint *) other_b;
5105
5106                             if (other_w->watchpoint_triggered
5107                                 == watch_triggered_yes)
5108                               {
5109                                 other_write_watchpoint = 1;
5110                                 break;
5111                               }
5112                           }
5113                     }
5114
5115                   if (other_write_watchpoint
5116                       || bl->watchpoint_type == hw_access)
5117                     {
5118                       /* We're watching the same memory for writes,
5119                          and the value changed since the last time we
5120                          updated it, so this trap must be for a write.
5121                          Ignore it.  */
5122                       bs->print_it = print_it_noop;
5123                       bs->stop = 0;
5124                     }
5125                 }
5126               break;
5127             case WP_VALUE_NOT_CHANGED:
5128               if (b->type == bp_hardware_watchpoint
5129                   || b->type == bp_watchpoint)
5130                 {
5131                   /* Don't stop: write watchpoints shouldn't fire if
5132                      the value hasn't changed.  */
5133                   bs->print_it = print_it_noop;
5134                   bs->stop = 0;
5135                 }
5136               /* Stop.  */
5137               break;
5138             default:
5139               /* Can't happen.  */
5140               break;
5141             }
5142         }
5143       else      /* must_check_value == 0 */
5144         {
5145           /* This is a case where some watchpoint(s) triggered, but
5146              not at the address of this watchpoint, or else no
5147              watchpoint triggered after all.  So don't print
5148              anything for this watchpoint.  */
5149           bs->print_it = print_it_noop;
5150           bs->stop = 0;
5151         }
5152     }
5153 }
5154
5155 /* For breakpoints that are currently marked as telling gdb to stop,
5156    check conditions (condition proper, frame, thread and ignore count)
5157    of breakpoint referred to by BS.  If we should not stop for this
5158    breakpoint, set BS->stop to 0.  */
5159
5160 static void
5161 bpstat_check_breakpoint_conditions (bpstat bs, thread_info *thread)
5162 {
5163   const struct bp_location *bl;
5164   struct breakpoint *b;
5165   /* Assume stop.  */
5166   bool condition_result = true;
5167   struct expression *cond;
5168
5169   gdb_assert (bs->stop);
5170
5171   /* BS is built for existing struct breakpoint.  */
5172   bl = bs->bp_location_at;
5173   gdb_assert (bl != NULL);
5174   b = bs->breakpoint_at;
5175   gdb_assert (b != NULL);
5176
5177   /* Even if the target evaluated the condition on its end and notified GDB, we
5178      need to do so again since GDB does not know if we stopped due to a
5179      breakpoint or a single step breakpoint.  */
5180
5181   if (frame_id_p (b->frame_id)
5182       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5183     {
5184       bs->stop = 0;
5185       return;
5186     }
5187
5188   /* If this is a thread/task-specific breakpoint, don't waste cpu
5189      evaluating the condition if this isn't the specified
5190      thread/task.  */
5191   if ((b->thread != -1 && b->thread != thread->global_num)
5192       || (b->task != 0 && b->task != ada_get_task_number (thread)))
5193     {
5194       bs->stop = 0;
5195       return;
5196     }
5197
5198   /* Evaluate extension language breakpoints that have a "stop" method
5199      implemented.  */
5200   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5201
5202   if (is_watchpoint (b))
5203     {
5204       struct watchpoint *w = (struct watchpoint *) b;
5205
5206       cond = w->cond_exp.get ();
5207     }
5208   else
5209     cond = bl->cond.get ();
5210
5211   if (cond && b->disposition != disp_del_at_next_stop)
5212     {
5213       int within_current_scope = 1;
5214       struct watchpoint * w;
5215
5216       /* We use value_mark and value_free_to_mark because it could
5217          be a long time before we return to the command level and
5218          call free_all_values.  We can't call free_all_values
5219          because we might be in the middle of evaluating a
5220          function call.  */
5221       struct value *mark = value_mark ();
5222
5223       if (is_watchpoint (b))
5224         w = (struct watchpoint *) b;
5225       else
5226         w = NULL;
5227
5228       /* Need to select the frame, with all that implies so that
5229          the conditions will have the right context.  Because we
5230          use the frame, we will not see an inlined function's
5231          variables when we arrive at a breakpoint at the start
5232          of the inlined function; the current frame will be the
5233          call site.  */
5234       if (w == NULL || w->cond_exp_valid_block == NULL)
5235         select_frame (get_current_frame ());
5236       else
5237         {
5238           struct frame_info *frame;
5239
5240           /* For local watchpoint expressions, which particular
5241              instance of a local is being watched matters, so we
5242              keep track of the frame to evaluate the expression
5243              in.  To evaluate the condition however, it doesn't
5244              really matter which instantiation of the function
5245              where the condition makes sense triggers the
5246              watchpoint.  This allows an expression like "watch
5247              global if q > 10" set in `func', catch writes to
5248              global on all threads that call `func', or catch
5249              writes on all recursive calls of `func' by a single
5250              thread.  We simply always evaluate the condition in
5251              the innermost frame that's executing where it makes
5252              sense to evaluate the condition.  It seems
5253              intuitive.  */
5254           frame = block_innermost_frame (w->cond_exp_valid_block);
5255           if (frame != NULL)
5256             select_frame (frame);
5257           else
5258             within_current_scope = 0;
5259         }
5260       if (within_current_scope)
5261         {
5262           TRY
5263             {
5264               condition_result = breakpoint_cond_eval (cond);
5265             }
5266           CATCH (ex, RETURN_MASK_ALL)
5267             {
5268               exception_fprintf (gdb_stderr, ex,
5269                                  "Error in testing breakpoint condition:\n");
5270             }
5271           END_CATCH
5272         }
5273       else
5274         {
5275           warning (_("Watchpoint condition cannot be tested "
5276                      "in the current scope"));
5277           /* If we failed to set the right context for this
5278              watchpoint, unconditionally report it.  */
5279         }
5280       /* FIXME-someday, should give breakpoint #.  */
5281       value_free_to_mark (mark);
5282     }
5283
5284   if (cond && !condition_result)
5285     {
5286       bs->stop = 0;
5287     }
5288   else if (b->ignore_count > 0)
5289     {
5290       b->ignore_count--;
5291       bs->stop = 0;
5292       /* Increase the hit count even though we don't stop.  */
5293       ++(b->hit_count);
5294       gdb::observers::breakpoint_modified.notify (b);
5295     }   
5296 }
5297
5298 /* Returns true if we need to track moribund locations of LOC's type
5299    on the current target.  */
5300
5301 static int
5302 need_moribund_for_location_type (struct bp_location *loc)
5303 {
5304   return ((loc->loc_type == bp_loc_software_breakpoint
5305            && !target_supports_stopped_by_sw_breakpoint ())
5306           || (loc->loc_type == bp_loc_hardware_breakpoint
5307               && !target_supports_stopped_by_hw_breakpoint ()));
5308 }
5309
5310 /* See breakpoint.h.  */
5311
5312 bpstat
5313 build_bpstat_chain (const address_space *aspace, CORE_ADDR bp_addr,
5314                     const struct target_waitstatus *ws)
5315 {
5316   struct breakpoint *b;
5317   bpstat bs_head = NULL, *bs_link = &bs_head;
5318
5319   ALL_BREAKPOINTS (b)
5320     {
5321       if (!breakpoint_enabled (b))
5322         continue;
5323
5324       for (bp_location *bl = b->loc; bl != NULL; bl = bl->next)
5325         {
5326           /* For hardware watchpoints, we look only at the first
5327              location.  The watchpoint_check function will work on the
5328              entire expression, not the individual locations.  For
5329              read watchpoints, the watchpoints_triggered function has
5330              checked all locations already.  */
5331           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5332             break;
5333
5334           if (!bl->enabled || bl->shlib_disabled)
5335             continue;
5336
5337           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5338             continue;
5339
5340           /* Come here if it's a watchpoint, or if the break address
5341              matches.  */
5342
5343           bpstat bs = new bpstats (bl, &bs_link);       /* Alloc a bpstat to
5344                                                            explain stop.  */
5345
5346           /* Assume we stop.  Should we find a watchpoint that is not
5347              actually triggered, or if the condition of the breakpoint
5348              evaluates as false, we'll reset 'stop' to 0.  */
5349           bs->stop = 1;
5350           bs->print = 1;
5351
5352           /* If this is a scope breakpoint, mark the associated
5353              watchpoint as triggered so that we will handle the
5354              out-of-scope event.  We'll get to the watchpoint next
5355              iteration.  */
5356           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5357             {
5358               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5359
5360               w->watchpoint_triggered = watch_triggered_yes;
5361             }
5362         }
5363     }
5364
5365   /* Check if a moribund breakpoint explains the stop.  */
5366   if (!target_supports_stopped_by_sw_breakpoint ()
5367       || !target_supports_stopped_by_hw_breakpoint ())
5368     {
5369       for (bp_location *loc : moribund_locations)
5370         {
5371           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5372               && need_moribund_for_location_type (loc))
5373             {
5374               bpstat bs = new bpstats (loc, &bs_link);
5375               /* For hits of moribund locations, we should just proceed.  */
5376               bs->stop = 0;
5377               bs->print = 0;
5378               bs->print_it = print_it_noop;
5379             }
5380         }
5381     }
5382
5383   return bs_head;
5384 }
5385
5386 /* See breakpoint.h.  */
5387
5388 bpstat
5389 bpstat_stop_status (const address_space *aspace,
5390                     CORE_ADDR bp_addr, thread_info *thread,
5391                     const struct target_waitstatus *ws,
5392                     bpstat stop_chain)
5393 {
5394   struct breakpoint *b = NULL;
5395   /* First item of allocated bpstat's.  */
5396   bpstat bs_head = stop_chain;
5397   bpstat bs;
5398   int need_remove_insert;
5399   int removed_any;
5400
5401   /* First, build the bpstat chain with locations that explain a
5402      target stop, while being careful to not set the target running,
5403      as that may invalidate locations (in particular watchpoint
5404      locations are recreated).  Resuming will happen here with
5405      breakpoint conditions or watchpoint expressions that include
5406      inferior function calls.  */
5407   if (bs_head == NULL)
5408     bs_head = build_bpstat_chain (aspace, bp_addr, ws);
5409
5410   /* A bit of special processing for shlib breakpoints.  We need to
5411      process solib loading here, so that the lists of loaded and
5412      unloaded libraries are correct before we handle "catch load" and
5413      "catch unload".  */
5414   for (bs = bs_head; bs != NULL; bs = bs->next)
5415     {
5416       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5417         {
5418           handle_solib_event ();
5419           break;
5420         }
5421     }
5422
5423   /* Now go through the locations that caused the target to stop, and
5424      check whether we're interested in reporting this stop to higher
5425      layers, or whether we should resume the target transparently.  */
5426
5427   removed_any = 0;
5428
5429   for (bs = bs_head; bs != NULL; bs = bs->next)
5430     {
5431       if (!bs->stop)
5432         continue;
5433
5434       b = bs->breakpoint_at;
5435       b->ops->check_status (bs);
5436       if (bs->stop)
5437         {
5438           bpstat_check_breakpoint_conditions (bs, thread);
5439
5440           if (bs->stop)
5441             {
5442               ++(b->hit_count);
5443               gdb::observers::breakpoint_modified.notify (b);
5444
5445               /* We will stop here.  */
5446               if (b->disposition == disp_disable)
5447                 {
5448                   --(b->enable_count);
5449                   if (b->enable_count <= 0)
5450                     b->enable_state = bp_disabled;
5451                   removed_any = 1;
5452                 }
5453               if (b->silent)
5454                 bs->print = 0;
5455               bs->commands = b->commands;
5456               if (command_line_is_silent (bs->commands
5457                                           ? bs->commands.get () : NULL))
5458                 bs->print = 0;
5459
5460               b->ops->after_condition_true (bs);
5461             }
5462
5463         }
5464
5465       /* Print nothing for this entry if we don't stop or don't
5466          print.  */
5467       if (!bs->stop || !bs->print)
5468         bs->print_it = print_it_noop;
5469     }
5470
5471   /* If we aren't stopping, the value of some hardware watchpoint may
5472      not have changed, but the intermediate memory locations we are
5473      watching may have.  Don't bother if we're stopping; this will get
5474      done later.  */
5475   need_remove_insert = 0;
5476   if (! bpstat_causes_stop (bs_head))
5477     for (bs = bs_head; bs != NULL; bs = bs->next)
5478       if (!bs->stop
5479           && bs->breakpoint_at
5480           && is_hardware_watchpoint (bs->breakpoint_at))
5481         {
5482           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5483
5484           update_watchpoint (w, 0 /* don't reparse.  */);
5485           need_remove_insert = 1;
5486         }
5487
5488   if (need_remove_insert)
5489     update_global_location_list (UGLL_MAY_INSERT);
5490   else if (removed_any)
5491     update_global_location_list (UGLL_DONT_INSERT);
5492
5493   return bs_head;
5494 }
5495
5496 static void
5497 handle_jit_event (void)
5498 {
5499   struct frame_info *frame;
5500   struct gdbarch *gdbarch;
5501
5502   if (debug_infrun)
5503     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5504
5505   /* Switch terminal for any messages produced by
5506      breakpoint_re_set.  */
5507   target_terminal::ours_for_output ();
5508
5509   frame = get_current_frame ();
5510   gdbarch = get_frame_arch (frame);
5511
5512   jit_event_handler (gdbarch);
5513
5514   target_terminal::inferior ();
5515 }
5516
5517 /* Prepare WHAT final decision for infrun.  */
5518
5519 /* Decide what infrun needs to do with this bpstat.  */
5520
5521 struct bpstat_what
5522 bpstat_what (bpstat bs_head)
5523 {
5524   struct bpstat_what retval;
5525   bpstat bs;
5526
5527   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5528   retval.call_dummy = STOP_NONE;
5529   retval.is_longjmp = 0;
5530
5531   for (bs = bs_head; bs != NULL; bs = bs->next)
5532     {
5533       /* Extract this BS's action.  After processing each BS, we check
5534          if its action overrides all we've seem so far.  */
5535       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5536       enum bptype bptype;
5537
5538       if (bs->breakpoint_at == NULL)
5539         {
5540           /* I suspect this can happen if it was a momentary
5541              breakpoint which has since been deleted.  */
5542           bptype = bp_none;
5543         }
5544       else
5545         bptype = bs->breakpoint_at->type;
5546
5547       switch (bptype)
5548         {
5549         case bp_none:
5550           break;
5551         case bp_breakpoint:
5552         case bp_hardware_breakpoint:
5553         case bp_single_step:
5554         case bp_until:
5555         case bp_finish:
5556         case bp_shlib_event:
5557           if (bs->stop)
5558             {
5559               if (bs->print)
5560                 this_action = BPSTAT_WHAT_STOP_NOISY;
5561               else
5562                 this_action = BPSTAT_WHAT_STOP_SILENT;
5563             }
5564           else
5565             this_action = BPSTAT_WHAT_SINGLE;
5566           break;
5567         case bp_watchpoint:
5568         case bp_hardware_watchpoint:
5569         case bp_read_watchpoint:
5570         case bp_access_watchpoint:
5571           if (bs->stop)
5572             {
5573               if (bs->print)
5574                 this_action = BPSTAT_WHAT_STOP_NOISY;
5575               else
5576                 this_action = BPSTAT_WHAT_STOP_SILENT;
5577             }
5578           else
5579             {
5580               /* There was a watchpoint, but we're not stopping.
5581                  This requires no further action.  */
5582             }
5583           break;
5584         case bp_longjmp:
5585         case bp_longjmp_call_dummy:
5586         case bp_exception:
5587           if (bs->stop)
5588             {
5589               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5590               retval.is_longjmp = bptype != bp_exception;
5591             }
5592           else
5593             this_action = BPSTAT_WHAT_SINGLE;
5594           break;
5595         case bp_longjmp_resume:
5596         case bp_exception_resume:
5597           if (bs->stop)
5598             {
5599               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5600               retval.is_longjmp = bptype == bp_longjmp_resume;
5601             }
5602           else
5603             this_action = BPSTAT_WHAT_SINGLE;
5604           break;
5605         case bp_step_resume:
5606           if (bs->stop)
5607             this_action = BPSTAT_WHAT_STEP_RESUME;
5608           else
5609             {
5610               /* It is for the wrong frame.  */
5611               this_action = BPSTAT_WHAT_SINGLE;
5612             }
5613           break;
5614         case bp_hp_step_resume:
5615           if (bs->stop)
5616             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5617           else
5618             {
5619               /* It is for the wrong frame.  */
5620               this_action = BPSTAT_WHAT_SINGLE;
5621             }
5622           break;
5623         case bp_watchpoint_scope:
5624         case bp_thread_event:
5625         case bp_overlay_event:
5626         case bp_longjmp_master:
5627         case bp_std_terminate_master:
5628         case bp_exception_master:
5629           this_action = BPSTAT_WHAT_SINGLE;
5630           break;
5631         case bp_catchpoint:
5632           if (bs->stop)
5633             {
5634               if (bs->print)
5635                 this_action = BPSTAT_WHAT_STOP_NOISY;
5636               else
5637                 this_action = BPSTAT_WHAT_STOP_SILENT;
5638             }
5639           else
5640             {
5641               /* There was a catchpoint, but we're not stopping.
5642                  This requires no further action.  */
5643             }
5644           break;
5645         case bp_jit_event:
5646           this_action = BPSTAT_WHAT_SINGLE;
5647           break;
5648         case bp_call_dummy:
5649           /* Make sure the action is stop (silent or noisy),
5650              so infrun.c pops the dummy frame.  */
5651           retval.call_dummy = STOP_STACK_DUMMY;
5652           this_action = BPSTAT_WHAT_STOP_SILENT;
5653           break;
5654         case bp_std_terminate:
5655           /* Make sure the action is stop (silent or noisy),
5656              so infrun.c pops the dummy frame.  */
5657           retval.call_dummy = STOP_STD_TERMINATE;
5658           this_action = BPSTAT_WHAT_STOP_SILENT;
5659           break;
5660         case bp_tracepoint:
5661         case bp_fast_tracepoint:
5662         case bp_static_tracepoint:
5663           /* Tracepoint hits should not be reported back to GDB, and
5664              if one got through somehow, it should have been filtered
5665              out already.  */
5666           internal_error (__FILE__, __LINE__,
5667                           _("bpstat_what: tracepoint encountered"));
5668           break;
5669         case bp_gnu_ifunc_resolver:
5670           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5671           this_action = BPSTAT_WHAT_SINGLE;
5672           break;
5673         case bp_gnu_ifunc_resolver_return:
5674           /* The breakpoint will be removed, execution will restart from the
5675              PC of the former breakpoint.  */
5676           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5677           break;
5678
5679         case bp_dprintf:
5680           if (bs->stop)
5681             this_action = BPSTAT_WHAT_STOP_SILENT;
5682           else
5683             this_action = BPSTAT_WHAT_SINGLE;
5684           break;
5685
5686         default:
5687           internal_error (__FILE__, __LINE__,
5688                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5689         }
5690
5691       retval.main_action = std::max (retval.main_action, this_action);
5692     }
5693
5694   return retval;
5695 }
5696
5697 void
5698 bpstat_run_callbacks (bpstat bs_head)
5699 {
5700   bpstat bs;
5701
5702   for (bs = bs_head; bs != NULL; bs = bs->next)
5703     {
5704       struct breakpoint *b = bs->breakpoint_at;
5705
5706       if (b == NULL)
5707         continue;
5708       switch (b->type)
5709         {
5710         case bp_jit_event:
5711           handle_jit_event ();
5712           break;
5713         case bp_gnu_ifunc_resolver:
5714           gnu_ifunc_resolver_stop (b);
5715           break;
5716         case bp_gnu_ifunc_resolver_return:
5717           gnu_ifunc_resolver_return_stop (b);
5718           break;
5719         }
5720     }
5721 }
5722
5723 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5724    without hardware support).  This isn't related to a specific bpstat,
5725    just to things like whether watchpoints are set.  */
5726
5727 int
5728 bpstat_should_step (void)
5729 {
5730   struct breakpoint *b;
5731
5732   ALL_BREAKPOINTS (b)
5733     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5734       return 1;
5735   return 0;
5736 }
5737
5738 int
5739 bpstat_causes_stop (bpstat bs)
5740 {
5741   for (; bs != NULL; bs = bs->next)
5742     if (bs->stop)
5743       return 1;
5744
5745   return 0;
5746 }
5747
5748 \f
5749
5750 /* Compute a string of spaces suitable to indent the next line
5751    so it starts at the position corresponding to the table column
5752    named COL_NAME in the currently active table of UIOUT.  */
5753
5754 static char *
5755 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5756 {
5757   static char wrap_indent[80];
5758   int i, total_width, width, align;
5759   const char *text;
5760
5761   total_width = 0;
5762   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
5763     {
5764       if (strcmp (text, col_name) == 0)
5765         {
5766           gdb_assert (total_width < sizeof wrap_indent);
5767           memset (wrap_indent, ' ', total_width);
5768           wrap_indent[total_width] = 0;
5769
5770           return wrap_indent;
5771         }
5772
5773       total_width += width + 1;
5774     }
5775
5776   return NULL;
5777 }
5778
5779 /* Determine if the locations of this breakpoint will have their conditions
5780    evaluated by the target, host or a mix of both.  Returns the following:
5781
5782     "host": Host evals condition.
5783     "host or target": Host or Target evals condition.
5784     "target": Target evals condition.
5785 */
5786
5787 static const char *
5788 bp_condition_evaluator (struct breakpoint *b)
5789 {
5790   struct bp_location *bl;
5791   char host_evals = 0;
5792   char target_evals = 0;
5793
5794   if (!b)
5795     return NULL;
5796
5797   if (!is_breakpoint (b))
5798     return NULL;
5799
5800   if (gdb_evaluates_breakpoint_condition_p ()
5801       || !target_supports_evaluation_of_breakpoint_conditions ())
5802     return condition_evaluation_host;
5803
5804   for (bl = b->loc; bl; bl = bl->next)
5805     {
5806       if (bl->cond_bytecode)
5807         target_evals++;
5808       else
5809         host_evals++;
5810     }
5811
5812   if (host_evals && target_evals)
5813     return condition_evaluation_both;
5814   else if (target_evals)
5815     return condition_evaluation_target;
5816   else
5817     return condition_evaluation_host;
5818 }
5819
5820 /* Determine the breakpoint location's condition evaluator.  This is
5821    similar to bp_condition_evaluator, but for locations.  */
5822
5823 static const char *
5824 bp_location_condition_evaluator (struct bp_location *bl)
5825 {
5826   if (bl && !is_breakpoint (bl->owner))
5827     return NULL;
5828
5829   if (gdb_evaluates_breakpoint_condition_p ()
5830       || !target_supports_evaluation_of_breakpoint_conditions ())
5831     return condition_evaluation_host;
5832
5833   if (bl && bl->cond_bytecode)
5834     return condition_evaluation_target;
5835   else
5836     return condition_evaluation_host;
5837 }
5838
5839 /* Print the LOC location out of the list of B->LOC locations.  */
5840
5841 static void
5842 print_breakpoint_location (struct breakpoint *b,
5843                            struct bp_location *loc)
5844 {
5845   struct ui_out *uiout = current_uiout;
5846
5847   scoped_restore_current_program_space restore_pspace;
5848
5849   if (loc != NULL && loc->shlib_disabled)
5850     loc = NULL;
5851
5852   if (loc != NULL)
5853     set_current_program_space (loc->pspace);
5854
5855   if (b->display_canonical)
5856     uiout->field_string ("what", event_location_to_string (b->location.get ()));
5857   else if (loc && loc->symtab)
5858     {
5859       const struct symbol *sym = loc->symbol;
5860
5861       if (sym)
5862         {
5863           uiout->text ("in ");
5864           uiout->field_string ("func", SYMBOL_PRINT_NAME (sym),
5865                                ui_out_style_kind::FUNCTION);
5866           uiout->text (" ");
5867           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
5868           uiout->text ("at ");
5869         }
5870       uiout->field_string ("file",
5871                            symtab_to_filename_for_display (loc->symtab),
5872                            ui_out_style_kind::FILE);
5873       uiout->text (":");
5874
5875       if (uiout->is_mi_like_p ())
5876         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
5877       
5878       uiout->field_int ("line", loc->line_number);
5879     }
5880   else if (loc)
5881     {
5882       string_file stb;
5883
5884       print_address_symbolic (loc->gdbarch, loc->address, &stb,
5885                               demangle, "");
5886       uiout->field_stream ("at", stb);
5887     }
5888   else
5889     {
5890       uiout->field_string ("pending",
5891                            event_location_to_string (b->location.get ()));
5892       /* If extra_string is available, it could be holding a condition
5893          or dprintf arguments.  In either case, make sure it is printed,
5894          too, but only for non-MI streams.  */
5895       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
5896         {
5897           if (b->type == bp_dprintf)
5898             uiout->text (",");
5899           else
5900             uiout->text (" ");
5901           uiout->text (b->extra_string);
5902         }
5903     }
5904
5905   if (loc && is_breakpoint (b)
5906       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5907       && bp_condition_evaluator (b) == condition_evaluation_both)
5908     {
5909       uiout->text (" (");
5910       uiout->field_string ("evaluated-by",
5911                            bp_location_condition_evaluator (loc));
5912       uiout->text (")");
5913     }
5914 }
5915
5916 static const char *
5917 bptype_string (enum bptype type)
5918 {
5919   struct ep_type_description
5920     {
5921       enum bptype type;
5922       const char *description;
5923     };
5924   static struct ep_type_description bptypes[] =
5925   {
5926     {bp_none, "?deleted?"},
5927     {bp_breakpoint, "breakpoint"},
5928     {bp_hardware_breakpoint, "hw breakpoint"},
5929     {bp_single_step, "sw single-step"},
5930     {bp_until, "until"},
5931     {bp_finish, "finish"},
5932     {bp_watchpoint, "watchpoint"},
5933     {bp_hardware_watchpoint, "hw watchpoint"},
5934     {bp_read_watchpoint, "read watchpoint"},
5935     {bp_access_watchpoint, "acc watchpoint"},
5936     {bp_longjmp, "longjmp"},
5937     {bp_longjmp_resume, "longjmp resume"},
5938     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5939     {bp_exception, "exception"},
5940     {bp_exception_resume, "exception resume"},
5941     {bp_step_resume, "step resume"},
5942     {bp_hp_step_resume, "high-priority step resume"},
5943     {bp_watchpoint_scope, "watchpoint scope"},
5944     {bp_call_dummy, "call dummy"},
5945     {bp_std_terminate, "std::terminate"},
5946     {bp_shlib_event, "shlib events"},
5947     {bp_thread_event, "thread events"},
5948     {bp_overlay_event, "overlay events"},
5949     {bp_longjmp_master, "longjmp master"},
5950     {bp_std_terminate_master, "std::terminate master"},
5951     {bp_exception_master, "exception master"},
5952     {bp_catchpoint, "catchpoint"},
5953     {bp_tracepoint, "tracepoint"},
5954     {bp_fast_tracepoint, "fast tracepoint"},
5955     {bp_static_tracepoint, "static tracepoint"},
5956     {bp_dprintf, "dprintf"},
5957     {bp_jit_event, "jit events"},
5958     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5959     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5960   };
5961
5962   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5963       || ((int) type != bptypes[(int) type].type))
5964     internal_error (__FILE__, __LINE__,
5965                     _("bptypes table does not describe type #%d."),
5966                     (int) type);
5967
5968   return bptypes[(int) type].description;
5969 }
5970
5971 /* For MI, output a field named 'thread-groups' with a list as the value.
5972    For CLI, prefix the list with the string 'inf'. */
5973
5974 static void
5975 output_thread_groups (struct ui_out *uiout,
5976                       const char *field_name,
5977                       const std::vector<int> &inf_nums,
5978                       int mi_only)
5979 {
5980   int is_mi = uiout->is_mi_like_p ();
5981
5982   /* For backward compatibility, don't display inferiors in CLI unless
5983      there are several.  Always display them for MI. */
5984   if (!is_mi && mi_only)
5985     return;
5986
5987   ui_out_emit_list list_emitter (uiout, field_name);
5988
5989   for (size_t i = 0; i < inf_nums.size (); i++)
5990     {
5991       if (is_mi)
5992         {
5993           char mi_group[10];
5994
5995           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf_nums[i]);
5996           uiout->field_string (NULL, mi_group);
5997         }
5998       else
5999         {
6000           if (i == 0)
6001             uiout->text (" inf ");
6002           else
6003             uiout->text (", ");
6004         
6005           uiout->text (plongest (inf_nums[i]));
6006         }
6007     }
6008 }
6009
6010 /* Print B to gdb_stdout.  */
6011
6012 static void
6013 print_one_breakpoint_location (struct breakpoint *b,
6014                                struct bp_location *loc,
6015                                int loc_number,
6016                                struct bp_location **last_loc,
6017                                int allflag)
6018 {
6019   struct command_line *l;
6020   static char bpenables[] = "nynny";
6021
6022   struct ui_out *uiout = current_uiout;
6023   int header_of_multiple = 0;
6024   int part_of_multiple = (loc != NULL);
6025   struct value_print_options opts;
6026
6027   get_user_print_options (&opts);
6028
6029   gdb_assert (!loc || loc_number != 0);
6030   /* See comment in print_one_breakpoint concerning treatment of
6031      breakpoints with single disabled location.  */
6032   if (loc == NULL 
6033       && (b->loc != NULL 
6034           && (b->loc->next != NULL || !b->loc->enabled)))
6035     header_of_multiple = 1;
6036   if (loc == NULL)
6037     loc = b->loc;
6038
6039   annotate_record ();
6040
6041   /* 1 */
6042   annotate_field (0);
6043   if (part_of_multiple)
6044     uiout->field_fmt ("number", "%d.%d", b->number, loc_number);
6045   else
6046     uiout->field_int ("number", b->number);
6047
6048   /* 2 */
6049   annotate_field (1);
6050   if (part_of_multiple)
6051     uiout->field_skip ("type");
6052   else
6053     uiout->field_string ("type", bptype_string (b->type));
6054
6055   /* 3 */
6056   annotate_field (2);
6057   if (part_of_multiple)
6058     uiout->field_skip ("disp");
6059   else
6060     uiout->field_string ("disp", bpdisp_text (b->disposition));
6061
6062   /* 4 */
6063   annotate_field (3);
6064   if (part_of_multiple)
6065     uiout->field_string ("enabled", loc->enabled ? "y" : "n");
6066   else
6067     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6068
6069   /* 5 and 6 */
6070   if (b->ops != NULL && b->ops->print_one != NULL)
6071     {
6072       /* Although the print_one can possibly print all locations,
6073          calling it here is not likely to get any nice result.  So,
6074          make sure there's just one location.  */
6075       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6076       b->ops->print_one (b, last_loc);
6077     }
6078   else
6079     switch (b->type)
6080       {
6081       case bp_none:
6082         internal_error (__FILE__, __LINE__,
6083                         _("print_one_breakpoint: bp_none encountered\n"));
6084         break;
6085
6086       case bp_watchpoint:
6087       case bp_hardware_watchpoint:
6088       case bp_read_watchpoint:
6089       case bp_access_watchpoint:
6090         {
6091           struct watchpoint *w = (struct watchpoint *) b;
6092
6093           /* Field 4, the address, is omitted (which makes the columns
6094              not line up too nicely with the headers, but the effect
6095              is relatively readable).  */
6096           if (opts.addressprint)
6097             uiout->field_skip ("addr");
6098           annotate_field (5);
6099           uiout->field_string ("what", w->exp_string);
6100         }
6101         break;
6102
6103       case bp_breakpoint:
6104       case bp_hardware_breakpoint:
6105       case bp_single_step:
6106       case bp_until:
6107       case bp_finish:
6108       case bp_longjmp:
6109       case bp_longjmp_resume:
6110       case bp_longjmp_call_dummy:
6111       case bp_exception:
6112       case bp_exception_resume:
6113       case bp_step_resume:
6114       case bp_hp_step_resume:
6115       case bp_watchpoint_scope:
6116       case bp_call_dummy:
6117       case bp_std_terminate:
6118       case bp_shlib_event:
6119       case bp_thread_event:
6120       case bp_overlay_event:
6121       case bp_longjmp_master:
6122       case bp_std_terminate_master:
6123       case bp_exception_master:
6124       case bp_tracepoint:
6125       case bp_fast_tracepoint:
6126       case bp_static_tracepoint:
6127       case bp_dprintf:
6128       case bp_jit_event:
6129       case bp_gnu_ifunc_resolver:
6130       case bp_gnu_ifunc_resolver_return:
6131         if (opts.addressprint)
6132           {
6133             annotate_field (4);
6134             if (header_of_multiple)
6135               uiout->field_string ("addr", "<MULTIPLE>");
6136             else if (b->loc == NULL || loc->shlib_disabled)
6137               uiout->field_string ("addr", "<PENDING>");
6138             else
6139               uiout->field_core_addr ("addr",
6140                                       loc->gdbarch, loc->address);
6141           }
6142         annotate_field (5);
6143         if (!header_of_multiple)
6144           print_breakpoint_location (b, loc);
6145         if (b->loc)
6146           *last_loc = b->loc;
6147         break;
6148       }
6149
6150
6151   if (loc != NULL && !header_of_multiple)
6152     {
6153       std::vector<int> inf_nums;
6154       int mi_only = 1;
6155
6156       for (inferior *inf : all_inferiors ())
6157         {
6158           if (inf->pspace == loc->pspace)
6159             inf_nums.push_back (inf->num);
6160         }
6161
6162         /* For backward compatibility, don't display inferiors in CLI unless
6163            there are several.  Always display for MI. */
6164         if (allflag
6165             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6166                 && (number_of_program_spaces () > 1
6167                     || number_of_inferiors () > 1)
6168                 /* LOC is for existing B, it cannot be in
6169                    moribund_locations and thus having NULL OWNER.  */
6170                 && loc->owner->type != bp_catchpoint))
6171         mi_only = 0;
6172       output_thread_groups (uiout, "thread-groups", inf_nums, mi_only);
6173     }
6174
6175   if (!part_of_multiple)
6176     {
6177       if (b->thread != -1)
6178         {
6179           /* FIXME: This seems to be redundant and lost here; see the
6180              "stop only in" line a little further down.  */
6181           uiout->text (" thread ");
6182           uiout->field_int ("thread", b->thread);
6183         }
6184       else if (b->task != 0)
6185         {
6186           uiout->text (" task ");
6187           uiout->field_int ("task", b->task);
6188         }
6189     }
6190
6191   uiout->text ("\n");
6192
6193   if (!part_of_multiple)
6194     b->ops->print_one_detail (b, uiout);
6195
6196   if (part_of_multiple && frame_id_p (b->frame_id))
6197     {
6198       annotate_field (6);
6199       uiout->text ("\tstop only in stack frame at ");
6200       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6201          the frame ID.  */
6202       uiout->field_core_addr ("frame",
6203                               b->gdbarch, b->frame_id.stack_addr);
6204       uiout->text ("\n");
6205     }
6206   
6207   if (!part_of_multiple && b->cond_string)
6208     {
6209       annotate_field (7);
6210       if (is_tracepoint (b))
6211         uiout->text ("\ttrace only if ");
6212       else
6213         uiout->text ("\tstop only if ");
6214       uiout->field_string ("cond", b->cond_string);
6215
6216       /* Print whether the target is doing the breakpoint's condition
6217          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6218       if (is_breakpoint (b)
6219           && breakpoint_condition_evaluation_mode ()
6220           == condition_evaluation_target)
6221         {
6222           uiout->text (" (");
6223           uiout->field_string ("evaluated-by",
6224                                bp_condition_evaluator (b));
6225           uiout->text (" evals)");
6226         }
6227       uiout->text ("\n");
6228     }
6229
6230   if (!part_of_multiple && b->thread != -1)
6231     {
6232       /* FIXME should make an annotation for this.  */
6233       uiout->text ("\tstop only in thread ");
6234       if (uiout->is_mi_like_p ())
6235         uiout->field_int ("thread", b->thread);
6236       else
6237         {
6238           struct thread_info *thr = find_thread_global_id (b->thread);
6239
6240           uiout->field_string ("thread", print_thread_id (thr));
6241         }
6242       uiout->text ("\n");
6243     }
6244   
6245   if (!part_of_multiple)
6246     {
6247       if (b->hit_count)
6248         {
6249           /* FIXME should make an annotation for this.  */
6250           if (is_catchpoint (b))
6251             uiout->text ("\tcatchpoint");
6252           else if (is_tracepoint (b))
6253             uiout->text ("\ttracepoint");
6254           else
6255             uiout->text ("\tbreakpoint");
6256           uiout->text (" already hit ");
6257           uiout->field_int ("times", b->hit_count);
6258           if (b->hit_count == 1)
6259             uiout->text (" time\n");
6260           else
6261             uiout->text (" times\n");
6262         }
6263       else
6264         {
6265           /* Output the count also if it is zero, but only if this is mi.  */
6266           if (uiout->is_mi_like_p ())
6267             uiout->field_int ("times", b->hit_count);
6268         }
6269     }
6270
6271   if (!part_of_multiple && b->ignore_count)
6272     {
6273       annotate_field (8);
6274       uiout->text ("\tignore next ");
6275       uiout->field_int ("ignore", b->ignore_count);
6276       uiout->text (" hits\n");
6277     }
6278
6279   /* Note that an enable count of 1 corresponds to "enable once"
6280      behavior, which is reported by the combination of enablement and
6281      disposition, so we don't need to mention it here.  */
6282   if (!part_of_multiple && b->enable_count > 1)
6283     {
6284       annotate_field (8);
6285       uiout->text ("\tdisable after ");
6286       /* Tweak the wording to clarify that ignore and enable counts
6287          are distinct, and have additive effect.  */
6288       if (b->ignore_count)
6289         uiout->text ("additional ");
6290       else
6291         uiout->text ("next ");
6292       uiout->field_int ("enable", b->enable_count);
6293       uiout->text (" hits\n");
6294     }
6295
6296   if (!part_of_multiple && is_tracepoint (b))
6297     {
6298       struct tracepoint *tp = (struct tracepoint *) b;
6299
6300       if (tp->traceframe_usage)
6301         {
6302           uiout->text ("\ttrace buffer usage ");
6303           uiout->field_int ("traceframe-usage", tp->traceframe_usage);
6304           uiout->text (" bytes\n");
6305         }
6306     }
6307
6308   l = b->commands ? b->commands.get () : NULL;
6309   if (!part_of_multiple && l)
6310     {
6311       annotate_field (9);
6312       ui_out_emit_tuple tuple_emitter (uiout, "script");
6313       print_command_lines (uiout, l, 4);
6314     }
6315
6316   if (is_tracepoint (b))
6317     {
6318       struct tracepoint *t = (struct tracepoint *) b;
6319
6320       if (!part_of_multiple && t->pass_count)
6321         {
6322           annotate_field (10);
6323           uiout->text ("\tpass count ");
6324           uiout->field_int ("pass", t->pass_count);
6325           uiout->text (" \n");
6326         }
6327
6328       /* Don't display it when tracepoint or tracepoint location is
6329          pending.   */
6330       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6331         {
6332           annotate_field (11);
6333
6334           if (uiout->is_mi_like_p ())
6335             uiout->field_string ("installed",
6336                                  loc->inserted ? "y" : "n");
6337           else
6338             {
6339               if (loc->inserted)
6340                 uiout->text ("\t");
6341               else
6342                 uiout->text ("\tnot ");
6343               uiout->text ("installed on target\n");
6344             }
6345         }
6346     }
6347
6348   if (uiout->is_mi_like_p () && !part_of_multiple)
6349     {
6350       if (is_watchpoint (b))
6351         {
6352           struct watchpoint *w = (struct watchpoint *) b;
6353
6354           uiout->field_string ("original-location", w->exp_string);
6355         }
6356       else if (b->location != NULL
6357                && event_location_to_string (b->location.get ()) != NULL)
6358         uiout->field_string ("original-location",
6359                              event_location_to_string (b->location.get ()));
6360     }
6361 }
6362
6363 static void
6364 print_one_breakpoint (struct breakpoint *b,
6365                       struct bp_location **last_loc, 
6366                       int allflag)
6367 {
6368   struct ui_out *uiout = current_uiout;
6369   bool use_fixed_output = mi_multi_location_breakpoint_output_fixed (uiout);
6370
6371   gdb::optional<ui_out_emit_tuple> bkpt_tuple_emitter (gdb::in_place, uiout, "bkpt");
6372   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6373
6374   /* The mi2 broken format: the main breakpoint tuple ends here, the locations
6375      are outside.  */
6376   if (!use_fixed_output)
6377     bkpt_tuple_emitter.reset ();
6378
6379   /* If this breakpoint has custom print function,
6380      it's already printed.  Otherwise, print individual
6381      locations, if any.  */
6382   if (b->ops == NULL || b->ops->print_one == NULL)
6383     {
6384       /* If breakpoint has a single location that is disabled, we
6385          print it as if it had several locations, since otherwise it's
6386          hard to represent "breakpoint enabled, location disabled"
6387          situation.
6388
6389          Note that while hardware watchpoints have several locations
6390          internally, that's not a property exposed to user.  */
6391       if (b->loc 
6392           && !is_hardware_watchpoint (b)
6393           && (b->loc->next || !b->loc->enabled))
6394         {
6395           gdb::optional<ui_out_emit_list> locations_list;
6396
6397           /* For MI version <= 2, keep the behavior where GDB outputs an invalid
6398              MI record.  For later versions, place breakpoint locations in a
6399              list.  */
6400           if (uiout->is_mi_like_p () && use_fixed_output)
6401             locations_list.emplace (uiout, "locations");
6402
6403           int n = 1;
6404           for (bp_location *loc = b->loc; loc != NULL; loc = loc->next, ++n)
6405             {
6406               ui_out_emit_tuple loc_tuple_emitter (uiout, NULL);
6407               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6408             }
6409         }
6410     }
6411 }
6412
6413 static int
6414 breakpoint_address_bits (struct breakpoint *b)
6415 {
6416   int print_address_bits = 0;
6417   struct bp_location *loc;
6418
6419   /* Software watchpoints that aren't watching memory don't have an
6420      address to print.  */
6421   if (is_no_memory_software_watchpoint (b))
6422     return 0;
6423
6424   for (loc = b->loc; loc; loc = loc->next)
6425     {
6426       int addr_bit;
6427
6428       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6429       if (addr_bit > print_address_bits)
6430         print_address_bits = addr_bit;
6431     }
6432
6433   return print_address_bits;
6434 }
6435
6436 /* See breakpoint.h.  */
6437
6438 void
6439 print_breakpoint (breakpoint *b)
6440 {
6441   struct bp_location *dummy_loc = NULL;
6442   print_one_breakpoint (b, &dummy_loc, 0);
6443 }
6444
6445 /* Return true if this breakpoint was set by the user, false if it is
6446    internal or momentary.  */
6447
6448 int
6449 user_breakpoint_p (struct breakpoint *b)
6450 {
6451   return b->number > 0;
6452 }
6453
6454 /* See breakpoint.h.  */
6455
6456 int
6457 pending_breakpoint_p (struct breakpoint *b)
6458 {
6459   return b->loc == NULL;
6460 }
6461
6462 /* Print information on user settable breakpoint (watchpoint, etc)
6463    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6464    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6465    FILTER is non-NULL, call it on each breakpoint and only include the
6466    ones for which it returns non-zero.  Return the total number of
6467    breakpoints listed.  */
6468
6469 static int
6470 breakpoint_1 (const char *args, int allflag, 
6471               int (*filter) (const struct breakpoint *))
6472 {
6473   struct breakpoint *b;
6474   struct bp_location *last_loc = NULL;
6475   int nr_printable_breakpoints;
6476   struct value_print_options opts;
6477   int print_address_bits = 0;
6478   int print_type_col_width = 14;
6479   struct ui_out *uiout = current_uiout;
6480
6481   get_user_print_options (&opts);
6482
6483   /* Compute the number of rows in the table, as well as the size
6484      required for address fields.  */
6485   nr_printable_breakpoints = 0;
6486   ALL_BREAKPOINTS (b)
6487     {
6488       /* If we have a filter, only list the breakpoints it accepts.  */
6489       if (filter && !filter (b))
6490         continue;
6491
6492       /* If we have an "args" string, it is a list of breakpoints to 
6493          accept.  Skip the others.  */
6494       if (args != NULL && *args != '\0')
6495         {
6496           if (allflag && parse_and_eval_long (args) != b->number)
6497             continue;
6498           if (!allflag && !number_is_in_list (args, b->number))
6499             continue;
6500         }
6501
6502       if (allflag || user_breakpoint_p (b))
6503         {
6504           int addr_bit, type_len;
6505
6506           addr_bit = breakpoint_address_bits (b);
6507           if (addr_bit > print_address_bits)
6508             print_address_bits = addr_bit;
6509
6510           type_len = strlen (bptype_string (b->type));
6511           if (type_len > print_type_col_width)
6512             print_type_col_width = type_len;
6513
6514           nr_printable_breakpoints++;
6515         }
6516     }
6517
6518   {
6519     ui_out_emit_table table_emitter (uiout,
6520                                      opts.addressprint ? 6 : 5,
6521                                      nr_printable_breakpoints,
6522                                      "BreakpointTable");
6523
6524     if (nr_printable_breakpoints > 0)
6525       annotate_breakpoints_headers ();
6526     if (nr_printable_breakpoints > 0)
6527       annotate_field (0);
6528     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6529     if (nr_printable_breakpoints > 0)
6530       annotate_field (1);
6531     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6532     if (nr_printable_breakpoints > 0)
6533       annotate_field (2);
6534     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6535     if (nr_printable_breakpoints > 0)
6536       annotate_field (3);
6537     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6538     if (opts.addressprint)
6539       {
6540         if (nr_printable_breakpoints > 0)
6541           annotate_field (4);
6542         if (print_address_bits <= 32)
6543           uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6544         else
6545           uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6546       }
6547     if (nr_printable_breakpoints > 0)
6548       annotate_field (5);
6549     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6550     uiout->table_body ();
6551     if (nr_printable_breakpoints > 0)
6552       annotate_breakpoints_table ();
6553
6554     ALL_BREAKPOINTS (b)
6555       {
6556         QUIT;
6557         /* If we have a filter, only list the breakpoints it accepts.  */
6558         if (filter && !filter (b))
6559           continue;
6560
6561         /* If we have an "args" string, it is a list of breakpoints to 
6562            accept.  Skip the others.  */
6563
6564         if (args != NULL && *args != '\0')
6565           {
6566             if (allflag)        /* maintenance info breakpoint */
6567               {
6568                 if (parse_and_eval_long (args) != b->number)
6569                   continue;
6570               }
6571             else                /* all others */
6572               {
6573                 if (!number_is_in_list (args, b->number))
6574                   continue;
6575               }
6576           }
6577         /* We only print out user settable breakpoints unless the
6578            allflag is set.  */
6579         if (allflag || user_breakpoint_p (b))
6580           print_one_breakpoint (b, &last_loc, allflag);
6581       }
6582   }
6583
6584   if (nr_printable_breakpoints == 0)
6585     {
6586       /* If there's a filter, let the caller decide how to report
6587          empty list.  */
6588       if (!filter)
6589         {
6590           if (args == NULL || *args == '\0')
6591             uiout->message ("No breakpoints or watchpoints.\n");
6592           else
6593             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6594                             args);
6595         }
6596     }
6597   else
6598     {
6599       if (last_loc && !server_command)
6600         set_next_address (last_loc->gdbarch, last_loc->address);
6601     }
6602
6603   /* FIXME?  Should this be moved up so that it is only called when
6604      there have been breakpoints? */
6605   annotate_breakpoints_table_end ();
6606
6607   return nr_printable_breakpoints;
6608 }
6609
6610 /* Display the value of default-collect in a way that is generally
6611    compatible with the breakpoint list.  */
6612
6613 static void
6614 default_collect_info (void)
6615 {
6616   struct ui_out *uiout = current_uiout;
6617
6618   /* If it has no value (which is frequently the case), say nothing; a
6619      message like "No default-collect." gets in user's face when it's
6620      not wanted.  */
6621   if (!*default_collect)
6622     return;
6623
6624   /* The following phrase lines up nicely with per-tracepoint collect
6625      actions.  */
6626   uiout->text ("default collect ");
6627   uiout->field_string ("default-collect", default_collect);
6628   uiout->text (" \n");
6629 }
6630   
6631 static void
6632 info_breakpoints_command (const char *args, int from_tty)
6633 {
6634   breakpoint_1 (args, 0, NULL);
6635
6636   default_collect_info ();
6637 }
6638
6639 static void
6640 info_watchpoints_command (const char *args, int from_tty)
6641 {
6642   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6643   struct ui_out *uiout = current_uiout;
6644
6645   if (num_printed == 0)
6646     {
6647       if (args == NULL || *args == '\0')
6648         uiout->message ("No watchpoints.\n");
6649       else
6650         uiout->message ("No watchpoint matching '%s'.\n", args);
6651     }
6652 }
6653
6654 static void
6655 maintenance_info_breakpoints (const char *args, int from_tty)
6656 {
6657   breakpoint_1 (args, 1, NULL);
6658
6659   default_collect_info ();
6660 }
6661
6662 static int
6663 breakpoint_has_pc (struct breakpoint *b,
6664                    struct program_space *pspace,
6665                    CORE_ADDR pc, struct obj_section *section)
6666 {
6667   struct bp_location *bl = b->loc;
6668
6669   for (; bl; bl = bl->next)
6670     {
6671       if (bl->pspace == pspace
6672           && bl->address == pc
6673           && (!overlay_debugging || bl->section == section))
6674         return 1;         
6675     }
6676   return 0;
6677 }
6678
6679 /* Print a message describing any user-breakpoints set at PC.  This
6680    concerns with logical breakpoints, so we match program spaces, not
6681    address spaces.  */
6682
6683 static void
6684 describe_other_breakpoints (struct gdbarch *gdbarch,
6685                             struct program_space *pspace, CORE_ADDR pc,
6686                             struct obj_section *section, int thread)
6687 {
6688   int others = 0;
6689   struct breakpoint *b;
6690
6691   ALL_BREAKPOINTS (b)
6692     others += (user_breakpoint_p (b)
6693                && breakpoint_has_pc (b, pspace, pc, section));
6694   if (others > 0)
6695     {
6696       if (others == 1)
6697         printf_filtered (_("Note: breakpoint "));
6698       else /* if (others == ???) */
6699         printf_filtered (_("Note: breakpoints "));
6700       ALL_BREAKPOINTS (b)
6701         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6702           {
6703             others--;
6704             printf_filtered ("%d", b->number);
6705             if (b->thread == -1 && thread != -1)
6706               printf_filtered (" (all threads)");
6707             else if (b->thread != -1)
6708               printf_filtered (" (thread %d)", b->thread);
6709             printf_filtered ("%s%s ",
6710                              ((b->enable_state == bp_disabled
6711                                || b->enable_state == bp_call_disabled)
6712                               ? " (disabled)"
6713                               : ""),
6714                              (others > 1) ? "," 
6715                              : ((others == 1) ? " and" : ""));
6716           }
6717       printf_filtered (_("also set at pc "));
6718       fputs_styled (paddress (gdbarch, pc), address_style.style (), gdb_stdout);
6719       printf_filtered (".\n");
6720     }
6721 }
6722 \f
6723
6724 /* Return true iff it is meaningful to use the address member of
6725    BPT locations.  For some breakpoint types, the locations' address members
6726    are irrelevant and it makes no sense to attempt to compare them to other
6727    addresses (or use them for any other purpose either).
6728
6729    More specifically, each of the following breakpoint types will
6730    always have a zero valued location address and we don't want to mark
6731    breakpoints of any of these types to be a duplicate of an actual
6732    breakpoint location at address zero:
6733
6734       bp_watchpoint
6735       bp_catchpoint
6736
6737 */
6738
6739 static int
6740 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6741 {
6742   enum bptype type = bpt->type;
6743
6744   return (type != bp_watchpoint && type != bp_catchpoint);
6745 }
6746
6747 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6748    true if LOC1 and LOC2 represent the same watchpoint location.  */
6749
6750 static int
6751 watchpoint_locations_match (struct bp_location *loc1, 
6752                             struct bp_location *loc2)
6753 {
6754   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6755   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6756
6757   /* Both of them must exist.  */
6758   gdb_assert (w1 != NULL);
6759   gdb_assert (w2 != NULL);
6760
6761   /* If the target can evaluate the condition expression in hardware,
6762      then we we need to insert both watchpoints even if they are at
6763      the same place.  Otherwise the watchpoint will only trigger when
6764      the condition of whichever watchpoint was inserted evaluates to
6765      true, not giving a chance for GDB to check the condition of the
6766      other watchpoint.  */
6767   if ((w1->cond_exp
6768        && target_can_accel_watchpoint_condition (loc1->address, 
6769                                                  loc1->length,
6770                                                  loc1->watchpoint_type,
6771                                                  w1->cond_exp.get ()))
6772       || (w2->cond_exp
6773           && target_can_accel_watchpoint_condition (loc2->address, 
6774                                                     loc2->length,
6775                                                     loc2->watchpoint_type,
6776                                                     w2->cond_exp.get ())))
6777     return 0;
6778
6779   /* Note that this checks the owner's type, not the location's.  In
6780      case the target does not support read watchpoints, but does
6781      support access watchpoints, we'll have bp_read_watchpoint
6782      watchpoints with hw_access locations.  Those should be considered
6783      duplicates of hw_read locations.  The hw_read locations will
6784      become hw_access locations later.  */
6785   return (loc1->owner->type == loc2->owner->type
6786           && loc1->pspace->aspace == loc2->pspace->aspace
6787           && loc1->address == loc2->address
6788           && loc1->length == loc2->length);
6789 }
6790
6791 /* See breakpoint.h.  */
6792
6793 int
6794 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
6795                           const address_space *aspace2, CORE_ADDR addr2)
6796 {
6797   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6798            || aspace1 == aspace2)
6799           && addr1 == addr2);
6800 }
6801
6802 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6803    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6804    matches ASPACE2.  On targets that have global breakpoints, the address
6805    space doesn't really matter.  */
6806
6807 static int
6808 breakpoint_address_match_range (const address_space *aspace1,
6809                                 CORE_ADDR addr1,
6810                                 int len1, const address_space *aspace2,
6811                                 CORE_ADDR addr2)
6812 {
6813   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6814            || aspace1 == aspace2)
6815           && addr2 >= addr1 && addr2 < addr1 + len1);
6816 }
6817
6818 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6819    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6820    matches the breakpoint's address space.  On targets that have global
6821    breakpoints, the address space doesn't really matter.  */
6822
6823 static int
6824 breakpoint_location_address_match (struct bp_location *bl,
6825                                    const address_space *aspace,
6826                                    CORE_ADDR addr)
6827 {
6828   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6829                                     aspace, addr)
6830           || (bl->length
6831               && breakpoint_address_match_range (bl->pspace->aspace,
6832                                                  bl->address, bl->length,
6833                                                  aspace, addr)));
6834 }
6835
6836 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
6837    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
6838    match happens only if ASPACE matches the breakpoint's address
6839    space.  On targets that have global breakpoints, the address space
6840    doesn't really matter.  */
6841
6842 static int
6843 breakpoint_location_address_range_overlap (struct bp_location *bl,
6844                                            const address_space *aspace,
6845                                            CORE_ADDR addr, int len)
6846 {
6847   if (gdbarch_has_global_breakpoints (target_gdbarch ())
6848       || bl->pspace->aspace == aspace)
6849     {
6850       int bl_len = bl->length != 0 ? bl->length : 1;
6851
6852       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
6853         return 1;
6854     }
6855   return 0;
6856 }
6857
6858 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6859    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6860    true, otherwise returns false.  */
6861
6862 static int
6863 tracepoint_locations_match (struct bp_location *loc1,
6864                             struct bp_location *loc2)
6865 {
6866   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6867     /* Since tracepoint locations are never duplicated with others', tracepoint
6868        locations at the same address of different tracepoints are regarded as
6869        different locations.  */
6870     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6871   else
6872     return 0;
6873 }
6874
6875 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6876    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6877    represent the same location.  */
6878
6879 static int
6880 breakpoint_locations_match (struct bp_location *loc1, 
6881                             struct bp_location *loc2)
6882 {
6883   int hw_point1, hw_point2;
6884
6885   /* Both of them must not be in moribund_locations.  */
6886   gdb_assert (loc1->owner != NULL);
6887   gdb_assert (loc2->owner != NULL);
6888
6889   hw_point1 = is_hardware_watchpoint (loc1->owner);
6890   hw_point2 = is_hardware_watchpoint (loc2->owner);
6891
6892   if (hw_point1 != hw_point2)
6893     return 0;
6894   else if (hw_point1)
6895     return watchpoint_locations_match (loc1, loc2);
6896   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6897     return tracepoint_locations_match (loc1, loc2);
6898   else
6899     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6900     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6901                                      loc2->pspace->aspace, loc2->address)
6902             && loc1->length == loc2->length);
6903 }
6904
6905 static void
6906 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6907                                int bnum, int have_bnum)
6908 {
6909   /* The longest string possibly returned by hex_string_custom
6910      is 50 chars.  These must be at least that big for safety.  */
6911   char astr1[64];
6912   char astr2[64];
6913
6914   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6915   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6916   if (have_bnum)
6917     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6918              bnum, astr1, astr2);
6919   else
6920     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6921 }
6922
6923 /* Adjust a breakpoint's address to account for architectural
6924    constraints on breakpoint placement.  Return the adjusted address.
6925    Note: Very few targets require this kind of adjustment.  For most
6926    targets, this function is simply the identity function.  */
6927
6928 static CORE_ADDR
6929 adjust_breakpoint_address (struct gdbarch *gdbarch,
6930                            CORE_ADDR bpaddr, enum bptype bptype)
6931 {
6932   if (bptype == bp_watchpoint
6933       || bptype == bp_hardware_watchpoint
6934       || bptype == bp_read_watchpoint
6935       || bptype == bp_access_watchpoint
6936       || bptype == bp_catchpoint)
6937     {
6938       /* Watchpoints and the various bp_catch_* eventpoints should not
6939          have their addresses modified.  */
6940       return bpaddr;
6941     }
6942   else if (bptype == bp_single_step)
6943     {
6944       /* Single-step breakpoints should not have their addresses
6945          modified.  If there's any architectural constrain that
6946          applies to this address, then it should have already been
6947          taken into account when the breakpoint was created in the
6948          first place.  If we didn't do this, stepping through e.g.,
6949          Thumb-2 IT blocks would break.  */
6950       return bpaddr;
6951     }
6952   else
6953     {
6954       CORE_ADDR adjusted_bpaddr = bpaddr;
6955
6956       if (gdbarch_adjust_breakpoint_address_p (gdbarch))
6957         {
6958           /* Some targets have architectural constraints on the placement
6959              of breakpoint instructions.  Obtain the adjusted address.  */
6960           adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6961         }
6962
6963       adjusted_bpaddr = address_significant (gdbarch, adjusted_bpaddr);
6964
6965       /* An adjusted breakpoint address can significantly alter
6966          a user's expectations.  Print a warning if an adjustment
6967          is required.  */
6968       if (adjusted_bpaddr != bpaddr)
6969         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6970
6971       return adjusted_bpaddr;
6972     }
6973 }
6974
6975 bp_location::bp_location (breakpoint *owner)
6976 {
6977   bp_location *loc = this;
6978
6979   loc->owner = owner;
6980   loc->cond_bytecode = NULL;
6981   loc->shlib_disabled = 0;
6982   loc->enabled = 1;
6983
6984   switch (owner->type)
6985     {
6986     case bp_breakpoint:
6987     case bp_single_step:
6988     case bp_until:
6989     case bp_finish:
6990     case bp_longjmp:
6991     case bp_longjmp_resume:
6992     case bp_longjmp_call_dummy:
6993     case bp_exception:
6994     case bp_exception_resume:
6995     case bp_step_resume:
6996     case bp_hp_step_resume:
6997     case bp_watchpoint_scope:
6998     case bp_call_dummy:
6999     case bp_std_terminate:
7000     case bp_shlib_event:
7001     case bp_thread_event:
7002     case bp_overlay_event:
7003     case bp_jit_event:
7004     case bp_longjmp_master:
7005     case bp_std_terminate_master:
7006     case bp_exception_master:
7007     case bp_gnu_ifunc_resolver:
7008     case bp_gnu_ifunc_resolver_return:
7009     case bp_dprintf:
7010       loc->loc_type = bp_loc_software_breakpoint;
7011       mark_breakpoint_location_modified (loc);
7012       break;
7013     case bp_hardware_breakpoint:
7014       loc->loc_type = bp_loc_hardware_breakpoint;
7015       mark_breakpoint_location_modified (loc);
7016       break;
7017     case bp_hardware_watchpoint:
7018     case bp_read_watchpoint:
7019     case bp_access_watchpoint:
7020       loc->loc_type = bp_loc_hardware_watchpoint;
7021       break;
7022     case bp_watchpoint:
7023     case bp_catchpoint:
7024     case bp_tracepoint:
7025     case bp_fast_tracepoint:
7026     case bp_static_tracepoint:
7027       loc->loc_type = bp_loc_other;
7028       break;
7029     default:
7030       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7031     }
7032
7033   loc->refc = 1;
7034 }
7035
7036 /* Allocate a struct bp_location.  */
7037
7038 static struct bp_location *
7039 allocate_bp_location (struct breakpoint *bpt)
7040 {
7041   return bpt->ops->allocate_location (bpt);
7042 }
7043
7044 static void
7045 free_bp_location (struct bp_location *loc)
7046 {
7047   delete loc;
7048 }
7049
7050 /* Increment reference count.  */
7051
7052 static void
7053 incref_bp_location (struct bp_location *bl)
7054 {
7055   ++bl->refc;
7056 }
7057
7058 /* Decrement reference count.  If the reference count reaches 0,
7059    destroy the bp_location.  Sets *BLP to NULL.  */
7060
7061 static void
7062 decref_bp_location (struct bp_location **blp)
7063 {
7064   gdb_assert ((*blp)->refc > 0);
7065
7066   if (--(*blp)->refc == 0)
7067     free_bp_location (*blp);
7068   *blp = NULL;
7069 }
7070
7071 /* Add breakpoint B at the end of the global breakpoint chain.  */
7072
7073 static breakpoint *
7074 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7075 {
7076   struct breakpoint *b1;
7077   struct breakpoint *result = b.get ();
7078
7079   /* Add this breakpoint to the end of the chain so that a list of
7080      breakpoints will come out in order of increasing numbers.  */
7081
7082   b1 = breakpoint_chain;
7083   if (b1 == 0)
7084     breakpoint_chain = b.release ();
7085   else
7086     {
7087       while (b1->next)
7088         b1 = b1->next;
7089       b1->next = b.release ();
7090     }
7091
7092   return result;
7093 }
7094
7095 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7096
7097 static void
7098 init_raw_breakpoint_without_location (struct breakpoint *b,
7099                                       struct gdbarch *gdbarch,
7100                                       enum bptype bptype,
7101                                       const struct breakpoint_ops *ops)
7102 {
7103   gdb_assert (ops != NULL);
7104
7105   b->ops = ops;
7106   b->type = bptype;
7107   b->gdbarch = gdbarch;
7108   b->language = current_language->la_language;
7109   b->input_radix = input_radix;
7110   b->related_breakpoint = b;
7111 }
7112
7113 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7114    that has type BPTYPE and has no locations as yet.  */
7115
7116 static struct breakpoint *
7117 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7118                                      enum bptype bptype,
7119                                      const struct breakpoint_ops *ops)
7120 {
7121   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7122
7123   init_raw_breakpoint_without_location (b.get (), gdbarch, bptype, ops);
7124   return add_to_breakpoint_chain (std::move (b));
7125 }
7126
7127 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7128    resolutions should be made as the user specified the location explicitly
7129    enough.  */
7130
7131 static void
7132 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7133 {
7134   gdb_assert (loc->owner != NULL);
7135
7136   if (loc->owner->type == bp_breakpoint
7137       || loc->owner->type == bp_hardware_breakpoint
7138       || is_tracepoint (loc->owner))
7139     {
7140       const char *function_name;
7141
7142       if (loc->msymbol != NULL
7143           && (MSYMBOL_TYPE (loc->msymbol) == mst_text_gnu_ifunc
7144               || MSYMBOL_TYPE (loc->msymbol) == mst_data_gnu_ifunc)
7145           && !explicit_loc)
7146         {
7147           struct breakpoint *b = loc->owner;
7148
7149           function_name = MSYMBOL_LINKAGE_NAME (loc->msymbol);
7150
7151           if (b->type == bp_breakpoint && b->loc == loc
7152               && loc->next == NULL && b->related_breakpoint == b)
7153             {
7154               /* Create only the whole new breakpoint of this type but do not
7155                  mess more complicated breakpoints with multiple locations.  */
7156               b->type = bp_gnu_ifunc_resolver;
7157               /* Remember the resolver's address for use by the return
7158                  breakpoint.  */
7159               loc->related_address = loc->address;
7160             }
7161         }
7162       else
7163         find_pc_partial_function (loc->address, &function_name, NULL, NULL);
7164
7165       if (function_name)
7166         loc->function_name = xstrdup (function_name);
7167     }
7168 }
7169
7170 /* Attempt to determine architecture of location identified by SAL.  */
7171 struct gdbarch *
7172 get_sal_arch (struct symtab_and_line sal)
7173 {
7174   if (sal.section)
7175     return get_objfile_arch (sal.section->objfile);
7176   if (sal.symtab)
7177     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7178
7179   return NULL;
7180 }
7181
7182 /* Low level routine for partially initializing a breakpoint of type
7183    BPTYPE.  The newly created breakpoint's address, section, source
7184    file name, and line number are provided by SAL.
7185
7186    It is expected that the caller will complete the initialization of
7187    the newly created breakpoint struct as well as output any status
7188    information regarding the creation of a new breakpoint.  */
7189
7190 static void
7191 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7192                      struct symtab_and_line sal, enum bptype bptype,
7193                      const struct breakpoint_ops *ops)
7194 {
7195   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7196
7197   add_location_to_breakpoint (b, &sal);
7198
7199   if (bptype != bp_catchpoint)
7200     gdb_assert (sal.pspace != NULL);
7201
7202   /* Store the program space that was used to set the breakpoint,
7203      except for ordinary breakpoints, which are independent of the
7204      program space.  */
7205   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7206     b->pspace = sal.pspace;
7207 }
7208
7209 /* set_raw_breakpoint is a low level routine for allocating and
7210    partially initializing a breakpoint of type BPTYPE.  The newly
7211    created breakpoint's address, section, source file name, and line
7212    number are provided by SAL.  The newly created and partially
7213    initialized breakpoint is added to the breakpoint chain and
7214    is also returned as the value of this function.
7215
7216    It is expected that the caller will complete the initialization of
7217    the newly created breakpoint struct as well as output any status
7218    information regarding the creation of a new breakpoint.  In
7219    particular, set_raw_breakpoint does NOT set the breakpoint
7220    number!  Care should be taken to not allow an error to occur
7221    prior to completing the initialization of the breakpoint.  If this
7222    should happen, a bogus breakpoint will be left on the chain.  */
7223
7224 struct breakpoint *
7225 set_raw_breakpoint (struct gdbarch *gdbarch,
7226                     struct symtab_and_line sal, enum bptype bptype,
7227                     const struct breakpoint_ops *ops)
7228 {
7229   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7230
7231   init_raw_breakpoint (b.get (), gdbarch, sal, bptype, ops);
7232   return add_to_breakpoint_chain (std::move (b));
7233 }
7234
7235 /* Call this routine when stepping and nexting to enable a breakpoint
7236    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7237    initiated the operation.  */
7238
7239 void
7240 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7241 {
7242   struct breakpoint *b, *b_tmp;
7243   int thread = tp->global_num;
7244
7245   /* To avoid having to rescan all objfile symbols at every step,
7246      we maintain a list of continually-inserted but always disabled
7247      longjmp "master" breakpoints.  Here, we simply create momentary
7248      clones of those and enable them for the requested thread.  */
7249   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7250     if (b->pspace == current_program_space
7251         && (b->type == bp_longjmp_master
7252             || b->type == bp_exception_master))
7253       {
7254         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7255         struct breakpoint *clone;
7256
7257         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7258            after their removal.  */
7259         clone = momentary_breakpoint_from_master (b, type,
7260                                                   &momentary_breakpoint_ops, 1);
7261         clone->thread = thread;
7262       }
7263
7264   tp->initiating_frame = frame;
7265 }
7266
7267 /* Delete all longjmp breakpoints from THREAD.  */
7268 void
7269 delete_longjmp_breakpoint (int thread)
7270 {
7271   struct breakpoint *b, *b_tmp;
7272
7273   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7274     if (b->type == bp_longjmp || b->type == bp_exception)
7275       {
7276         if (b->thread == thread)
7277           delete_breakpoint (b);
7278       }
7279 }
7280
7281 void
7282 delete_longjmp_breakpoint_at_next_stop (int thread)
7283 {
7284   struct breakpoint *b, *b_tmp;
7285
7286   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7287     if (b->type == bp_longjmp || b->type == bp_exception)
7288       {
7289         if (b->thread == thread)
7290           b->disposition = disp_del_at_next_stop;
7291       }
7292 }
7293
7294 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7295    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7296    pointer to any of them.  Return NULL if this system cannot place longjmp
7297    breakpoints.  */
7298
7299 struct breakpoint *
7300 set_longjmp_breakpoint_for_call_dummy (void)
7301 {
7302   struct breakpoint *b, *retval = NULL;
7303
7304   ALL_BREAKPOINTS (b)
7305     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7306       {
7307         struct breakpoint *new_b;
7308
7309         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7310                                                   &momentary_breakpoint_ops,
7311                                                   1);
7312         new_b->thread = inferior_thread ()->global_num;
7313
7314         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7315
7316         gdb_assert (new_b->related_breakpoint == new_b);
7317         if (retval == NULL)
7318           retval = new_b;
7319         new_b->related_breakpoint = retval;
7320         while (retval->related_breakpoint != new_b->related_breakpoint)
7321           retval = retval->related_breakpoint;
7322         retval->related_breakpoint = new_b;
7323       }
7324
7325   return retval;
7326 }
7327
7328 /* Verify all existing dummy frames and their associated breakpoints for
7329    TP.  Remove those which can no longer be found in the current frame
7330    stack.
7331
7332    You should call this function only at places where it is safe to currently
7333    unwind the whole stack.  Failed stack unwind would discard live dummy
7334    frames.  */
7335
7336 void
7337 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7338 {
7339   struct breakpoint *b, *b_tmp;
7340
7341   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7342     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7343       {
7344         struct breakpoint *dummy_b = b->related_breakpoint;
7345
7346         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7347           dummy_b = dummy_b->related_breakpoint;
7348         if (dummy_b->type != bp_call_dummy
7349             || frame_find_by_id (dummy_b->frame_id) != NULL)
7350           continue;
7351         
7352         dummy_frame_discard (dummy_b->frame_id, tp);
7353
7354         while (b->related_breakpoint != b)
7355           {
7356             if (b_tmp == b->related_breakpoint)
7357               b_tmp = b->related_breakpoint->next;
7358             delete_breakpoint (b->related_breakpoint);
7359           }
7360         delete_breakpoint (b);
7361       }
7362 }
7363
7364 void
7365 enable_overlay_breakpoints (void)
7366 {
7367   struct breakpoint *b;
7368
7369   ALL_BREAKPOINTS (b)
7370     if (b->type == bp_overlay_event)
7371     {
7372       b->enable_state = bp_enabled;
7373       update_global_location_list (UGLL_MAY_INSERT);
7374       overlay_events_enabled = 1;
7375     }
7376 }
7377
7378 void
7379 disable_overlay_breakpoints (void)
7380 {
7381   struct breakpoint *b;
7382
7383   ALL_BREAKPOINTS (b)
7384     if (b->type == bp_overlay_event)
7385     {
7386       b->enable_state = bp_disabled;
7387       update_global_location_list (UGLL_DONT_INSERT);
7388       overlay_events_enabled = 0;
7389     }
7390 }
7391
7392 /* Set an active std::terminate breakpoint for each std::terminate
7393    master breakpoint.  */
7394 void
7395 set_std_terminate_breakpoint (void)
7396 {
7397   struct breakpoint *b, *b_tmp;
7398
7399   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7400     if (b->pspace == current_program_space
7401         && b->type == bp_std_terminate_master)
7402       {
7403         momentary_breakpoint_from_master (b, bp_std_terminate,
7404                                           &momentary_breakpoint_ops, 1);
7405       }
7406 }
7407
7408 /* Delete all the std::terminate breakpoints.  */
7409 void
7410 delete_std_terminate_breakpoint (void)
7411 {
7412   struct breakpoint *b, *b_tmp;
7413
7414   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7415     if (b->type == bp_std_terminate)
7416       delete_breakpoint (b);
7417 }
7418
7419 struct breakpoint *
7420 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7421 {
7422   struct breakpoint *b;
7423
7424   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7425                                   &internal_breakpoint_ops);
7426
7427   b->enable_state = bp_enabled;
7428   /* location has to be used or breakpoint_re_set will delete me.  */
7429   b->location = new_address_location (b->loc->address, NULL, 0);
7430
7431   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7432
7433   return b;
7434 }
7435
7436 struct lang_and_radix
7437   {
7438     enum language lang;
7439     int radix;
7440   };
7441
7442 /* Create a breakpoint for JIT code registration and unregistration.  */
7443
7444 struct breakpoint *
7445 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7446 {
7447   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7448                                      &internal_breakpoint_ops);
7449 }
7450
7451 /* Remove JIT code registration and unregistration breakpoint(s).  */
7452
7453 void
7454 remove_jit_event_breakpoints (void)
7455 {
7456   struct breakpoint *b, *b_tmp;
7457
7458   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7459     if (b->type == bp_jit_event
7460         && b->loc->pspace == current_program_space)
7461       delete_breakpoint (b);
7462 }
7463
7464 void
7465 remove_solib_event_breakpoints (void)
7466 {
7467   struct breakpoint *b, *b_tmp;
7468
7469   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7470     if (b->type == bp_shlib_event
7471         && b->loc->pspace == current_program_space)
7472       delete_breakpoint (b);
7473 }
7474
7475 /* See breakpoint.h.  */
7476
7477 void
7478 remove_solib_event_breakpoints_at_next_stop (void)
7479 {
7480   struct breakpoint *b, *b_tmp;
7481
7482   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7483     if (b->type == bp_shlib_event
7484         && b->loc->pspace == current_program_space)
7485       b->disposition = disp_del_at_next_stop;
7486 }
7487
7488 /* Helper for create_solib_event_breakpoint /
7489    create_and_insert_solib_event_breakpoint.  Allows specifying which
7490    INSERT_MODE to pass through to update_global_location_list.  */
7491
7492 static struct breakpoint *
7493 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7494                                  enum ugll_insert_mode insert_mode)
7495 {
7496   struct breakpoint *b;
7497
7498   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7499                                   &internal_breakpoint_ops);
7500   update_global_location_list_nothrow (insert_mode);
7501   return b;
7502 }
7503
7504 struct breakpoint *
7505 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7506 {
7507   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7508 }
7509
7510 /* See breakpoint.h.  */
7511
7512 struct breakpoint *
7513 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7514 {
7515   struct breakpoint *b;
7516
7517   /* Explicitly tell update_global_location_list to insert
7518      locations.  */
7519   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7520   if (!b->loc->inserted)
7521     {
7522       delete_breakpoint (b);
7523       return NULL;
7524     }
7525   return b;
7526 }
7527
7528 /* Disable any breakpoints that are on code in shared libraries.  Only
7529    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7530
7531 void
7532 disable_breakpoints_in_shlibs (void)
7533 {
7534   struct bp_location *loc, **locp_tmp;
7535
7536   ALL_BP_LOCATIONS (loc, locp_tmp)
7537   {
7538     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7539     struct breakpoint *b = loc->owner;
7540
7541     /* We apply the check to all breakpoints, including disabled for
7542        those with loc->duplicate set.  This is so that when breakpoint
7543        becomes enabled, or the duplicate is removed, gdb will try to
7544        insert all breakpoints.  If we don't set shlib_disabled here,
7545        we'll try to insert those breakpoints and fail.  */
7546     if (((b->type == bp_breakpoint)
7547          || (b->type == bp_jit_event)
7548          || (b->type == bp_hardware_breakpoint)
7549          || (is_tracepoint (b)))
7550         && loc->pspace == current_program_space
7551         && !loc->shlib_disabled
7552         && solib_name_from_address (loc->pspace, loc->address)
7553         )
7554       {
7555         loc->shlib_disabled = 1;
7556       }
7557   }
7558 }
7559
7560 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7561    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7562    disabled ones can just stay disabled.  */
7563
7564 static void
7565 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7566 {
7567   struct bp_location *loc, **locp_tmp;
7568   int disabled_shlib_breaks = 0;
7569
7570   ALL_BP_LOCATIONS (loc, locp_tmp)
7571   {
7572     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7573     struct breakpoint *b = loc->owner;
7574
7575     if (solib->pspace == loc->pspace
7576         && !loc->shlib_disabled
7577         && (((b->type == bp_breakpoint
7578               || b->type == bp_jit_event
7579               || b->type == bp_hardware_breakpoint)
7580              && (loc->loc_type == bp_loc_hardware_breakpoint
7581                  || loc->loc_type == bp_loc_software_breakpoint))
7582             || is_tracepoint (b))
7583         && solib_contains_address_p (solib, loc->address))
7584       {
7585         loc->shlib_disabled = 1;
7586         /* At this point, we cannot rely on remove_breakpoint
7587            succeeding so we must mark the breakpoint as not inserted
7588            to prevent future errors occurring in remove_breakpoints.  */
7589         loc->inserted = 0;
7590
7591         /* This may cause duplicate notifications for the same breakpoint.  */
7592         gdb::observers::breakpoint_modified.notify (b);
7593
7594         if (!disabled_shlib_breaks)
7595           {
7596             target_terminal::ours_for_output ();
7597             warning (_("Temporarily disabling breakpoints "
7598                        "for unloaded shared library \"%s\""),
7599                      solib->so_name);
7600           }
7601         disabled_shlib_breaks = 1;
7602       }
7603   }
7604 }
7605
7606 /* Disable any breakpoints and tracepoints in OBJFILE upon
7607    notification of free_objfile.  Only apply to enabled breakpoints,
7608    disabled ones can just stay disabled.  */
7609
7610 static void
7611 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7612 {
7613   struct breakpoint *b;
7614
7615   if (objfile == NULL)
7616     return;
7617
7618   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7619      managed by the user with add-symbol-file/remove-symbol-file.
7620      Similarly to how breakpoints in shared libraries are handled in
7621      response to "nosharedlibrary", mark breakpoints in such modules
7622      shlib_disabled so they end up uninserted on the next global
7623      location list update.  Shared libraries not loaded by the user
7624      aren't handled here -- they're already handled in
7625      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7626      solib_unloaded observer.  We skip objfiles that are not
7627      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7628      main objfile).  */
7629   if ((objfile->flags & OBJF_SHARED) == 0
7630       || (objfile->flags & OBJF_USERLOADED) == 0)
7631     return;
7632
7633   ALL_BREAKPOINTS (b)
7634     {
7635       struct bp_location *loc;
7636       int bp_modified = 0;
7637
7638       if (!is_breakpoint (b) && !is_tracepoint (b))
7639         continue;
7640
7641       for (loc = b->loc; loc != NULL; loc = loc->next)
7642         {
7643           CORE_ADDR loc_addr = loc->address;
7644
7645           if (loc->loc_type != bp_loc_hardware_breakpoint
7646               && loc->loc_type != bp_loc_software_breakpoint)
7647             continue;
7648
7649           if (loc->shlib_disabled != 0)
7650             continue;
7651
7652           if (objfile->pspace != loc->pspace)
7653             continue;
7654
7655           if (loc->loc_type != bp_loc_hardware_breakpoint
7656               && loc->loc_type != bp_loc_software_breakpoint)
7657             continue;
7658
7659           if (is_addr_in_objfile (loc_addr, objfile))
7660             {
7661               loc->shlib_disabled = 1;
7662               /* At this point, we don't know whether the object was
7663                  unmapped from the inferior or not, so leave the
7664                  inserted flag alone.  We'll handle failure to
7665                  uninsert quietly, in case the object was indeed
7666                  unmapped.  */
7667
7668               mark_breakpoint_location_modified (loc);
7669
7670               bp_modified = 1;
7671             }
7672         }
7673
7674       if (bp_modified)
7675         gdb::observers::breakpoint_modified.notify (b);
7676     }
7677 }
7678
7679 /* FORK & VFORK catchpoints.  */
7680
7681 /* An instance of this type is used to represent a fork or vfork
7682    catchpoint.  A breakpoint is really of this type iff its ops pointer points
7683    to CATCH_FORK_BREAKPOINT_OPS.  */
7684
7685 struct fork_catchpoint : public breakpoint
7686 {
7687   /* Process id of a child process whose forking triggered this
7688      catchpoint.  This field is only valid immediately after this
7689      catchpoint has triggered.  */
7690   ptid_t forked_inferior_pid;
7691 };
7692
7693 /* Implement the "insert" breakpoint_ops method for fork
7694    catchpoints.  */
7695
7696 static int
7697 insert_catch_fork (struct bp_location *bl)
7698 {
7699   return target_insert_fork_catchpoint (inferior_ptid.pid ());
7700 }
7701
7702 /* Implement the "remove" breakpoint_ops method for fork
7703    catchpoints.  */
7704
7705 static int
7706 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
7707 {
7708   return target_remove_fork_catchpoint (inferior_ptid.pid ());
7709 }
7710
7711 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7712    catchpoints.  */
7713
7714 static int
7715 breakpoint_hit_catch_fork (const struct bp_location *bl,
7716                            const address_space *aspace, CORE_ADDR bp_addr,
7717                            const struct target_waitstatus *ws)
7718 {
7719   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7720
7721   if (ws->kind != TARGET_WAITKIND_FORKED)
7722     return 0;
7723
7724   c->forked_inferior_pid = ws->value.related_pid;
7725   return 1;
7726 }
7727
7728 /* Implement the "print_it" breakpoint_ops method for fork
7729    catchpoints.  */
7730
7731 static enum print_stop_action
7732 print_it_catch_fork (bpstat bs)
7733 {
7734   struct ui_out *uiout = current_uiout;
7735   struct breakpoint *b = bs->breakpoint_at;
7736   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7737
7738   annotate_catchpoint (b->number);
7739   maybe_print_thread_hit_breakpoint (uiout);
7740   if (b->disposition == disp_del)
7741     uiout->text ("Temporary catchpoint ");
7742   else
7743     uiout->text ("Catchpoint ");
7744   if (uiout->is_mi_like_p ())
7745     {
7746       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
7747       uiout->field_string ("disp", bpdisp_text (b->disposition));
7748     }
7749   uiout->field_int ("bkptno", b->number);
7750   uiout->text (" (forked process ");
7751   uiout->field_int ("newpid", c->forked_inferior_pid.pid ());
7752   uiout->text ("), ");
7753   return PRINT_SRC_AND_LOC;
7754 }
7755
7756 /* Implement the "print_one" breakpoint_ops method for fork
7757    catchpoints.  */
7758
7759 static void
7760 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7761 {
7762   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7763   struct value_print_options opts;
7764   struct ui_out *uiout = current_uiout;
7765
7766   get_user_print_options (&opts);
7767
7768   /* Field 4, the address, is omitted (which makes the columns not
7769      line up too nicely with the headers, but the effect is relatively
7770      readable).  */
7771   if (opts.addressprint)
7772     uiout->field_skip ("addr");
7773   annotate_field (5);
7774   uiout->text ("fork");
7775   if (c->forked_inferior_pid != null_ptid)
7776     {
7777       uiout->text (", process ");
7778       uiout->field_int ("what", c->forked_inferior_pid.pid ());
7779       uiout->spaces (1);
7780     }
7781
7782   if (uiout->is_mi_like_p ())
7783     uiout->field_string ("catch-type", "fork");
7784 }
7785
7786 /* Implement the "print_mention" breakpoint_ops method for fork
7787    catchpoints.  */
7788
7789 static void
7790 print_mention_catch_fork (struct breakpoint *b)
7791 {
7792   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7793 }
7794
7795 /* Implement the "print_recreate" breakpoint_ops method for fork
7796    catchpoints.  */
7797
7798 static void
7799 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7800 {
7801   fprintf_unfiltered (fp, "catch fork");
7802   print_recreate_thread (b, fp);
7803 }
7804
7805 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7806
7807 static struct breakpoint_ops catch_fork_breakpoint_ops;
7808
7809 /* Implement the "insert" breakpoint_ops method for vfork
7810    catchpoints.  */
7811
7812 static int
7813 insert_catch_vfork (struct bp_location *bl)
7814 {
7815   return target_insert_vfork_catchpoint (inferior_ptid.pid ());
7816 }
7817
7818 /* Implement the "remove" breakpoint_ops method for vfork
7819    catchpoints.  */
7820
7821 static int
7822 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
7823 {
7824   return target_remove_vfork_catchpoint (inferior_ptid.pid ());
7825 }
7826
7827 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7828    catchpoints.  */
7829
7830 static int
7831 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7832                             const address_space *aspace, CORE_ADDR bp_addr,
7833                             const struct target_waitstatus *ws)
7834 {
7835   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7836
7837   if (ws->kind != TARGET_WAITKIND_VFORKED)
7838     return 0;
7839
7840   c->forked_inferior_pid = ws->value.related_pid;
7841   return 1;
7842 }
7843
7844 /* Implement the "print_it" breakpoint_ops method for vfork
7845    catchpoints.  */
7846
7847 static enum print_stop_action
7848 print_it_catch_vfork (bpstat bs)
7849 {
7850   struct ui_out *uiout = current_uiout;
7851   struct breakpoint *b = bs->breakpoint_at;
7852   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7853
7854   annotate_catchpoint (b->number);
7855   maybe_print_thread_hit_breakpoint (uiout);
7856   if (b->disposition == disp_del)
7857     uiout->text ("Temporary catchpoint ");
7858   else
7859     uiout->text ("Catchpoint ");
7860   if (uiout->is_mi_like_p ())
7861     {
7862       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
7863       uiout->field_string ("disp", bpdisp_text (b->disposition));
7864     }
7865   uiout->field_int ("bkptno", b->number);
7866   uiout->text (" (vforked process ");
7867   uiout->field_int ("newpid", c->forked_inferior_pid.pid ());
7868   uiout->text ("), ");
7869   return PRINT_SRC_AND_LOC;
7870 }
7871
7872 /* Implement the "print_one" breakpoint_ops method for vfork
7873    catchpoints.  */
7874
7875 static void
7876 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7877 {
7878   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7879   struct value_print_options opts;
7880   struct ui_out *uiout = current_uiout;
7881
7882   get_user_print_options (&opts);
7883   /* Field 4, the address, is omitted (which makes the columns not
7884      line up too nicely with the headers, but the effect is relatively
7885      readable).  */
7886   if (opts.addressprint)
7887     uiout->field_skip ("addr");
7888   annotate_field (5);
7889   uiout->text ("vfork");
7890   if (c->forked_inferior_pid != null_ptid)
7891     {
7892       uiout->text (", process ");
7893       uiout->field_int ("what", c->forked_inferior_pid.pid ());
7894       uiout->spaces (1);
7895     }
7896
7897   if (uiout->is_mi_like_p ())
7898     uiout->field_string ("catch-type", "vfork");
7899 }
7900
7901 /* Implement the "print_mention" breakpoint_ops method for vfork
7902    catchpoints.  */
7903
7904 static void
7905 print_mention_catch_vfork (struct breakpoint *b)
7906 {
7907   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7908 }
7909
7910 /* Implement the "print_recreate" breakpoint_ops method for vfork
7911    catchpoints.  */
7912
7913 static void
7914 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7915 {
7916   fprintf_unfiltered (fp, "catch vfork");
7917   print_recreate_thread (b, fp);
7918 }
7919
7920 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7921
7922 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7923
7924 /* An instance of this type is used to represent an solib catchpoint.
7925    A breakpoint is really of this type iff its ops pointer points to
7926    CATCH_SOLIB_BREAKPOINT_OPS.  */
7927
7928 struct solib_catchpoint : public breakpoint
7929 {
7930   ~solib_catchpoint () override;
7931
7932   /* True for "catch load", false for "catch unload".  */
7933   unsigned char is_load;
7934
7935   /* Regular expression to match, if any.  COMPILED is only valid when
7936      REGEX is non-NULL.  */
7937   char *regex;
7938   std::unique_ptr<compiled_regex> compiled;
7939 };
7940
7941 solib_catchpoint::~solib_catchpoint ()
7942 {
7943   xfree (this->regex);
7944 }
7945
7946 static int
7947 insert_catch_solib (struct bp_location *ignore)
7948 {
7949   return 0;
7950 }
7951
7952 static int
7953 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
7954 {
7955   return 0;
7956 }
7957
7958 static int
7959 breakpoint_hit_catch_solib (const struct bp_location *bl,
7960                             const address_space *aspace,
7961                             CORE_ADDR bp_addr,
7962                             const struct target_waitstatus *ws)
7963 {
7964   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7965   struct breakpoint *other;
7966
7967   if (ws->kind == TARGET_WAITKIND_LOADED)
7968     return 1;
7969
7970   ALL_BREAKPOINTS (other)
7971   {
7972     struct bp_location *other_bl;
7973
7974     if (other == bl->owner)
7975       continue;
7976
7977     if (other->type != bp_shlib_event)
7978       continue;
7979
7980     if (self->pspace != NULL && other->pspace != self->pspace)
7981       continue;
7982
7983     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7984       {
7985         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7986           return 1;
7987       }
7988   }
7989
7990   return 0;
7991 }
7992
7993 static void
7994 check_status_catch_solib (struct bpstats *bs)
7995 {
7996   struct solib_catchpoint *self
7997     = (struct solib_catchpoint *) bs->breakpoint_at;
7998
7999   if (self->is_load)
8000     {
8001       for (so_list *iter : current_program_space->added_solibs)
8002         {
8003           if (!self->regex
8004               || self->compiled->exec (iter->so_name, 0, NULL, 0) == 0)
8005             return;
8006         }
8007     }
8008   else
8009     {
8010       for (const std::string &iter : current_program_space->deleted_solibs)
8011         {
8012           if (!self->regex
8013               || self->compiled->exec (iter.c_str (), 0, NULL, 0) == 0)
8014             return;
8015         }
8016     }
8017
8018   bs->stop = 0;
8019   bs->print_it = print_it_noop;
8020 }
8021
8022 static enum print_stop_action
8023 print_it_catch_solib (bpstat bs)
8024 {
8025   struct breakpoint *b = bs->breakpoint_at;
8026   struct ui_out *uiout = current_uiout;
8027
8028   annotate_catchpoint (b->number);
8029   maybe_print_thread_hit_breakpoint (uiout);
8030   if (b->disposition == disp_del)
8031     uiout->text ("Temporary catchpoint ");
8032   else
8033     uiout->text ("Catchpoint ");
8034   uiout->field_int ("bkptno", b->number);
8035   uiout->text ("\n");
8036   if (uiout->is_mi_like_p ())
8037     uiout->field_string ("disp", bpdisp_text (b->disposition));
8038   print_solib_event (1);
8039   return PRINT_SRC_AND_LOC;
8040 }
8041
8042 static void
8043 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8044 {
8045   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8046   struct value_print_options opts;
8047   struct ui_out *uiout = current_uiout;
8048
8049   get_user_print_options (&opts);
8050   /* Field 4, the address, is omitted (which makes the columns not
8051      line up too nicely with the headers, but the effect is relatively
8052      readable).  */
8053   if (opts.addressprint)
8054     {
8055       annotate_field (4);
8056       uiout->field_skip ("addr");
8057     }
8058
8059   std::string msg;
8060   annotate_field (5);
8061   if (self->is_load)
8062     {
8063       if (self->regex)
8064         msg = string_printf (_("load of library matching %s"), self->regex);
8065       else
8066         msg = _("load of library");
8067     }
8068   else
8069     {
8070       if (self->regex)
8071         msg = string_printf (_("unload of library matching %s"), self->regex);
8072       else
8073         msg = _("unload of library");
8074     }
8075   uiout->field_string ("what", msg);
8076
8077   if (uiout->is_mi_like_p ())
8078     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8079 }
8080
8081 static void
8082 print_mention_catch_solib (struct breakpoint *b)
8083 {
8084   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8085
8086   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8087                    self->is_load ? "load" : "unload");
8088 }
8089
8090 static void
8091 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8092 {
8093   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8094
8095   fprintf_unfiltered (fp, "%s %s",
8096                       b->disposition == disp_del ? "tcatch" : "catch",
8097                       self->is_load ? "load" : "unload");
8098   if (self->regex)
8099     fprintf_unfiltered (fp, " %s", self->regex);
8100   fprintf_unfiltered (fp, "\n");
8101 }
8102
8103 static struct breakpoint_ops catch_solib_breakpoint_ops;
8104
8105 /* Shared helper function (MI and CLI) for creating and installing
8106    a shared object event catchpoint.  If IS_LOAD is non-zero then
8107    the events to be caught are load events, otherwise they are
8108    unload events.  If IS_TEMP is non-zero the catchpoint is a
8109    temporary one.  If ENABLED is non-zero the catchpoint is
8110    created in an enabled state.  */
8111
8112 void
8113 add_solib_catchpoint (const char *arg, int is_load, int is_temp, int enabled)
8114 {
8115   struct gdbarch *gdbarch = get_current_arch ();
8116
8117   if (!arg)
8118     arg = "";
8119   arg = skip_spaces (arg);
8120
8121   std::unique_ptr<solib_catchpoint> c (new solib_catchpoint ());
8122
8123   if (*arg != '\0')
8124     {
8125       c->compiled.reset (new compiled_regex (arg, REG_NOSUB,
8126                                              _("Invalid regexp")));
8127       c->regex = xstrdup (arg);
8128     }
8129
8130   c->is_load = is_load;
8131   init_catchpoint (c.get (), gdbarch, is_temp, NULL,
8132                    &catch_solib_breakpoint_ops);
8133
8134   c->enable_state = enabled ? bp_enabled : bp_disabled;
8135
8136   install_breakpoint (0, std::move (c), 1);
8137 }
8138
8139 /* A helper function that does all the work for "catch load" and
8140    "catch unload".  */
8141
8142 static void
8143 catch_load_or_unload (const char *arg, int from_tty, int is_load,
8144                       struct cmd_list_element *command)
8145 {
8146   int tempflag;
8147   const int enabled = 1;
8148
8149   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8150
8151   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8152 }
8153
8154 static void
8155 catch_load_command_1 (const char *arg, int from_tty,
8156                       struct cmd_list_element *command)
8157 {
8158   catch_load_or_unload (arg, from_tty, 1, command);
8159 }
8160
8161 static void
8162 catch_unload_command_1 (const char *arg, int from_tty,
8163                         struct cmd_list_element *command)
8164 {
8165   catch_load_or_unload (arg, from_tty, 0, command);
8166 }
8167
8168 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8169    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8170    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8171    the breakpoint_ops structure associated to the catchpoint.  */
8172
8173 void
8174 init_catchpoint (struct breakpoint *b,
8175                  struct gdbarch *gdbarch, int tempflag,
8176                  const char *cond_string,
8177                  const struct breakpoint_ops *ops)
8178 {
8179   symtab_and_line sal;
8180   sal.pspace = current_program_space;
8181
8182   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8183
8184   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8185   b->disposition = tempflag ? disp_del : disp_donttouch;
8186 }
8187
8188 void
8189 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8190 {
8191   breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8192   set_breakpoint_number (internal, b);
8193   if (is_tracepoint (b))
8194     set_tracepoint_count (breakpoint_count);
8195   if (!internal)
8196     mention (b);
8197   gdb::observers::breakpoint_created.notify (b);
8198
8199   if (update_gll)
8200     update_global_location_list (UGLL_MAY_INSERT);
8201 }
8202
8203 static void
8204 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8205                                     int tempflag, const char *cond_string,
8206                                     const struct breakpoint_ops *ops)
8207 {
8208   std::unique_ptr<fork_catchpoint> c (new fork_catchpoint ());
8209
8210   init_catchpoint (c.get (), gdbarch, tempflag, cond_string, ops);
8211
8212   c->forked_inferior_pid = null_ptid;
8213
8214   install_breakpoint (0, std::move (c), 1);
8215 }
8216
8217 /* Exec catchpoints.  */
8218
8219 /* An instance of this type is used to represent an exec catchpoint.
8220    A breakpoint is really of this type iff its ops pointer points to
8221    CATCH_EXEC_BREAKPOINT_OPS.  */
8222
8223 struct exec_catchpoint : public breakpoint
8224 {
8225   ~exec_catchpoint () override;
8226
8227   /* Filename of a program whose exec triggered this catchpoint.
8228      This field is only valid immediately after this catchpoint has
8229      triggered.  */
8230   char *exec_pathname;
8231 };
8232
8233 /* Exec catchpoint destructor.  */
8234
8235 exec_catchpoint::~exec_catchpoint ()
8236 {
8237   xfree (this->exec_pathname);
8238 }
8239
8240 static int
8241 insert_catch_exec (struct bp_location *bl)
8242 {
8243   return target_insert_exec_catchpoint (inferior_ptid.pid ());
8244 }
8245
8246 static int
8247 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8248 {
8249   return target_remove_exec_catchpoint (inferior_ptid.pid ());
8250 }
8251
8252 static int
8253 breakpoint_hit_catch_exec (const struct bp_location *bl,
8254                            const address_space *aspace, CORE_ADDR bp_addr,
8255                            const struct target_waitstatus *ws)
8256 {
8257   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8258
8259   if (ws->kind != TARGET_WAITKIND_EXECD)
8260     return 0;
8261
8262   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8263   return 1;
8264 }
8265
8266 static enum print_stop_action
8267 print_it_catch_exec (bpstat bs)
8268 {
8269   struct ui_out *uiout = current_uiout;
8270   struct breakpoint *b = bs->breakpoint_at;
8271   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8272
8273   annotate_catchpoint (b->number);
8274   maybe_print_thread_hit_breakpoint (uiout);
8275   if (b->disposition == disp_del)
8276     uiout->text ("Temporary catchpoint ");
8277   else
8278     uiout->text ("Catchpoint ");
8279   if (uiout->is_mi_like_p ())
8280     {
8281       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8282       uiout->field_string ("disp", bpdisp_text (b->disposition));
8283     }
8284   uiout->field_int ("bkptno", b->number);
8285   uiout->text (" (exec'd ");
8286   uiout->field_string ("new-exec", c->exec_pathname);
8287   uiout->text ("), ");
8288
8289   return PRINT_SRC_AND_LOC;
8290 }
8291
8292 static void
8293 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8294 {
8295   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8296   struct value_print_options opts;
8297   struct ui_out *uiout = current_uiout;
8298
8299   get_user_print_options (&opts);
8300
8301   /* Field 4, the address, is omitted (which makes the columns
8302      not line up too nicely with the headers, but the effect
8303      is relatively readable).  */
8304   if (opts.addressprint)
8305     uiout->field_skip ("addr");
8306   annotate_field (5);
8307   uiout->text ("exec");
8308   if (c->exec_pathname != NULL)
8309     {
8310       uiout->text (", program \"");
8311       uiout->field_string ("what", c->exec_pathname);
8312       uiout->text ("\" ");
8313     }
8314
8315   if (uiout->is_mi_like_p ())
8316     uiout->field_string ("catch-type", "exec");
8317 }
8318
8319 static void
8320 print_mention_catch_exec (struct breakpoint *b)
8321 {
8322   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8323 }
8324
8325 /* Implement the "print_recreate" breakpoint_ops method for exec
8326    catchpoints.  */
8327
8328 static void
8329 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8330 {
8331   fprintf_unfiltered (fp, "catch exec");
8332   print_recreate_thread (b, fp);
8333 }
8334
8335 static struct breakpoint_ops catch_exec_breakpoint_ops;
8336
8337 static int
8338 hw_breakpoint_used_count (void)
8339 {
8340   int i = 0;
8341   struct breakpoint *b;
8342   struct bp_location *bl;
8343
8344   ALL_BREAKPOINTS (b)
8345   {
8346     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8347       for (bl = b->loc; bl; bl = bl->next)
8348         {
8349           /* Special types of hardware breakpoints may use more than
8350              one register.  */
8351           i += b->ops->resources_needed (bl);
8352         }
8353   }
8354
8355   return i;
8356 }
8357
8358 /* Returns the resources B would use if it were a hardware
8359    watchpoint.  */
8360
8361 static int
8362 hw_watchpoint_use_count (struct breakpoint *b)
8363 {
8364   int i = 0;
8365   struct bp_location *bl;
8366
8367   if (!breakpoint_enabled (b))
8368     return 0;
8369
8370   for (bl = b->loc; bl; bl = bl->next)
8371     {
8372       /* Special types of hardware watchpoints may use more than
8373          one register.  */
8374       i += b->ops->resources_needed (bl);
8375     }
8376
8377   return i;
8378 }
8379
8380 /* Returns the sum the used resources of all hardware watchpoints of
8381    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8382    the sum of the used resources of all hardware watchpoints of other
8383    types _not_ TYPE.  */
8384
8385 static int
8386 hw_watchpoint_used_count_others (struct breakpoint *except,
8387                                  enum bptype type, int *other_type_used)
8388 {
8389   int i = 0;
8390   struct breakpoint *b;
8391
8392   *other_type_used = 0;
8393   ALL_BREAKPOINTS (b)
8394     {
8395       if (b == except)
8396         continue;
8397       if (!breakpoint_enabled (b))
8398         continue;
8399
8400       if (b->type == type)
8401         i += hw_watchpoint_use_count (b);
8402       else if (is_hardware_watchpoint (b))
8403         *other_type_used = 1;
8404     }
8405
8406   return i;
8407 }
8408
8409 void
8410 disable_watchpoints_before_interactive_call_start (void)
8411 {
8412   struct breakpoint *b;
8413
8414   ALL_BREAKPOINTS (b)
8415   {
8416     if (is_watchpoint (b) && breakpoint_enabled (b))
8417       {
8418         b->enable_state = bp_call_disabled;
8419         update_global_location_list (UGLL_DONT_INSERT);
8420       }
8421   }
8422 }
8423
8424 void
8425 enable_watchpoints_after_interactive_call_stop (void)
8426 {
8427   struct breakpoint *b;
8428
8429   ALL_BREAKPOINTS (b)
8430   {
8431     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8432       {
8433         b->enable_state = bp_enabled;
8434         update_global_location_list (UGLL_MAY_INSERT);
8435       }
8436   }
8437 }
8438
8439 void
8440 disable_breakpoints_before_startup (void)
8441 {
8442   current_program_space->executing_startup = 1;
8443   update_global_location_list (UGLL_DONT_INSERT);
8444 }
8445
8446 void
8447 enable_breakpoints_after_startup (void)
8448 {
8449   current_program_space->executing_startup = 0;
8450   breakpoint_re_set ();
8451 }
8452
8453 /* Create a new single-step breakpoint for thread THREAD, with no
8454    locations.  */
8455
8456 static struct breakpoint *
8457 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8458 {
8459   std::unique_ptr<breakpoint> b (new breakpoint ());
8460
8461   init_raw_breakpoint_without_location (b.get (), gdbarch, bp_single_step,
8462                                         &momentary_breakpoint_ops);
8463
8464   b->disposition = disp_donttouch;
8465   b->frame_id = null_frame_id;
8466
8467   b->thread = thread;
8468   gdb_assert (b->thread != 0);
8469
8470   return add_to_breakpoint_chain (std::move (b));
8471 }
8472
8473 /* Set a momentary breakpoint of type TYPE at address specified by
8474    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8475    frame.  */
8476
8477 breakpoint_up
8478 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8479                           struct frame_id frame_id, enum bptype type)
8480 {
8481   struct breakpoint *b;
8482
8483   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8484      tail-called one.  */
8485   gdb_assert (!frame_id_artificial_p (frame_id));
8486
8487   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8488   b->enable_state = bp_enabled;
8489   b->disposition = disp_donttouch;
8490   b->frame_id = frame_id;
8491
8492   b->thread = inferior_thread ()->global_num;
8493
8494   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8495
8496   return breakpoint_up (b);
8497 }
8498
8499 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8500    The new breakpoint will have type TYPE, use OPS as its
8501    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8502
8503 static struct breakpoint *
8504 momentary_breakpoint_from_master (struct breakpoint *orig,
8505                                   enum bptype type,
8506                                   const struct breakpoint_ops *ops,
8507                                   int loc_enabled)
8508 {
8509   struct breakpoint *copy;
8510
8511   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8512   copy->loc = allocate_bp_location (copy);
8513   set_breakpoint_location_function (copy->loc, 1);
8514
8515   copy->loc->gdbarch = orig->loc->gdbarch;
8516   copy->loc->requested_address = orig->loc->requested_address;
8517   copy->loc->address = orig->loc->address;
8518   copy->loc->section = orig->loc->section;
8519   copy->loc->pspace = orig->loc->pspace;
8520   copy->loc->probe = orig->loc->probe;
8521   copy->loc->line_number = orig->loc->line_number;
8522   copy->loc->symtab = orig->loc->symtab;
8523   copy->loc->enabled = loc_enabled;
8524   copy->frame_id = orig->frame_id;
8525   copy->thread = orig->thread;
8526   copy->pspace = orig->pspace;
8527
8528   copy->enable_state = bp_enabled;
8529   copy->disposition = disp_donttouch;
8530   copy->number = internal_breakpoint_number--;
8531
8532   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8533   return copy;
8534 }
8535
8536 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8537    ORIG is NULL.  */
8538
8539 struct breakpoint *
8540 clone_momentary_breakpoint (struct breakpoint *orig)
8541 {
8542   /* If there's nothing to clone, then return nothing.  */
8543   if (orig == NULL)
8544     return NULL;
8545
8546   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8547 }
8548
8549 breakpoint_up
8550 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8551                                 enum bptype type)
8552 {
8553   struct symtab_and_line sal;
8554
8555   sal = find_pc_line (pc, 0);
8556   sal.pc = pc;
8557   sal.section = find_pc_overlay (pc);
8558   sal.explicit_pc = 1;
8559
8560   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8561 }
8562 \f
8563
8564 /* Tell the user we have just set a breakpoint B.  */
8565
8566 static void
8567 mention (struct breakpoint *b)
8568 {
8569   b->ops->print_mention (b);
8570   current_uiout->text ("\n");
8571 }
8572 \f
8573
8574 static int bp_loc_is_permanent (struct bp_location *loc);
8575
8576 static struct bp_location *
8577 add_location_to_breakpoint (struct breakpoint *b,
8578                             const struct symtab_and_line *sal)
8579 {
8580   struct bp_location *loc, **tmp;
8581   CORE_ADDR adjusted_address;
8582   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8583
8584   if (loc_gdbarch == NULL)
8585     loc_gdbarch = b->gdbarch;
8586
8587   /* Adjust the breakpoint's address prior to allocating a location.
8588      Once we call allocate_bp_location(), that mostly uninitialized
8589      location will be placed on the location chain.  Adjustment of the
8590      breakpoint may cause target_read_memory() to be called and we do
8591      not want its scan of the location chain to find a breakpoint and
8592      location that's only been partially initialized.  */
8593   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8594                                                 sal->pc, b->type);
8595
8596   /* Sort the locations by their ADDRESS.  */
8597   loc = allocate_bp_location (b);
8598   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8599        tmp = &((*tmp)->next))
8600     ;
8601   loc->next = *tmp;
8602   *tmp = loc;
8603
8604   loc->requested_address = sal->pc;
8605   loc->address = adjusted_address;
8606   loc->pspace = sal->pspace;
8607   loc->probe.prob = sal->prob;
8608   loc->probe.objfile = sal->objfile;
8609   gdb_assert (loc->pspace != NULL);
8610   loc->section = sal->section;
8611   loc->gdbarch = loc_gdbarch;
8612   loc->line_number = sal->line;
8613   loc->symtab = sal->symtab;
8614   loc->symbol = sal->symbol;
8615   loc->msymbol = sal->msymbol;
8616   loc->objfile = sal->objfile;
8617
8618   set_breakpoint_location_function (loc,
8619                                     sal->explicit_pc || sal->explicit_line);
8620
8621   /* While by definition, permanent breakpoints are already present in the
8622      code, we don't mark the location as inserted.  Normally one would expect
8623      that GDB could rely on that breakpoint instruction to stop the program,
8624      thus removing the need to insert its own breakpoint, except that executing
8625      the breakpoint instruction can kill the target instead of reporting a
8626      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8627      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8628      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8629      breakpoint be inserted normally results in QEMU knowing about the GDB
8630      breakpoint, and thus trap before the breakpoint instruction is executed.
8631      (If GDB later needs to continue execution past the permanent breakpoint,
8632      it manually increments the PC, thus avoiding executing the breakpoint
8633      instruction.)  */
8634   if (bp_loc_is_permanent (loc))
8635     loc->permanent = 1;
8636
8637   return loc;
8638 }
8639 \f
8640
8641 /* See breakpoint.h.  */
8642
8643 int
8644 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
8645 {
8646   int len;
8647   CORE_ADDR addr;
8648   const gdb_byte *bpoint;
8649   gdb_byte *target_mem;
8650
8651   addr = address;
8652   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
8653
8654   /* Software breakpoints unsupported?  */
8655   if (bpoint == NULL)
8656     return 0;
8657
8658   target_mem = (gdb_byte *) alloca (len);
8659
8660   /* Enable the automatic memory restoration from breakpoints while
8661      we read the memory.  Otherwise we could say about our temporary
8662      breakpoints they are permanent.  */
8663   scoped_restore restore_memory
8664     = make_scoped_restore_show_memory_breakpoints (0);
8665
8666   if (target_read_memory (address, target_mem, len) == 0
8667       && memcmp (target_mem, bpoint, len) == 0)
8668     return 1;
8669
8670   return 0;
8671 }
8672
8673 /* Return 1 if LOC is pointing to a permanent breakpoint,
8674    return 0 otherwise.  */
8675
8676 static int
8677 bp_loc_is_permanent (struct bp_location *loc)
8678 {
8679   gdb_assert (loc != NULL);
8680
8681   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
8682      attempt to read from the addresses the locations of these breakpoint types
8683      point to.  program_breakpoint_here_p, below, will attempt to read
8684      memory.  */
8685   if (!breakpoint_address_is_meaningful (loc->owner))
8686     return 0;
8687
8688   scoped_restore_current_pspace_and_thread restore_pspace_thread;
8689   switch_to_program_space_and_thread (loc->pspace);
8690   return program_breakpoint_here_p (loc->gdbarch, loc->address);
8691 }
8692
8693 /* Build a command list for the dprintf corresponding to the current
8694    settings of the dprintf style options.  */
8695
8696 static void
8697 update_dprintf_command_list (struct breakpoint *b)
8698 {
8699   char *dprintf_args = b->extra_string;
8700   char *printf_line = NULL;
8701
8702   if (!dprintf_args)
8703     return;
8704
8705   dprintf_args = skip_spaces (dprintf_args);
8706
8707   /* Allow a comma, as it may have terminated a location, but don't
8708      insist on it.  */
8709   if (*dprintf_args == ',')
8710     ++dprintf_args;
8711   dprintf_args = skip_spaces (dprintf_args);
8712
8713   if (*dprintf_args != '"')
8714     error (_("Bad format string, missing '\"'."));
8715
8716   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8717     printf_line = xstrprintf ("printf %s", dprintf_args);
8718   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8719     {
8720       if (!dprintf_function)
8721         error (_("No function supplied for dprintf call"));
8722
8723       if (dprintf_channel && strlen (dprintf_channel) > 0)
8724         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8725                                   dprintf_function,
8726                                   dprintf_channel,
8727                                   dprintf_args);
8728       else
8729         printf_line = xstrprintf ("call (void) %s (%s)",
8730                                   dprintf_function,
8731                                   dprintf_args);
8732     }
8733   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8734     {
8735       if (target_can_run_breakpoint_commands ())
8736         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8737       else
8738         {
8739           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8740           printf_line = xstrprintf ("printf %s", dprintf_args);
8741         }
8742     }
8743   else
8744     internal_error (__FILE__, __LINE__,
8745                     _("Invalid dprintf style."));
8746
8747   gdb_assert (printf_line != NULL);
8748
8749   /* Manufacture a printf sequence.  */
8750   struct command_line *printf_cmd_line
8751     = new struct command_line (simple_control, printf_line);
8752   breakpoint_set_commands (b, counted_command_line (printf_cmd_line,
8753                                                     command_lines_deleter ()));
8754 }
8755
8756 /* Update all dprintf commands, making their command lists reflect
8757    current style settings.  */
8758
8759 static void
8760 update_dprintf_commands (const char *args, int from_tty,
8761                          struct cmd_list_element *c)
8762 {
8763   struct breakpoint *b;
8764
8765   ALL_BREAKPOINTS (b)
8766     {
8767       if (b->type == bp_dprintf)
8768         update_dprintf_command_list (b);
8769     }
8770 }
8771
8772 /* Create a breakpoint with SAL as location.  Use LOCATION
8773    as a description of the location, and COND_STRING
8774    as condition expression.  If LOCATION is NULL then create an
8775    "address location" from the address in the SAL.  */
8776
8777 static void
8778 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8779                      gdb::array_view<const symtab_and_line> sals,
8780                      event_location_up &&location,
8781                      gdb::unique_xmalloc_ptr<char> filter,
8782                      gdb::unique_xmalloc_ptr<char> cond_string,
8783                      gdb::unique_xmalloc_ptr<char> extra_string,
8784                      enum bptype type, enum bpdisp disposition,
8785                      int thread, int task, int ignore_count,
8786                      const struct breakpoint_ops *ops, int from_tty,
8787                      int enabled, int internal, unsigned flags,
8788                      int display_canonical)
8789 {
8790   int i;
8791
8792   if (type == bp_hardware_breakpoint)
8793     {
8794       int target_resources_ok;
8795
8796       i = hw_breakpoint_used_count ();
8797       target_resources_ok =
8798         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8799                                             i + 1, 0);
8800       if (target_resources_ok == 0)
8801         error (_("No hardware breakpoint support in the target."));
8802       else if (target_resources_ok < 0)
8803         error (_("Hardware breakpoints used exceeds limit."));
8804     }
8805
8806   gdb_assert (!sals.empty ());
8807
8808   for (const auto &sal : sals)
8809     {
8810       struct bp_location *loc;
8811
8812       if (from_tty)
8813         {
8814           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8815           if (!loc_gdbarch)
8816             loc_gdbarch = gdbarch;
8817
8818           describe_other_breakpoints (loc_gdbarch,
8819                                       sal.pspace, sal.pc, sal.section, thread);
8820         }
8821
8822       if (&sal == &sals[0])
8823         {
8824           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8825           b->thread = thread;
8826           b->task = task;
8827
8828           b->cond_string = cond_string.release ();
8829           b->extra_string = extra_string.release ();
8830           b->ignore_count = ignore_count;
8831           b->enable_state = enabled ? bp_enabled : bp_disabled;
8832           b->disposition = disposition;
8833
8834           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8835             b->loc->inserted = 1;
8836
8837           if (type == bp_static_tracepoint)
8838             {
8839               struct tracepoint *t = (struct tracepoint *) b;
8840               struct static_tracepoint_marker marker;
8841
8842               if (strace_marker_p (b))
8843                 {
8844                   /* We already know the marker exists, otherwise, we
8845                      wouldn't see a sal for it.  */
8846                   const char *p
8847                     = &event_location_to_string (b->location.get ())[3];
8848                   const char *endp;
8849
8850                   p = skip_spaces (p);
8851
8852                   endp = skip_to_space (p);
8853
8854                   t->static_trace_marker_id.assign (p, endp - p);
8855
8856                   printf_filtered (_("Probed static tracepoint "
8857                                      "marker \"%s\"\n"),
8858                                    t->static_trace_marker_id.c_str ());
8859                 }
8860               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8861                 {
8862                   t->static_trace_marker_id = std::move (marker.str_id);
8863
8864                   printf_filtered (_("Probed static tracepoint "
8865                                      "marker \"%s\"\n"),
8866                                    t->static_trace_marker_id.c_str ());
8867                 }
8868               else
8869                 warning (_("Couldn't determine the static "
8870                            "tracepoint marker to probe"));
8871             }
8872
8873           loc = b->loc;
8874         }
8875       else
8876         {
8877           loc = add_location_to_breakpoint (b, &sal);
8878           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8879             loc->inserted = 1;
8880         }
8881
8882       if (b->cond_string)
8883         {
8884           const char *arg = b->cond_string;
8885
8886           loc->cond = parse_exp_1 (&arg, loc->address,
8887                                    block_for_pc (loc->address), 0);
8888           if (*arg)
8889               error (_("Garbage '%s' follows condition"), arg);
8890         }
8891
8892       /* Dynamic printf requires and uses additional arguments on the
8893          command line, otherwise it's an error.  */
8894       if (type == bp_dprintf)
8895         {
8896           if (b->extra_string)
8897             update_dprintf_command_list (b);
8898           else
8899             error (_("Format string required"));
8900         }
8901       else if (b->extra_string)
8902         error (_("Garbage '%s' at end of command"), b->extra_string);
8903     }
8904
8905   b->display_canonical = display_canonical;
8906   if (location != NULL)
8907     b->location = std::move (location);
8908   else
8909     b->location = new_address_location (b->loc->address, NULL, 0);
8910   b->filter = filter.release ();
8911 }
8912
8913 static void
8914 create_breakpoint_sal (struct gdbarch *gdbarch,
8915                        gdb::array_view<const symtab_and_line> sals,
8916                        event_location_up &&location,
8917                        gdb::unique_xmalloc_ptr<char> filter,
8918                        gdb::unique_xmalloc_ptr<char> cond_string,
8919                        gdb::unique_xmalloc_ptr<char> extra_string,
8920                        enum bptype type, enum bpdisp disposition,
8921                        int thread, int task, int ignore_count,
8922                        const struct breakpoint_ops *ops, int from_tty,
8923                        int enabled, int internal, unsigned flags,
8924                        int display_canonical)
8925 {
8926   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (type);
8927
8928   init_breakpoint_sal (b.get (), gdbarch,
8929                        sals, std::move (location),
8930                        std::move (filter),
8931                        std::move (cond_string),
8932                        std::move (extra_string),
8933                        type, disposition,
8934                        thread, task, ignore_count,
8935                        ops, from_tty,
8936                        enabled, internal, flags,
8937                        display_canonical);
8938
8939   install_breakpoint (internal, std::move (b), 0);
8940 }
8941
8942 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
8943    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8944    value.  COND_STRING, if not NULL, specified the condition to be
8945    used for all breakpoints.  Essentially the only case where
8946    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8947    function.  In that case, it's still not possible to specify
8948    separate conditions for different overloaded functions, so
8949    we take just a single condition string.
8950    
8951    NOTE: If the function succeeds, the caller is expected to cleanup
8952    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8953    array contents).  If the function fails (error() is called), the
8954    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8955    COND and SALS arrays and each of those arrays contents.  */
8956
8957 static void
8958 create_breakpoints_sal (struct gdbarch *gdbarch,
8959                         struct linespec_result *canonical,
8960                         gdb::unique_xmalloc_ptr<char> cond_string,
8961                         gdb::unique_xmalloc_ptr<char> extra_string,
8962                         enum bptype type, enum bpdisp disposition,
8963                         int thread, int task, int ignore_count,
8964                         const struct breakpoint_ops *ops, int from_tty,
8965                         int enabled, int internal, unsigned flags)
8966 {
8967   if (canonical->pre_expanded)
8968     gdb_assert (canonical->lsals.size () == 1);
8969
8970   for (const auto &lsal : canonical->lsals)
8971     {
8972       /* Note that 'location' can be NULL in the case of a plain
8973          'break', without arguments.  */
8974       event_location_up location
8975         = (canonical->location != NULL
8976            ? copy_event_location (canonical->location.get ()) : NULL);
8977       gdb::unique_xmalloc_ptr<char> filter_string
8978         (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
8979
8980       create_breakpoint_sal (gdbarch, lsal.sals,
8981                              std::move (location),
8982                              std::move (filter_string),
8983                              std::move (cond_string),
8984                              std::move (extra_string),
8985                              type, disposition,
8986                              thread, task, ignore_count, ops,
8987                              from_tty, enabled, internal, flags,
8988                              canonical->special_display);
8989     }
8990 }
8991
8992 /* Parse LOCATION which is assumed to be a SAL specification possibly
8993    followed by conditionals.  On return, SALS contains an array of SAL
8994    addresses found.  LOCATION points to the end of the SAL (for
8995    linespec locations).
8996
8997    The array and the line spec strings are allocated on the heap, it is
8998    the caller's responsibility to free them.  */
8999
9000 static void
9001 parse_breakpoint_sals (const struct event_location *location,
9002                        struct linespec_result *canonical)
9003 {
9004   struct symtab_and_line cursal;
9005
9006   if (event_location_type (location) == LINESPEC_LOCATION)
9007     {
9008       const char *spec = get_linespec_location (location)->spec_string;
9009
9010       if (spec == NULL)
9011         {
9012           /* The last displayed codepoint, if it's valid, is our default
9013              breakpoint address.  */
9014           if (last_displayed_sal_is_valid ())
9015             {
9016               /* Set sal's pspace, pc, symtab, and line to the values
9017                  corresponding to the last call to print_frame_info.
9018                  Be sure to reinitialize LINE with NOTCURRENT == 0
9019                  as the breakpoint line number is inappropriate otherwise.
9020                  find_pc_line would adjust PC, re-set it back.  */
9021               symtab_and_line sal = get_last_displayed_sal ();
9022               CORE_ADDR pc = sal.pc;
9023
9024               sal = find_pc_line (pc, 0);
9025
9026               /* "break" without arguments is equivalent to "break *PC"
9027                  where PC is the last displayed codepoint's address.  So
9028                  make sure to set sal.explicit_pc to prevent GDB from
9029                  trying to expand the list of sals to include all other
9030                  instances with the same symtab and line.  */
9031               sal.pc = pc;
9032               sal.explicit_pc = 1;
9033
9034               struct linespec_sals lsal;
9035               lsal.sals = {sal};
9036               lsal.canonical = NULL;
9037
9038               canonical->lsals.push_back (std::move (lsal));
9039               return;
9040             }
9041           else
9042             error (_("No default breakpoint address now."));
9043         }
9044     }
9045
9046   /* Force almost all breakpoints to be in terms of the
9047      current_source_symtab (which is decode_line_1's default).
9048      This should produce the results we want almost all of the
9049      time while leaving default_breakpoint_* alone.
9050
9051      ObjC: However, don't match an Objective-C method name which
9052      may have a '+' or '-' succeeded by a '['.  */
9053   cursal = get_current_source_symtab_and_line ();
9054   if (last_displayed_sal_is_valid ())
9055     {
9056       const char *spec = NULL;
9057
9058       if (event_location_type (location) == LINESPEC_LOCATION)
9059         spec = get_linespec_location (location)->spec_string;
9060
9061       if (!cursal.symtab
9062           || (spec != NULL
9063               && strchr ("+-", spec[0]) != NULL
9064               && spec[1] != '['))
9065         {
9066           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9067                             get_last_displayed_symtab (),
9068                             get_last_displayed_line (),
9069                             canonical, NULL, NULL);
9070           return;
9071         }
9072     }
9073
9074   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9075                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9076 }
9077
9078
9079 /* Convert each SAL into a real PC.  Verify that the PC can be
9080    inserted as a breakpoint.  If it can't throw an error.  */
9081
9082 static void
9083 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
9084 {    
9085   for (auto &sal : sals)
9086     resolve_sal_pc (&sal);
9087 }
9088
9089 /* Fast tracepoints may have restrictions on valid locations.  For
9090    instance, a fast tracepoint using a jump instead of a trap will
9091    likely have to overwrite more bytes than a trap would, and so can
9092    only be placed where the instruction is longer than the jump, or a
9093    multi-instruction sequence does not have a jump into the middle of
9094    it, etc.  */
9095
9096 static void
9097 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9098                             gdb::array_view<const symtab_and_line> sals)
9099 {
9100   for (const auto &sal : sals)
9101     {
9102       struct gdbarch *sarch;
9103
9104       sarch = get_sal_arch (sal);
9105       /* We fall back to GDBARCH if there is no architecture
9106          associated with SAL.  */
9107       if (sarch == NULL)
9108         sarch = gdbarch;
9109       std::string msg;
9110       if (!gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg))
9111         error (_("May not have a fast tracepoint at %s%s"),
9112                paddress (sarch, sal.pc), msg.c_str ());
9113     }
9114 }
9115
9116 /* Given TOK, a string specification of condition and thread, as
9117    accepted by the 'break' command, extract the condition
9118    string and thread number and set *COND_STRING and *THREAD.
9119    PC identifies the context at which the condition should be parsed.
9120    If no condition is found, *COND_STRING is set to NULL.
9121    If no thread is found, *THREAD is set to -1.  */
9122
9123 static void
9124 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9125                            char **cond_string, int *thread, int *task,
9126                            char **rest)
9127 {
9128   *cond_string = NULL;
9129   *thread = -1;
9130   *task = 0;
9131   *rest = NULL;
9132
9133   while (tok && *tok)
9134     {
9135       const char *end_tok;
9136       int toklen;
9137       const char *cond_start = NULL;
9138       const char *cond_end = NULL;
9139
9140       tok = skip_spaces (tok);
9141
9142       if ((*tok == '"' || *tok == ',') && rest)
9143         {
9144           *rest = savestring (tok, strlen (tok));
9145           return;
9146         }
9147
9148       end_tok = skip_to_space (tok);
9149
9150       toklen = end_tok - tok;
9151
9152       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9153         {
9154           tok = cond_start = end_tok + 1;
9155           parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9156           cond_end = tok;
9157           *cond_string = savestring (cond_start, cond_end - cond_start);
9158         }
9159       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9160         {
9161           const char *tmptok;
9162           struct thread_info *thr;
9163
9164           tok = end_tok + 1;
9165           thr = parse_thread_id (tok, &tmptok);
9166           if (tok == tmptok)
9167             error (_("Junk after thread keyword."));
9168           *thread = thr->global_num;
9169           tok = tmptok;
9170         }
9171       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9172         {
9173           char *tmptok;
9174
9175           tok = end_tok + 1;
9176           *task = strtol (tok, &tmptok, 0);
9177           if (tok == tmptok)
9178             error (_("Junk after task keyword."));
9179           if (!valid_task_id (*task))
9180             error (_("Unknown task %d."), *task);
9181           tok = tmptok;
9182         }
9183       else if (rest)
9184         {
9185           *rest = savestring (tok, strlen (tok));
9186           return;
9187         }
9188       else
9189         error (_("Junk at end of arguments."));
9190     }
9191 }
9192
9193 /* Decode a static tracepoint marker spec.  */
9194
9195 static std::vector<symtab_and_line>
9196 decode_static_tracepoint_spec (const char **arg_p)
9197 {
9198   const char *p = &(*arg_p)[3];
9199   const char *endp;
9200
9201   p = skip_spaces (p);
9202
9203   endp = skip_to_space (p);
9204
9205   std::string marker_str (p, endp - p);
9206
9207   std::vector<static_tracepoint_marker> markers
9208     = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
9209   if (markers.empty ())
9210     error (_("No known static tracepoint marker named %s"),
9211            marker_str.c_str ());
9212
9213   std::vector<symtab_and_line> sals;
9214   sals.reserve (markers.size ());
9215
9216   for (const static_tracepoint_marker &marker : markers)
9217     {
9218       symtab_and_line sal = find_pc_line (marker.address, 0);
9219       sal.pc = marker.address;
9220       sals.push_back (sal);
9221    }
9222
9223   *arg_p = endp;
9224   return sals;
9225 }
9226
9227 /* See breakpoint.h.  */
9228
9229 int
9230 create_breakpoint (struct gdbarch *gdbarch,
9231                    const struct event_location *location,
9232                    const char *cond_string,
9233                    int thread, const char *extra_string,
9234                    int parse_extra,
9235                    int tempflag, enum bptype type_wanted,
9236                    int ignore_count,
9237                    enum auto_boolean pending_break_support,
9238                    const struct breakpoint_ops *ops,
9239                    int from_tty, int enabled, int internal,
9240                    unsigned flags)
9241 {
9242   struct linespec_result canonical;
9243   int pending = 0;
9244   int task = 0;
9245   int prev_bkpt_count = breakpoint_count;
9246
9247   gdb_assert (ops != NULL);
9248
9249   /* If extra_string isn't useful, set it to NULL.  */
9250   if (extra_string != NULL && *extra_string == '\0')
9251     extra_string = NULL;
9252
9253   TRY
9254     {
9255       ops->create_sals_from_location (location, &canonical, type_wanted);
9256     }
9257   CATCH (e, RETURN_MASK_ERROR)
9258     {
9259       /* If caller is interested in rc value from parse, set
9260          value.  */
9261       if (e.error == NOT_FOUND_ERROR)
9262         {
9263           /* If pending breakpoint support is turned off, throw
9264              error.  */
9265
9266           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9267             throw_exception (e);
9268
9269           exception_print (gdb_stderr, e);
9270
9271           /* If pending breakpoint support is auto query and the user
9272              selects no, then simply return the error code.  */
9273           if (pending_break_support == AUTO_BOOLEAN_AUTO
9274               && !nquery (_("Make %s pending on future shared library load? "),
9275                           bptype_string (type_wanted)))
9276             return 0;
9277
9278           /* At this point, either the user was queried about setting
9279              a pending breakpoint and selected yes, or pending
9280              breakpoint behavior is on and thus a pending breakpoint
9281              is defaulted on behalf of the user.  */
9282           pending = 1;
9283         }
9284       else
9285         throw_exception (e);
9286     }
9287   END_CATCH
9288
9289   if (!pending && canonical.lsals.empty ())
9290     return 0;
9291
9292   /* Resolve all line numbers to PC's and verify that the addresses
9293      are ok for the target.  */
9294   if (!pending)
9295     {
9296       for (auto &lsal : canonical.lsals)
9297         breakpoint_sals_to_pc (lsal.sals);
9298     }
9299
9300   /* Fast tracepoints may have additional restrictions on location.  */
9301   if (!pending && type_wanted == bp_fast_tracepoint)
9302     {
9303       for (const auto &lsal : canonical.lsals)
9304         check_fast_tracepoint_sals (gdbarch, lsal.sals);
9305     }
9306
9307   /* Verify that condition can be parsed, before setting any
9308      breakpoints.  Allocate a separate condition expression for each
9309      breakpoint.  */
9310   if (!pending)
9311     {
9312       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9313       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9314
9315       if (parse_extra)
9316         {
9317           char *rest;
9318           char *cond;
9319
9320           const linespec_sals &lsal = canonical.lsals[0];
9321
9322           /* Here we only parse 'arg' to separate condition
9323              from thread number, so parsing in context of first
9324              sal is OK.  When setting the breakpoint we'll
9325              re-parse it in context of each sal.  */
9326
9327           find_condition_and_thread (extra_string, lsal.sals[0].pc,
9328                                      &cond, &thread, &task, &rest);
9329           cond_string_copy.reset (cond);
9330           extra_string_copy.reset (rest);
9331         }
9332       else
9333         {
9334           if (type_wanted != bp_dprintf
9335               && extra_string != NULL && *extra_string != '\0')
9336                 error (_("Garbage '%s' at end of location"), extra_string);
9337
9338           /* Create a private copy of condition string.  */
9339           if (cond_string)
9340             cond_string_copy.reset (xstrdup (cond_string));
9341           /* Create a private copy of any extra string.  */
9342           if (extra_string)
9343             extra_string_copy.reset (xstrdup (extra_string));
9344         }
9345
9346       ops->create_breakpoints_sal (gdbarch, &canonical,
9347                                    std::move (cond_string_copy),
9348                                    std::move (extra_string_copy),
9349                                    type_wanted,
9350                                    tempflag ? disp_del : disp_donttouch,
9351                                    thread, task, ignore_count, ops,
9352                                    from_tty, enabled, internal, flags);
9353     }
9354   else
9355     {
9356       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (type_wanted);
9357
9358       init_raw_breakpoint_without_location (b.get (), gdbarch, type_wanted, ops);
9359       b->location = copy_event_location (location);
9360
9361       if (parse_extra)
9362         b->cond_string = NULL;
9363       else
9364         {
9365           /* Create a private copy of condition string.  */
9366           b->cond_string = cond_string != NULL ? xstrdup (cond_string) : NULL;
9367           b->thread = thread;
9368         }
9369
9370       /* Create a private copy of any extra string.  */
9371       b->extra_string = extra_string != NULL ? xstrdup (extra_string) : NULL;
9372       b->ignore_count = ignore_count;
9373       b->disposition = tempflag ? disp_del : disp_donttouch;
9374       b->condition_not_parsed = 1;
9375       b->enable_state = enabled ? bp_enabled : bp_disabled;
9376       if ((type_wanted != bp_breakpoint
9377            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9378         b->pspace = current_program_space;
9379
9380       install_breakpoint (internal, std::move (b), 0);
9381     }
9382   
9383   if (canonical.lsals.size () > 1)
9384     {
9385       warning (_("Multiple breakpoints were set.\nUse the "
9386                  "\"delete\" command to delete unwanted breakpoints."));
9387       prev_breakpoint_count = prev_bkpt_count;
9388     }
9389
9390   update_global_location_list (UGLL_MAY_INSERT);
9391
9392   return 1;
9393 }
9394
9395 /* Set a breakpoint.
9396    ARG is a string describing breakpoint address,
9397    condition, and thread.
9398    FLAG specifies if a breakpoint is hardware on,
9399    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9400    and BP_TEMPFLAG.  */
9401
9402 static void
9403 break_command_1 (const char *arg, int flag, int from_tty)
9404 {
9405   int tempflag = flag & BP_TEMPFLAG;
9406   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9407                              ? bp_hardware_breakpoint
9408                              : bp_breakpoint);
9409   struct breakpoint_ops *ops;
9410
9411   event_location_up location = string_to_event_location (&arg, current_language);
9412
9413   /* Matching breakpoints on probes.  */
9414   if (location != NULL
9415       && event_location_type (location.get ()) == PROBE_LOCATION)
9416     ops = &bkpt_probe_breakpoint_ops;
9417   else
9418     ops = &bkpt_breakpoint_ops;
9419
9420   create_breakpoint (get_current_arch (),
9421                      location.get (),
9422                      NULL, 0, arg, 1 /* parse arg */,
9423                      tempflag, type_wanted,
9424                      0 /* Ignore count */,
9425                      pending_break_support,
9426                      ops,
9427                      from_tty,
9428                      1 /* enabled */,
9429                      0 /* internal */,
9430                      0);
9431 }
9432
9433 /* Helper function for break_command_1 and disassemble_command.  */
9434
9435 void
9436 resolve_sal_pc (struct symtab_and_line *sal)
9437 {
9438   CORE_ADDR pc;
9439
9440   if (sal->pc == 0 && sal->symtab != NULL)
9441     {
9442       if (!find_line_pc (sal->symtab, sal->line, &pc))
9443         error (_("No line %d in file \"%s\"."),
9444                sal->line, symtab_to_filename_for_display (sal->symtab));
9445       sal->pc = pc;
9446
9447       /* If this SAL corresponds to a breakpoint inserted using a line
9448          number, then skip the function prologue if necessary.  */
9449       if (sal->explicit_line)
9450         skip_prologue_sal (sal);
9451     }
9452
9453   if (sal->section == 0 && sal->symtab != NULL)
9454     {
9455       const struct blockvector *bv;
9456       const struct block *b;
9457       struct symbol *sym;
9458
9459       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9460                                     SYMTAB_COMPUNIT (sal->symtab));
9461       if (bv != NULL)
9462         {
9463           sym = block_linkage_function (b);
9464           if (sym != NULL)
9465             {
9466               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9467               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9468                                                  sym);
9469             }
9470           else
9471             {
9472               /* It really is worthwhile to have the section, so we'll
9473                  just have to look harder. This case can be executed
9474                  if we have line numbers but no functions (as can
9475                  happen in assembly source).  */
9476
9477               scoped_restore_current_pspace_and_thread restore_pspace_thread;
9478               switch_to_program_space_and_thread (sal->pspace);
9479
9480               bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9481               if (msym.minsym)
9482                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9483             }
9484         }
9485     }
9486 }
9487
9488 void
9489 break_command (const char *arg, int from_tty)
9490 {
9491   break_command_1 (arg, 0, from_tty);
9492 }
9493
9494 void
9495 tbreak_command (const char *arg, int from_tty)
9496 {
9497   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9498 }
9499
9500 static void
9501 hbreak_command (const char *arg, int from_tty)
9502 {
9503   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9504 }
9505
9506 static void
9507 thbreak_command (const char *arg, int from_tty)
9508 {
9509   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9510 }
9511
9512 static void
9513 stop_command (const char *arg, int from_tty)
9514 {
9515   printf_filtered (_("Specify the type of breakpoint to set.\n\
9516 Usage: stop in <function | address>\n\
9517        stop at <line>\n"));
9518 }
9519
9520 static void
9521 stopin_command (const char *arg, int from_tty)
9522 {
9523   int badInput = 0;
9524
9525   if (arg == (char *) NULL)
9526     badInput = 1;
9527   else if (*arg != '*')
9528     {
9529       const char *argptr = arg;
9530       int hasColon = 0;
9531
9532       /* Look for a ':'.  If this is a line number specification, then
9533          say it is bad, otherwise, it should be an address or
9534          function/method name.  */
9535       while (*argptr && !hasColon)
9536         {
9537           hasColon = (*argptr == ':');
9538           argptr++;
9539         }
9540
9541       if (hasColon)
9542         badInput = (*argptr != ':');    /* Not a class::method */
9543       else
9544         badInput = isdigit (*arg);      /* a simple line number */
9545     }
9546
9547   if (badInput)
9548     printf_filtered (_("Usage: stop in <function | address>\n"));
9549   else
9550     break_command_1 (arg, 0, from_tty);
9551 }
9552
9553 static void
9554 stopat_command (const char *arg, int from_tty)
9555 {
9556   int badInput = 0;
9557
9558   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9559     badInput = 1;
9560   else
9561     {
9562       const char *argptr = arg;
9563       int hasColon = 0;
9564
9565       /* Look for a ':'.  If there is a '::' then get out, otherwise
9566          it is probably a line number.  */
9567       while (*argptr && !hasColon)
9568         {
9569           hasColon = (*argptr == ':');
9570           argptr++;
9571         }
9572
9573       if (hasColon)
9574         badInput = (*argptr == ':');    /* we have class::method */
9575       else
9576         badInput = !isdigit (*arg);     /* not a line number */
9577     }
9578
9579   if (badInput)
9580     printf_filtered (_("Usage: stop at LINE\n"));
9581   else
9582     break_command_1 (arg, 0, from_tty);
9583 }
9584
9585 /* The dynamic printf command is mostly like a regular breakpoint, but
9586    with a prewired command list consisting of a single output command,
9587    built from extra arguments supplied on the dprintf command
9588    line.  */
9589
9590 static void
9591 dprintf_command (const char *arg, int from_tty)
9592 {
9593   event_location_up location = string_to_event_location (&arg, current_language);
9594
9595   /* If non-NULL, ARG should have been advanced past the location;
9596      the next character must be ','.  */
9597   if (arg != NULL)
9598     {
9599       if (arg[0] != ',' || arg[1] == '\0')
9600         error (_("Format string required"));
9601       else
9602         {
9603           /* Skip the comma.  */
9604           ++arg;
9605         }
9606     }
9607
9608   create_breakpoint (get_current_arch (),
9609                      location.get (),
9610                      NULL, 0, arg, 1 /* parse arg */,
9611                      0, bp_dprintf,
9612                      0 /* Ignore count */,
9613                      pending_break_support,
9614                      &dprintf_breakpoint_ops,
9615                      from_tty,
9616                      1 /* enabled */,
9617                      0 /* internal */,
9618                      0);
9619 }
9620
9621 static void
9622 agent_printf_command (const char *arg, int from_tty)
9623 {
9624   error (_("May only run agent-printf on the target"));
9625 }
9626
9627 /* Implement the "breakpoint_hit" breakpoint_ops method for
9628    ranged breakpoints.  */
9629
9630 static int
9631 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9632                                   const address_space *aspace,
9633                                   CORE_ADDR bp_addr,
9634                                   const struct target_waitstatus *ws)
9635 {
9636   if (ws->kind != TARGET_WAITKIND_STOPPED
9637       || ws->value.sig != GDB_SIGNAL_TRAP)
9638     return 0;
9639
9640   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9641                                          bl->length, aspace, bp_addr);
9642 }
9643
9644 /* Implement the "resources_needed" breakpoint_ops method for
9645    ranged breakpoints.  */
9646
9647 static int
9648 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9649 {
9650   return target_ranged_break_num_registers ();
9651 }
9652
9653 /* Implement the "print_it" breakpoint_ops method for
9654    ranged breakpoints.  */
9655
9656 static enum print_stop_action
9657 print_it_ranged_breakpoint (bpstat bs)
9658 {
9659   struct breakpoint *b = bs->breakpoint_at;
9660   struct bp_location *bl = b->loc;
9661   struct ui_out *uiout = current_uiout;
9662
9663   gdb_assert (b->type == bp_hardware_breakpoint);
9664
9665   /* Ranged breakpoints have only one location.  */
9666   gdb_assert (bl && bl->next == NULL);
9667
9668   annotate_breakpoint (b->number);
9669
9670   maybe_print_thread_hit_breakpoint (uiout);
9671
9672   if (b->disposition == disp_del)
9673     uiout->text ("Temporary ranged breakpoint ");
9674   else
9675     uiout->text ("Ranged breakpoint ");
9676   if (uiout->is_mi_like_p ())
9677     {
9678       uiout->field_string ("reason",
9679                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9680       uiout->field_string ("disp", bpdisp_text (b->disposition));
9681     }
9682   uiout->field_int ("bkptno", b->number);
9683   uiout->text (", ");
9684
9685   return PRINT_SRC_AND_LOC;
9686 }
9687
9688 /* Implement the "print_one" breakpoint_ops method for
9689    ranged breakpoints.  */
9690
9691 static void
9692 print_one_ranged_breakpoint (struct breakpoint *b,
9693                              struct bp_location **last_loc)
9694 {
9695   struct bp_location *bl = b->loc;
9696   struct value_print_options opts;
9697   struct ui_out *uiout = current_uiout;
9698
9699   /* Ranged breakpoints have only one location.  */
9700   gdb_assert (bl && bl->next == NULL);
9701
9702   get_user_print_options (&opts);
9703
9704   if (opts.addressprint)
9705     /* We don't print the address range here, it will be printed later
9706        by print_one_detail_ranged_breakpoint.  */
9707     uiout->field_skip ("addr");
9708   annotate_field (5);
9709   print_breakpoint_location (b, bl);
9710   *last_loc = bl;
9711 }
9712
9713 /* Implement the "print_one_detail" breakpoint_ops method for
9714    ranged breakpoints.  */
9715
9716 static void
9717 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9718                                     struct ui_out *uiout)
9719 {
9720   CORE_ADDR address_start, address_end;
9721   struct bp_location *bl = b->loc;
9722   string_file stb;
9723
9724   gdb_assert (bl);
9725
9726   address_start = bl->address;
9727   address_end = address_start + bl->length - 1;
9728
9729   uiout->text ("\taddress range: ");
9730   stb.printf ("[%s, %s]",
9731               print_core_address (bl->gdbarch, address_start),
9732               print_core_address (bl->gdbarch, address_end));
9733   uiout->field_stream ("addr", stb);
9734   uiout->text ("\n");
9735 }
9736
9737 /* Implement the "print_mention" breakpoint_ops method for
9738    ranged breakpoints.  */
9739
9740 static void
9741 print_mention_ranged_breakpoint (struct breakpoint *b)
9742 {
9743   struct bp_location *bl = b->loc;
9744   struct ui_out *uiout = current_uiout;
9745
9746   gdb_assert (bl);
9747   gdb_assert (b->type == bp_hardware_breakpoint);
9748
9749   uiout->message (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9750                   b->number, paddress (bl->gdbarch, bl->address),
9751                   paddress (bl->gdbarch, bl->address + bl->length - 1));
9752 }
9753
9754 /* Implement the "print_recreate" breakpoint_ops method for
9755    ranged breakpoints.  */
9756
9757 static void
9758 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9759 {
9760   fprintf_unfiltered (fp, "break-range %s, %s",
9761                       event_location_to_string (b->location.get ()),
9762                       event_location_to_string (b->location_range_end.get ()));
9763   print_recreate_thread (b, fp);
9764 }
9765
9766 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9767
9768 static struct breakpoint_ops ranged_breakpoint_ops;
9769
9770 /* Find the address where the end of the breakpoint range should be
9771    placed, given the SAL of the end of the range.  This is so that if
9772    the user provides a line number, the end of the range is set to the
9773    last instruction of the given line.  */
9774
9775 static CORE_ADDR
9776 find_breakpoint_range_end (struct symtab_and_line sal)
9777 {
9778   CORE_ADDR end;
9779
9780   /* If the user provided a PC value, use it.  Otherwise,
9781      find the address of the end of the given location.  */
9782   if (sal.explicit_pc)
9783     end = sal.pc;
9784   else
9785     {
9786       int ret;
9787       CORE_ADDR start;
9788
9789       ret = find_line_pc_range (sal, &start, &end);
9790       if (!ret)
9791         error (_("Could not find location of the end of the range."));
9792
9793       /* find_line_pc_range returns the start of the next line.  */
9794       end--;
9795     }
9796
9797   return end;
9798 }
9799
9800 /* Implement the "break-range" CLI command.  */
9801
9802 static void
9803 break_range_command (const char *arg, int from_tty)
9804 {
9805   const char *arg_start;
9806   struct linespec_result canonical_start, canonical_end;
9807   int bp_count, can_use_bp, length;
9808   CORE_ADDR end;
9809   struct breakpoint *b;
9810
9811   /* We don't support software ranged breakpoints.  */
9812   if (target_ranged_break_num_registers () < 0)
9813     error (_("This target does not support hardware ranged breakpoints."));
9814
9815   bp_count = hw_breakpoint_used_count ();
9816   bp_count += target_ranged_break_num_registers ();
9817   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9818                                                    bp_count, 0);
9819   if (can_use_bp < 0)
9820     error (_("Hardware breakpoints used exceeds limit."));
9821
9822   arg = skip_spaces (arg);
9823   if (arg == NULL || arg[0] == '\0')
9824     error(_("No address range specified."));
9825
9826   arg_start = arg;
9827   event_location_up start_location = string_to_event_location (&arg,
9828                                                                current_language);
9829   parse_breakpoint_sals (start_location.get (), &canonical_start);
9830
9831   if (arg[0] != ',')
9832     error (_("Too few arguments."));
9833   else if (canonical_start.lsals.empty ())
9834     error (_("Could not find location of the beginning of the range."));
9835
9836   const linespec_sals &lsal_start = canonical_start.lsals[0];
9837
9838   if (canonical_start.lsals.size () > 1
9839       || lsal_start.sals.size () != 1)
9840     error (_("Cannot create a ranged breakpoint with multiple locations."));
9841
9842   const symtab_and_line &sal_start = lsal_start.sals[0];
9843   std::string addr_string_start (arg_start, arg - arg_start);
9844
9845   arg++;        /* Skip the comma.  */
9846   arg = skip_spaces (arg);
9847
9848   /* Parse the end location.  */
9849
9850   arg_start = arg;
9851
9852   /* We call decode_line_full directly here instead of using
9853      parse_breakpoint_sals because we need to specify the start location's
9854      symtab and line as the default symtab and line for the end of the
9855      range.  This makes it possible to have ranges like "foo.c:27, +14",
9856      where +14 means 14 lines from the start location.  */
9857   event_location_up end_location = string_to_event_location (&arg,
9858                                                              current_language);
9859   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
9860                     sal_start.symtab, sal_start.line,
9861                     &canonical_end, NULL, NULL);
9862
9863   if (canonical_end.lsals.empty ())
9864     error (_("Could not find location of the end of the range."));
9865
9866   const linespec_sals &lsal_end = canonical_end.lsals[0];
9867   if (canonical_end.lsals.size () > 1
9868       || lsal_end.sals.size () != 1)
9869     error (_("Cannot create a ranged breakpoint with multiple locations."));
9870
9871   const symtab_and_line &sal_end = lsal_end.sals[0];
9872
9873   end = find_breakpoint_range_end (sal_end);
9874   if (sal_start.pc > end)
9875     error (_("Invalid address range, end precedes start."));
9876
9877   length = end - sal_start.pc + 1;
9878   if (length < 0)
9879     /* Length overflowed.  */
9880     error (_("Address range too large."));
9881   else if (length == 1)
9882     {
9883       /* This range is simple enough to be handled by
9884          the `hbreak' command.  */
9885       hbreak_command (&addr_string_start[0], 1);
9886
9887       return;
9888     }
9889
9890   /* Now set up the breakpoint.  */
9891   b = set_raw_breakpoint (get_current_arch (), sal_start,
9892                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
9893   set_breakpoint_count (breakpoint_count + 1);
9894   b->number = breakpoint_count;
9895   b->disposition = disp_donttouch;
9896   b->location = std::move (start_location);
9897   b->location_range_end = std::move (end_location);
9898   b->loc->length = length;
9899
9900   mention (b);
9901   gdb::observers::breakpoint_created.notify (b);
9902   update_global_location_list (UGLL_MAY_INSERT);
9903 }
9904
9905 /*  Return non-zero if EXP is verified as constant.  Returned zero
9906     means EXP is variable.  Also the constant detection may fail for
9907     some constant expressions and in such case still falsely return
9908     zero.  */
9909
9910 static int
9911 watchpoint_exp_is_const (const struct expression *exp)
9912 {
9913   int i = exp->nelts;
9914
9915   while (i > 0)
9916     {
9917       int oplenp, argsp;
9918
9919       /* We are only interested in the descriptor of each element.  */
9920       operator_length (exp, i, &oplenp, &argsp);
9921       i -= oplenp;
9922
9923       switch (exp->elts[i].opcode)
9924         {
9925         case BINOP_ADD:
9926         case BINOP_SUB:
9927         case BINOP_MUL:
9928         case BINOP_DIV:
9929         case BINOP_REM:
9930         case BINOP_MOD:
9931         case BINOP_LSH:
9932         case BINOP_RSH:
9933         case BINOP_LOGICAL_AND:
9934         case BINOP_LOGICAL_OR:
9935         case BINOP_BITWISE_AND:
9936         case BINOP_BITWISE_IOR:
9937         case BINOP_BITWISE_XOR:
9938         case BINOP_EQUAL:
9939         case BINOP_NOTEQUAL:
9940         case BINOP_LESS:
9941         case BINOP_GTR:
9942         case BINOP_LEQ:
9943         case BINOP_GEQ:
9944         case BINOP_REPEAT:
9945         case BINOP_COMMA:
9946         case BINOP_EXP:
9947         case BINOP_MIN:
9948         case BINOP_MAX:
9949         case BINOP_INTDIV:
9950         case BINOP_CONCAT:
9951         case TERNOP_COND:
9952         case TERNOP_SLICE:
9953
9954         case OP_LONG:
9955         case OP_FLOAT:
9956         case OP_LAST:
9957         case OP_COMPLEX:
9958         case OP_STRING:
9959         case OP_ARRAY:
9960         case OP_TYPE:
9961         case OP_TYPEOF:
9962         case OP_DECLTYPE:
9963         case OP_TYPEID:
9964         case OP_NAME:
9965         case OP_OBJC_NSSTRING:
9966
9967         case UNOP_NEG:
9968         case UNOP_LOGICAL_NOT:
9969         case UNOP_COMPLEMENT:
9970         case UNOP_ADDR:
9971         case UNOP_HIGH:
9972         case UNOP_CAST:
9973
9974         case UNOP_CAST_TYPE:
9975         case UNOP_REINTERPRET_CAST:
9976         case UNOP_DYNAMIC_CAST:
9977           /* Unary, binary and ternary operators: We have to check
9978              their operands.  If they are constant, then so is the
9979              result of that operation.  For instance, if A and B are
9980              determined to be constants, then so is "A + B".
9981
9982              UNOP_IND is one exception to the rule above, because the
9983              value of *ADDR is not necessarily a constant, even when
9984              ADDR is.  */
9985           break;
9986
9987         case OP_VAR_VALUE:
9988           /* Check whether the associated symbol is a constant.
9989
9990              We use SYMBOL_CLASS rather than TYPE_CONST because it's
9991              possible that a buggy compiler could mark a variable as
9992              constant even when it is not, and TYPE_CONST would return
9993              true in this case, while SYMBOL_CLASS wouldn't.
9994
9995              We also have to check for function symbols because they
9996              are always constant.  */
9997           {
9998             struct symbol *s = exp->elts[i + 2].symbol;
9999
10000             if (SYMBOL_CLASS (s) != LOC_BLOCK
10001                 && SYMBOL_CLASS (s) != LOC_CONST
10002                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10003               return 0;
10004             break;
10005           }
10006
10007         /* The default action is to return 0 because we are using
10008            the optimistic approach here: If we don't know something,
10009            then it is not a constant.  */
10010         default:
10011           return 0;
10012         }
10013     }
10014
10015   return 1;
10016 }
10017
10018 /* Watchpoint destructor.  */
10019
10020 watchpoint::~watchpoint ()
10021 {
10022   xfree (this->exp_string);
10023   xfree (this->exp_string_reparse);
10024 }
10025
10026 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10027
10028 static void
10029 re_set_watchpoint (struct breakpoint *b)
10030 {
10031   struct watchpoint *w = (struct watchpoint *) b;
10032
10033   /* Watchpoint can be either on expression using entirely global
10034      variables, or it can be on local variables.
10035
10036      Watchpoints of the first kind are never auto-deleted, and even
10037      persist across program restarts.  Since they can use variables
10038      from shared libraries, we need to reparse expression as libraries
10039      are loaded and unloaded.
10040
10041      Watchpoints on local variables can also change meaning as result
10042      of solib event.  For example, if a watchpoint uses both a local
10043      and a global variables in expression, it's a local watchpoint,
10044      but unloading of a shared library will make the expression
10045      invalid.  This is not a very common use case, but we still
10046      re-evaluate expression, to avoid surprises to the user.
10047
10048      Note that for local watchpoints, we re-evaluate it only if
10049      watchpoints frame id is still valid.  If it's not, it means the
10050      watchpoint is out of scope and will be deleted soon.  In fact,
10051      I'm not sure we'll ever be called in this case.
10052
10053      If a local watchpoint's frame id is still valid, then
10054      w->exp_valid_block is likewise valid, and we can safely use it.
10055
10056      Don't do anything about disabled watchpoints, since they will be
10057      reevaluated again when enabled.  */
10058   update_watchpoint (w, 1 /* reparse */);
10059 }
10060
10061 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10062
10063 static int
10064 insert_watchpoint (struct bp_location *bl)
10065 {
10066   struct watchpoint *w = (struct watchpoint *) bl->owner;
10067   int length = w->exact ? 1 : bl->length;
10068
10069   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10070                                    w->cond_exp.get ());
10071 }
10072
10073 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10074
10075 static int
10076 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10077 {
10078   struct watchpoint *w = (struct watchpoint *) bl->owner;
10079   int length = w->exact ? 1 : bl->length;
10080
10081   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10082                                    w->cond_exp.get ());
10083 }
10084
10085 static int
10086 breakpoint_hit_watchpoint (const struct bp_location *bl,
10087                            const address_space *aspace, CORE_ADDR bp_addr,
10088                            const struct target_waitstatus *ws)
10089 {
10090   struct breakpoint *b = bl->owner;
10091   struct watchpoint *w = (struct watchpoint *) b;
10092
10093   /* Continuable hardware watchpoints are treated as non-existent if the
10094      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10095      some data address).  Otherwise gdb won't stop on a break instruction
10096      in the code (not from a breakpoint) when a hardware watchpoint has
10097      been defined.  Also skip watchpoints which we know did not trigger
10098      (did not match the data address).  */
10099   if (is_hardware_watchpoint (b)
10100       && w->watchpoint_triggered == watch_triggered_no)
10101     return 0;
10102
10103   return 1;
10104 }
10105
10106 static void
10107 check_status_watchpoint (bpstat bs)
10108 {
10109   gdb_assert (is_watchpoint (bs->breakpoint_at));
10110
10111   bpstat_check_watchpoint (bs);
10112 }
10113
10114 /* Implement the "resources_needed" breakpoint_ops method for
10115    hardware watchpoints.  */
10116
10117 static int
10118 resources_needed_watchpoint (const struct bp_location *bl)
10119 {
10120   struct watchpoint *w = (struct watchpoint *) bl->owner;
10121   int length = w->exact? 1 : bl->length;
10122
10123   return target_region_ok_for_hw_watchpoint (bl->address, length);
10124 }
10125
10126 /* Implement the "works_in_software_mode" breakpoint_ops method for
10127    hardware watchpoints.  */
10128
10129 static int
10130 works_in_software_mode_watchpoint (const struct breakpoint *b)
10131 {
10132   /* Read and access watchpoints only work with hardware support.  */
10133   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10134 }
10135
10136 static enum print_stop_action
10137 print_it_watchpoint (bpstat bs)
10138 {
10139   struct breakpoint *b;
10140   enum print_stop_action result;
10141   struct watchpoint *w;
10142   struct ui_out *uiout = current_uiout;
10143
10144   gdb_assert (bs->bp_location_at != NULL);
10145
10146   b = bs->breakpoint_at;
10147   w = (struct watchpoint *) b;
10148
10149   annotate_watchpoint (b->number);
10150   maybe_print_thread_hit_breakpoint (uiout);
10151
10152   string_file stb;
10153
10154   gdb::optional<ui_out_emit_tuple> tuple_emitter;
10155   switch (b->type)
10156     {
10157     case bp_watchpoint:
10158     case bp_hardware_watchpoint:
10159       if (uiout->is_mi_like_p ())
10160         uiout->field_string
10161           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10162       mention (b);
10163       tuple_emitter.emplace (uiout, "value");
10164       uiout->text ("\nOld value = ");
10165       watchpoint_value_print (bs->old_val.get (), &stb);
10166       uiout->field_stream ("old", stb);
10167       uiout->text ("\nNew value = ");
10168       watchpoint_value_print (w->val.get (), &stb);
10169       uiout->field_stream ("new", stb);
10170       uiout->text ("\n");
10171       /* More than one watchpoint may have been triggered.  */
10172       result = PRINT_UNKNOWN;
10173       break;
10174
10175     case bp_read_watchpoint:
10176       if (uiout->is_mi_like_p ())
10177         uiout->field_string
10178           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10179       mention (b);
10180       tuple_emitter.emplace (uiout, "value");
10181       uiout->text ("\nValue = ");
10182       watchpoint_value_print (w->val.get (), &stb);
10183       uiout->field_stream ("value", stb);
10184       uiout->text ("\n");
10185       result = PRINT_UNKNOWN;
10186       break;
10187
10188     case bp_access_watchpoint:
10189       if (bs->old_val != NULL)
10190         {
10191           if (uiout->is_mi_like_p ())
10192             uiout->field_string
10193               ("reason",
10194                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10195           mention (b);
10196           tuple_emitter.emplace (uiout, "value");
10197           uiout->text ("\nOld value = ");
10198           watchpoint_value_print (bs->old_val.get (), &stb);
10199           uiout->field_stream ("old", stb);
10200           uiout->text ("\nNew value = ");
10201         }
10202       else
10203         {
10204           mention (b);
10205           if (uiout->is_mi_like_p ())
10206             uiout->field_string
10207               ("reason",
10208                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10209           tuple_emitter.emplace (uiout, "value");
10210           uiout->text ("\nValue = ");
10211         }
10212       watchpoint_value_print (w->val.get (), &stb);
10213       uiout->field_stream ("new", stb);
10214       uiout->text ("\n");
10215       result = PRINT_UNKNOWN;
10216       break;
10217     default:
10218       result = PRINT_UNKNOWN;
10219     }
10220
10221   return result;
10222 }
10223
10224 /* Implement the "print_mention" breakpoint_ops method for hardware
10225    watchpoints.  */
10226
10227 static void
10228 print_mention_watchpoint (struct breakpoint *b)
10229 {
10230   struct watchpoint *w = (struct watchpoint *) b;
10231   struct ui_out *uiout = current_uiout;
10232   const char *tuple_name;
10233
10234   switch (b->type)
10235     {
10236     case bp_watchpoint:
10237       uiout->text ("Watchpoint ");
10238       tuple_name = "wpt";
10239       break;
10240     case bp_hardware_watchpoint:
10241       uiout->text ("Hardware watchpoint ");
10242       tuple_name = "wpt";
10243       break;
10244     case bp_read_watchpoint:
10245       uiout->text ("Hardware read watchpoint ");
10246       tuple_name = "hw-rwpt";
10247       break;
10248     case bp_access_watchpoint:
10249       uiout->text ("Hardware access (read/write) watchpoint ");
10250       tuple_name = "hw-awpt";
10251       break;
10252     default:
10253       internal_error (__FILE__, __LINE__,
10254                       _("Invalid hardware watchpoint type."));
10255     }
10256
10257   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10258   uiout->field_int ("number", b->number);
10259   uiout->text (": ");
10260   uiout->field_string ("exp", w->exp_string);
10261 }
10262
10263 /* Implement the "print_recreate" breakpoint_ops method for
10264    watchpoints.  */
10265
10266 static void
10267 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10268 {
10269   struct watchpoint *w = (struct watchpoint *) b;
10270
10271   switch (b->type)
10272     {
10273     case bp_watchpoint:
10274     case bp_hardware_watchpoint:
10275       fprintf_unfiltered (fp, "watch");
10276       break;
10277     case bp_read_watchpoint:
10278       fprintf_unfiltered (fp, "rwatch");
10279       break;
10280     case bp_access_watchpoint:
10281       fprintf_unfiltered (fp, "awatch");
10282       break;
10283     default:
10284       internal_error (__FILE__, __LINE__,
10285                       _("Invalid watchpoint type."));
10286     }
10287
10288   fprintf_unfiltered (fp, " %s", w->exp_string);
10289   print_recreate_thread (b, fp);
10290 }
10291
10292 /* Implement the "explains_signal" breakpoint_ops method for
10293    watchpoints.  */
10294
10295 static int
10296 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10297 {
10298   /* A software watchpoint cannot cause a signal other than
10299      GDB_SIGNAL_TRAP.  */
10300   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10301     return 0;
10302
10303   return 1;
10304 }
10305
10306 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10307
10308 static struct breakpoint_ops watchpoint_breakpoint_ops;
10309
10310 /* Implement the "insert" breakpoint_ops method for
10311    masked hardware watchpoints.  */
10312
10313 static int
10314 insert_masked_watchpoint (struct bp_location *bl)
10315 {
10316   struct watchpoint *w = (struct watchpoint *) bl->owner;
10317
10318   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10319                                         bl->watchpoint_type);
10320 }
10321
10322 /* Implement the "remove" breakpoint_ops method for
10323    masked hardware watchpoints.  */
10324
10325 static int
10326 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10327 {
10328   struct watchpoint *w = (struct watchpoint *) bl->owner;
10329
10330   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10331                                         bl->watchpoint_type);
10332 }
10333
10334 /* Implement the "resources_needed" breakpoint_ops method for
10335    masked hardware watchpoints.  */
10336
10337 static int
10338 resources_needed_masked_watchpoint (const struct bp_location *bl)
10339 {
10340   struct watchpoint *w = (struct watchpoint *) bl->owner;
10341
10342   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10343 }
10344
10345 /* Implement the "works_in_software_mode" breakpoint_ops method for
10346    masked hardware watchpoints.  */
10347
10348 static int
10349 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10350 {
10351   return 0;
10352 }
10353
10354 /* Implement the "print_it" breakpoint_ops method for
10355    masked hardware watchpoints.  */
10356
10357 static enum print_stop_action
10358 print_it_masked_watchpoint (bpstat bs)
10359 {
10360   struct breakpoint *b = bs->breakpoint_at;
10361   struct ui_out *uiout = current_uiout;
10362
10363   /* Masked watchpoints have only one location.  */
10364   gdb_assert (b->loc && b->loc->next == NULL);
10365
10366   annotate_watchpoint (b->number);
10367   maybe_print_thread_hit_breakpoint (uiout);
10368
10369   switch (b->type)
10370     {
10371     case bp_hardware_watchpoint:
10372       if (uiout->is_mi_like_p ())
10373         uiout->field_string
10374           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10375       break;
10376
10377     case bp_read_watchpoint:
10378       if (uiout->is_mi_like_p ())
10379         uiout->field_string
10380           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10381       break;
10382
10383     case bp_access_watchpoint:
10384       if (uiout->is_mi_like_p ())
10385         uiout->field_string
10386           ("reason",
10387            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10388       break;
10389     default:
10390       internal_error (__FILE__, __LINE__,
10391                       _("Invalid hardware watchpoint type."));
10392     }
10393
10394   mention (b);
10395   uiout->text (_("\n\
10396 Check the underlying instruction at PC for the memory\n\
10397 address and value which triggered this watchpoint.\n"));
10398   uiout->text ("\n");
10399
10400   /* More than one watchpoint may have been triggered.  */
10401   return PRINT_UNKNOWN;
10402 }
10403
10404 /* Implement the "print_one_detail" breakpoint_ops method for
10405    masked hardware watchpoints.  */
10406
10407 static void
10408 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10409                                     struct ui_out *uiout)
10410 {
10411   struct watchpoint *w = (struct watchpoint *) b;
10412
10413   /* Masked watchpoints have only one location.  */
10414   gdb_assert (b->loc && b->loc->next == NULL);
10415
10416   uiout->text ("\tmask ");
10417   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10418   uiout->text ("\n");
10419 }
10420
10421 /* Implement the "print_mention" breakpoint_ops method for
10422    masked hardware watchpoints.  */
10423
10424 static void
10425 print_mention_masked_watchpoint (struct breakpoint *b)
10426 {
10427   struct watchpoint *w = (struct watchpoint *) b;
10428   struct ui_out *uiout = current_uiout;
10429   const char *tuple_name;
10430
10431   switch (b->type)
10432     {
10433     case bp_hardware_watchpoint:
10434       uiout->text ("Masked hardware watchpoint ");
10435       tuple_name = "wpt";
10436       break;
10437     case bp_read_watchpoint:
10438       uiout->text ("Masked hardware read watchpoint ");
10439       tuple_name = "hw-rwpt";
10440       break;
10441     case bp_access_watchpoint:
10442       uiout->text ("Masked hardware access (read/write) watchpoint ");
10443       tuple_name = "hw-awpt";
10444       break;
10445     default:
10446       internal_error (__FILE__, __LINE__,
10447                       _("Invalid hardware watchpoint type."));
10448     }
10449
10450   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10451   uiout->field_int ("number", b->number);
10452   uiout->text (": ");
10453   uiout->field_string ("exp", w->exp_string);
10454 }
10455
10456 /* Implement the "print_recreate" breakpoint_ops method for
10457    masked hardware watchpoints.  */
10458
10459 static void
10460 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10461 {
10462   struct watchpoint *w = (struct watchpoint *) b;
10463   char tmp[40];
10464
10465   switch (b->type)
10466     {
10467     case bp_hardware_watchpoint:
10468       fprintf_unfiltered (fp, "watch");
10469       break;
10470     case bp_read_watchpoint:
10471       fprintf_unfiltered (fp, "rwatch");
10472       break;
10473     case bp_access_watchpoint:
10474       fprintf_unfiltered (fp, "awatch");
10475       break;
10476     default:
10477       internal_error (__FILE__, __LINE__,
10478                       _("Invalid hardware watchpoint type."));
10479     }
10480
10481   sprintf_vma (tmp, w->hw_wp_mask);
10482   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10483   print_recreate_thread (b, fp);
10484 }
10485
10486 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10487
10488 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10489
10490 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10491
10492 static int
10493 is_masked_watchpoint (const struct breakpoint *b)
10494 {
10495   return b->ops == &masked_watchpoint_breakpoint_ops;
10496 }
10497
10498 /* accessflag:  hw_write:  watch write, 
10499                 hw_read:   watch read, 
10500                 hw_access: watch access (read or write) */
10501 static void
10502 watch_command_1 (const char *arg, int accessflag, int from_tty,
10503                  int just_location, int internal)
10504 {
10505   struct breakpoint *scope_breakpoint = NULL;
10506   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10507   struct value *result;
10508   int saved_bitpos = 0, saved_bitsize = 0;
10509   const char *exp_start = NULL;
10510   const char *exp_end = NULL;
10511   const char *tok, *end_tok;
10512   int toklen = -1;
10513   const char *cond_start = NULL;
10514   const char *cond_end = NULL;
10515   enum bptype bp_type;
10516   int thread = -1;
10517   int pc = 0;
10518   /* Flag to indicate whether we are going to use masks for
10519      the hardware watchpoint.  */
10520   int use_mask = 0;
10521   CORE_ADDR mask = 0;
10522
10523   /* Make sure that we actually have parameters to parse.  */
10524   if (arg != NULL && arg[0] != '\0')
10525     {
10526       const char *value_start;
10527
10528       exp_end = arg + strlen (arg);
10529
10530       /* Look for "parameter value" pairs at the end
10531          of the arguments string.  */
10532       for (tok = exp_end - 1; tok > arg; tok--)
10533         {
10534           /* Skip whitespace at the end of the argument list.  */
10535           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10536             tok--;
10537
10538           /* Find the beginning of the last token.
10539              This is the value of the parameter.  */
10540           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10541             tok--;
10542           value_start = tok + 1;
10543
10544           /* Skip whitespace.  */
10545           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10546             tok--;
10547
10548           end_tok = tok;
10549
10550           /* Find the beginning of the second to last token.
10551              This is the parameter itself.  */
10552           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10553             tok--;
10554           tok++;
10555           toklen = end_tok - tok + 1;
10556
10557           if (toklen == 6 && startswith (tok, "thread"))
10558             {
10559               struct thread_info *thr;
10560               /* At this point we've found a "thread" token, which means
10561                  the user is trying to set a watchpoint that triggers
10562                  only in a specific thread.  */
10563               const char *endp;
10564
10565               if (thread != -1)
10566                 error(_("You can specify only one thread."));
10567
10568               /* Extract the thread ID from the next token.  */
10569               thr = parse_thread_id (value_start, &endp);
10570
10571               /* Check if the user provided a valid thread ID.  */
10572               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10573                 invalid_thread_id_error (value_start);
10574
10575               thread = thr->global_num;
10576             }
10577           else if (toklen == 4 && startswith (tok, "mask"))
10578             {
10579               /* We've found a "mask" token, which means the user wants to
10580                  create a hardware watchpoint that is going to have the mask
10581                  facility.  */
10582               struct value *mask_value, *mark;
10583
10584               if (use_mask)
10585                 error(_("You can specify only one mask."));
10586
10587               use_mask = just_location = 1;
10588
10589               mark = value_mark ();
10590               mask_value = parse_to_comma_and_eval (&value_start);
10591               mask = value_as_address (mask_value);
10592               value_free_to_mark (mark);
10593             }
10594           else
10595             /* We didn't recognize what we found.  We should stop here.  */
10596             break;
10597
10598           /* Truncate the string and get rid of the "parameter value" pair before
10599              the arguments string is parsed by the parse_exp_1 function.  */
10600           exp_end = tok;
10601         }
10602     }
10603   else
10604     exp_end = arg;
10605
10606   /* Parse the rest of the arguments.  From here on out, everything
10607      is in terms of a newly allocated string instead of the original
10608      ARG.  */
10609   std::string expression (arg, exp_end - arg);
10610   exp_start = arg = expression.c_str ();
10611   innermost_block_tracker tracker;
10612   expression_up exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
10613   exp_end = arg;
10614   /* Remove trailing whitespace from the expression before saving it.
10615      This makes the eventual display of the expression string a bit
10616      prettier.  */
10617   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10618     --exp_end;
10619
10620   /* Checking if the expression is not constant.  */
10621   if (watchpoint_exp_is_const (exp.get ()))
10622     {
10623       int len;
10624
10625       len = exp_end - exp_start;
10626       while (len > 0 && isspace (exp_start[len - 1]))
10627         len--;
10628       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10629     }
10630
10631   exp_valid_block = tracker.block ();
10632   struct value *mark = value_mark ();
10633   struct value *val_as_value = nullptr;
10634   fetch_subexp_value (exp.get (), &pc, &val_as_value, &result, NULL,
10635                       just_location);
10636
10637   if (val_as_value != NULL && just_location)
10638     {
10639       saved_bitpos = value_bitpos (val_as_value);
10640       saved_bitsize = value_bitsize (val_as_value);
10641     }
10642
10643   value_ref_ptr val;
10644   if (just_location)
10645     {
10646       int ret;
10647
10648       exp_valid_block = NULL;
10649       val = release_value (value_addr (result));
10650       value_free_to_mark (mark);
10651
10652       if (use_mask)
10653         {
10654           ret = target_masked_watch_num_registers (value_as_address (val.get ()),
10655                                                    mask);
10656           if (ret == -1)
10657             error (_("This target does not support masked watchpoints."));
10658           else if (ret == -2)
10659             error (_("Invalid mask or memory region."));
10660         }
10661     }
10662   else if (val_as_value != NULL)
10663     val = release_value (val_as_value);
10664
10665   tok = skip_spaces (arg);
10666   end_tok = skip_to_space (tok);
10667
10668   toklen = end_tok - tok;
10669   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10670     {
10671       tok = cond_start = end_tok + 1;
10672       innermost_block_tracker if_tracker;
10673       parse_exp_1 (&tok, 0, 0, 0, &if_tracker);
10674
10675       /* The watchpoint expression may not be local, but the condition
10676          may still be.  E.g.: `watch global if local > 0'.  */
10677       cond_exp_valid_block = if_tracker.block ();
10678
10679       cond_end = tok;
10680     }
10681   if (*tok)
10682     error (_("Junk at end of command."));
10683
10684   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
10685
10686   /* Save this because create_internal_breakpoint below invalidates
10687      'wp_frame'.  */
10688   frame_id watchpoint_frame = get_frame_id (wp_frame);
10689
10690   /* If the expression is "local", then set up a "watchpoint scope"
10691      breakpoint at the point where we've left the scope of the watchpoint
10692      expression.  Create the scope breakpoint before the watchpoint, so
10693      that we will encounter it first in bpstat_stop_status.  */
10694   if (exp_valid_block != NULL && wp_frame != NULL)
10695     {
10696       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10697
10698       if (frame_id_p (caller_frame_id))
10699         {
10700           gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10701           CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10702
10703           scope_breakpoint
10704             = create_internal_breakpoint (caller_arch, caller_pc,
10705                                           bp_watchpoint_scope,
10706                                           &momentary_breakpoint_ops);
10707
10708           /* create_internal_breakpoint could invalidate WP_FRAME.  */
10709           wp_frame = NULL;
10710
10711           scope_breakpoint->enable_state = bp_enabled;
10712
10713           /* Automatically delete the breakpoint when it hits.  */
10714           scope_breakpoint->disposition = disp_del;
10715
10716           /* Only break in the proper frame (help with recursion).  */
10717           scope_breakpoint->frame_id = caller_frame_id;
10718
10719           /* Set the address at which we will stop.  */
10720           scope_breakpoint->loc->gdbarch = caller_arch;
10721           scope_breakpoint->loc->requested_address = caller_pc;
10722           scope_breakpoint->loc->address
10723             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10724                                          scope_breakpoint->loc->requested_address,
10725                                          scope_breakpoint->type);
10726         }
10727     }
10728
10729   /* Now set up the breakpoint.  We create all watchpoints as hardware
10730      watchpoints here even if hardware watchpoints are turned off, a call
10731      to update_watchpoint later in this function will cause the type to
10732      drop back to bp_watchpoint (software watchpoint) if required.  */
10733
10734   if (accessflag == hw_read)
10735     bp_type = bp_read_watchpoint;
10736   else if (accessflag == hw_access)
10737     bp_type = bp_access_watchpoint;
10738   else
10739     bp_type = bp_hardware_watchpoint;
10740
10741   std::unique_ptr<watchpoint> w (new watchpoint ());
10742
10743   if (use_mask)
10744     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10745                                           &masked_watchpoint_breakpoint_ops);
10746   else
10747     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10748                                           &watchpoint_breakpoint_ops);
10749   w->thread = thread;
10750   w->disposition = disp_donttouch;
10751   w->pspace = current_program_space;
10752   w->exp = std::move (exp);
10753   w->exp_valid_block = exp_valid_block;
10754   w->cond_exp_valid_block = cond_exp_valid_block;
10755   if (just_location)
10756     {
10757       struct type *t = value_type (val.get ());
10758       CORE_ADDR addr = value_as_address (val.get ());
10759
10760       w->exp_string_reparse
10761         = current_language->la_watch_location_expression (t, addr).release ();
10762
10763       w->exp_string = xstrprintf ("-location %.*s",
10764                                   (int) (exp_end - exp_start), exp_start);
10765     }
10766   else
10767     w->exp_string = savestring (exp_start, exp_end - exp_start);
10768
10769   if (use_mask)
10770     {
10771       w->hw_wp_mask = mask;
10772     }
10773   else
10774     {
10775       w->val = val;
10776       w->val_bitpos = saved_bitpos;
10777       w->val_bitsize = saved_bitsize;
10778       w->val_valid = 1;
10779     }
10780
10781   if (cond_start)
10782     w->cond_string = savestring (cond_start, cond_end - cond_start);
10783   else
10784     w->cond_string = 0;
10785
10786   if (frame_id_p (watchpoint_frame))
10787     {
10788       w->watchpoint_frame = watchpoint_frame;
10789       w->watchpoint_thread = inferior_ptid;
10790     }
10791   else
10792     {
10793       w->watchpoint_frame = null_frame_id;
10794       w->watchpoint_thread = null_ptid;
10795     }
10796
10797   if (scope_breakpoint != NULL)
10798     {
10799       /* The scope breakpoint is related to the watchpoint.  We will
10800          need to act on them together.  */
10801       w->related_breakpoint = scope_breakpoint;
10802       scope_breakpoint->related_breakpoint = w.get ();
10803     }
10804
10805   if (!just_location)
10806     value_free_to_mark (mark);
10807
10808   /* Finally update the new watchpoint.  This creates the locations
10809      that should be inserted.  */
10810   update_watchpoint (w.get (), 1);
10811
10812   install_breakpoint (internal, std::move (w), 1);
10813 }
10814
10815 /* Return count of debug registers needed to watch the given expression.
10816    If the watchpoint cannot be handled in hardware return zero.  */
10817
10818 static int
10819 can_use_hardware_watchpoint (const std::vector<value_ref_ptr> &vals)
10820 {
10821   int found_memory_cnt = 0;
10822
10823   /* Did the user specifically forbid us to use hardware watchpoints? */
10824   if (!can_use_hw_watchpoints)
10825     return 0;
10826
10827   gdb_assert (!vals.empty ());
10828   struct value *head = vals[0].get ();
10829
10830   /* Make sure that the value of the expression depends only upon
10831      memory contents, and values computed from them within GDB.  If we
10832      find any register references or function calls, we can't use a
10833      hardware watchpoint.
10834
10835      The idea here is that evaluating an expression generates a series
10836      of values, one holding the value of every subexpression.  (The
10837      expression a*b+c has five subexpressions: a, b, a*b, c, and
10838      a*b+c.)  GDB's values hold almost enough information to establish
10839      the criteria given above --- they identify memory lvalues,
10840      register lvalues, computed values, etcetera.  So we can evaluate
10841      the expression, and then scan the chain of values that leaves
10842      behind to decide whether we can detect any possible change to the
10843      expression's final value using only hardware watchpoints.
10844
10845      However, I don't think that the values returned by inferior
10846      function calls are special in any way.  So this function may not
10847      notice that an expression involving an inferior function call
10848      can't be watched with hardware watchpoints.  FIXME.  */
10849   for (const value_ref_ptr &iter : vals)
10850     {
10851       struct value *v = iter.get ();
10852
10853       if (VALUE_LVAL (v) == lval_memory)
10854         {
10855           if (v != head && value_lazy (v))
10856             /* A lazy memory lvalue in the chain is one that GDB never
10857                needed to fetch; we either just used its address (e.g.,
10858                `a' in `a.b') or we never needed it at all (e.g., `a'
10859                in `a,b').  This doesn't apply to HEAD; if that is
10860                lazy then it was not readable, but watch it anyway.  */
10861             ;
10862           else
10863             {
10864               /* Ahh, memory we actually used!  Check if we can cover
10865                  it with hardware watchpoints.  */
10866               struct type *vtype = check_typedef (value_type (v));
10867
10868               /* We only watch structs and arrays if user asked for it
10869                  explicitly, never if they just happen to appear in a
10870                  middle of some value chain.  */
10871               if (v == head
10872                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
10873                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
10874                 {
10875                   CORE_ADDR vaddr = value_address (v);
10876                   int len;
10877                   int num_regs;
10878
10879                   len = (target_exact_watchpoints
10880                          && is_scalar_type_recursive (vtype))?
10881                     1 : TYPE_LENGTH (value_type (v));
10882
10883                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10884                   if (!num_regs)
10885                     return 0;
10886                   else
10887                     found_memory_cnt += num_regs;
10888                 }
10889             }
10890         }
10891       else if (VALUE_LVAL (v) != not_lval
10892                && deprecated_value_modifiable (v) == 0)
10893         return 0;       /* These are values from the history (e.g., $1).  */
10894       else if (VALUE_LVAL (v) == lval_register)
10895         return 0;       /* Cannot watch a register with a HW watchpoint.  */
10896     }
10897
10898   /* The expression itself looks suitable for using a hardware
10899      watchpoint, but give the target machine a chance to reject it.  */
10900   return found_memory_cnt;
10901 }
10902
10903 void
10904 watch_command_wrapper (const char *arg, int from_tty, int internal)
10905 {
10906   watch_command_1 (arg, hw_write, from_tty, 0, internal);
10907 }
10908
10909 /* A helper function that looks for the "-location" argument and then
10910    calls watch_command_1.  */
10911
10912 static void
10913 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
10914 {
10915   int just_location = 0;
10916
10917   if (arg
10918       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
10919           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
10920     {
10921       arg = skip_spaces (arg);
10922       just_location = 1;
10923     }
10924
10925   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
10926 }
10927
10928 static void
10929 watch_command (const char *arg, int from_tty)
10930 {
10931   watch_maybe_just_location (arg, hw_write, from_tty);
10932 }
10933
10934 void
10935 rwatch_command_wrapper (const char *arg, int from_tty, int internal)
10936 {
10937   watch_command_1 (arg, hw_read, from_tty, 0, internal);
10938 }
10939
10940 static void
10941 rwatch_command (const char *arg, int from_tty)
10942 {
10943   watch_maybe_just_location (arg, hw_read, from_tty);
10944 }
10945
10946 void
10947 awatch_command_wrapper (const char *arg, int from_tty, int internal)
10948 {
10949   watch_command_1 (arg, hw_access, from_tty, 0, internal);
10950 }
10951
10952 static void
10953 awatch_command (const char *arg, int from_tty)
10954 {
10955   watch_maybe_just_location (arg, hw_access, from_tty);
10956 }
10957 \f
10958
10959 /* Data for the FSM that manages the until(location)/advance commands
10960    in infcmd.c.  Here because it uses the mechanisms of
10961    breakpoints.  */
10962
10963 struct until_break_fsm : public thread_fsm
10964 {
10965   /* The thread that was current when the command was executed.  */
10966   int thread;
10967
10968   /* The breakpoint set at the destination location.  */
10969   breakpoint_up location_breakpoint;
10970
10971   /* Breakpoint set at the return address in the caller frame.  May be
10972      NULL.  */
10973   breakpoint_up caller_breakpoint;
10974
10975   until_break_fsm (struct interp *cmd_interp, int thread,
10976                    breakpoint_up &&location_breakpoint,
10977                    breakpoint_up &&caller_breakpoint)
10978     : thread_fsm (cmd_interp),
10979       thread (thread),
10980       location_breakpoint (std::move (location_breakpoint)),
10981       caller_breakpoint (std::move (caller_breakpoint))
10982   {
10983   }
10984
10985   void clean_up (struct thread_info *thread) override;
10986   bool should_stop (struct thread_info *thread) override;
10987   enum async_reply_reason do_async_reply_reason () override;
10988 };
10989
10990 /* Implementation of the 'should_stop' FSM method for the
10991    until(location)/advance commands.  */
10992
10993 bool
10994 until_break_fsm::should_stop (struct thread_info *tp)
10995 {
10996   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
10997                               location_breakpoint.get ()) != NULL
10998       || (caller_breakpoint != NULL
10999           && bpstat_find_breakpoint (tp->control.stop_bpstat,
11000                                      caller_breakpoint.get ()) != NULL))
11001     set_finished ();
11002
11003   return true;
11004 }
11005
11006 /* Implementation of the 'clean_up' FSM method for the
11007    until(location)/advance commands.  */
11008
11009 void
11010 until_break_fsm::clean_up (struct thread_info *)
11011 {
11012   /* Clean up our temporary breakpoints.  */
11013   location_breakpoint.reset ();
11014   caller_breakpoint.reset ();
11015   delete_longjmp_breakpoint (thread);
11016 }
11017
11018 /* Implementation of the 'async_reply_reason' FSM method for the
11019    until(location)/advance commands.  */
11020
11021 enum async_reply_reason
11022 until_break_fsm::do_async_reply_reason ()
11023 {
11024   return EXEC_ASYNC_LOCATION_REACHED;
11025 }
11026
11027 void
11028 until_break_command (const char *arg, int from_tty, int anywhere)
11029 {
11030   struct frame_info *frame;
11031   struct gdbarch *frame_gdbarch;
11032   struct frame_id stack_frame_id;
11033   struct frame_id caller_frame_id;
11034   int thread;
11035   struct thread_info *tp;
11036
11037   clear_proceed_status (0);
11038
11039   /* Set a breakpoint where the user wants it and at return from
11040      this function.  */
11041
11042   event_location_up location = string_to_event_location (&arg, current_language);
11043
11044   std::vector<symtab_and_line> sals
11045     = (last_displayed_sal_is_valid ()
11046        ? decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
11047                         get_last_displayed_symtab (),
11048                         get_last_displayed_line ())
11049        : decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
11050                         NULL, (struct symtab *) NULL, 0));
11051
11052   if (sals.size () != 1)
11053     error (_("Couldn't get information on specified line."));
11054
11055   symtab_and_line &sal = sals[0];
11056
11057   if (*arg)
11058     error (_("Junk at end of arguments."));
11059
11060   resolve_sal_pc (&sal);
11061
11062   tp = inferior_thread ();
11063   thread = tp->global_num;
11064
11065   /* Note linespec handling above invalidates the frame chain.
11066      Installing a breakpoint also invalidates the frame chain (as it
11067      may need to switch threads), so do any frame handling before
11068      that.  */
11069
11070   frame = get_selected_frame (NULL);
11071   frame_gdbarch = get_frame_arch (frame);
11072   stack_frame_id = get_stack_frame_id (frame);
11073   caller_frame_id = frame_unwind_caller_id (frame);
11074
11075   /* Keep within the current frame, or in frames called by the current
11076      one.  */
11077
11078   breakpoint_up caller_breakpoint;
11079
11080   gdb::optional<delete_longjmp_breakpoint_cleanup> lj_deleter;
11081
11082   if (frame_id_p (caller_frame_id))
11083     {
11084       struct symtab_and_line sal2;
11085       struct gdbarch *caller_gdbarch;
11086
11087       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11088       sal2.pc = frame_unwind_caller_pc (frame);
11089       caller_gdbarch = frame_unwind_caller_arch (frame);
11090       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11091                                                     sal2,
11092                                                     caller_frame_id,
11093                                                     bp_until);
11094
11095       set_longjmp_breakpoint (tp, caller_frame_id);
11096       lj_deleter.emplace (thread);
11097     }
11098
11099   /* set_momentary_breakpoint could invalidate FRAME.  */
11100   frame = NULL;
11101
11102   breakpoint_up location_breakpoint;
11103   if (anywhere)
11104     /* If the user told us to continue until a specified location,
11105        we don't specify a frame at which we need to stop.  */
11106     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11107                                                     null_frame_id, bp_until);
11108   else
11109     /* Otherwise, specify the selected frame, because we want to stop
11110        only at the very same frame.  */
11111     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11112                                                     stack_frame_id, bp_until);
11113
11114   tp->thread_fsm = new until_break_fsm (command_interp (), tp->global_num,
11115                                         std::move (location_breakpoint),
11116                                         std::move (caller_breakpoint));
11117
11118   if (lj_deleter)
11119     lj_deleter->release ();
11120
11121   proceed (-1, GDB_SIGNAL_DEFAULT);
11122 }
11123
11124 /* This function attempts to parse an optional "if <cond>" clause
11125    from the arg string.  If one is not found, it returns NULL.
11126
11127    Else, it returns a pointer to the condition string.  (It does not
11128    attempt to evaluate the string against a particular block.)  And,
11129    it updates arg to point to the first character following the parsed
11130    if clause in the arg string.  */
11131
11132 const char *
11133 ep_parse_optional_if_clause (const char **arg)
11134 {
11135   const char *cond_string;
11136
11137   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11138     return NULL;
11139
11140   /* Skip the "if" keyword.  */
11141   (*arg) += 2;
11142
11143   /* Skip any extra leading whitespace, and record the start of the
11144      condition string.  */
11145   *arg = skip_spaces (*arg);
11146   cond_string = *arg;
11147
11148   /* Assume that the condition occupies the remainder of the arg
11149      string.  */
11150   (*arg) += strlen (cond_string);
11151
11152   return cond_string;
11153 }
11154
11155 /* Commands to deal with catching events, such as signals, exceptions,
11156    process start/exit, etc.  */
11157
11158 typedef enum
11159 {
11160   catch_fork_temporary, catch_vfork_temporary,
11161   catch_fork_permanent, catch_vfork_permanent
11162 }
11163 catch_fork_kind;
11164
11165 static void
11166 catch_fork_command_1 (const char *arg, int from_tty,
11167                       struct cmd_list_element *command)
11168 {
11169   struct gdbarch *gdbarch = get_current_arch ();
11170   const char *cond_string = NULL;
11171   catch_fork_kind fork_kind;
11172   int tempflag;
11173
11174   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11175   tempflag = (fork_kind == catch_fork_temporary
11176               || fork_kind == catch_vfork_temporary);
11177
11178   if (!arg)
11179     arg = "";
11180   arg = skip_spaces (arg);
11181
11182   /* The allowed syntax is:
11183      catch [v]fork
11184      catch [v]fork if <cond>
11185
11186      First, check if there's an if clause.  */
11187   cond_string = ep_parse_optional_if_clause (&arg);
11188
11189   if ((*arg != '\0') && !isspace (*arg))
11190     error (_("Junk at end of arguments."));
11191
11192   /* If this target supports it, create a fork or vfork catchpoint
11193      and enable reporting of such events.  */
11194   switch (fork_kind)
11195     {
11196     case catch_fork_temporary:
11197     case catch_fork_permanent:
11198       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11199                                           &catch_fork_breakpoint_ops);
11200       break;
11201     case catch_vfork_temporary:
11202     case catch_vfork_permanent:
11203       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11204                                           &catch_vfork_breakpoint_ops);
11205       break;
11206     default:
11207       error (_("unsupported or unknown fork kind; cannot catch it"));
11208       break;
11209     }
11210 }
11211
11212 static void
11213 catch_exec_command_1 (const char *arg, int from_tty,
11214                       struct cmd_list_element *command)
11215 {
11216   struct gdbarch *gdbarch = get_current_arch ();
11217   int tempflag;
11218   const char *cond_string = NULL;
11219
11220   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11221
11222   if (!arg)
11223     arg = "";
11224   arg = skip_spaces (arg);
11225
11226   /* The allowed syntax is:
11227      catch exec
11228      catch exec if <cond>
11229
11230      First, check if there's an if clause.  */
11231   cond_string = ep_parse_optional_if_clause (&arg);
11232
11233   if ((*arg != '\0') && !isspace (*arg))
11234     error (_("Junk at end of arguments."));
11235
11236   std::unique_ptr<exec_catchpoint> c (new exec_catchpoint ());
11237   init_catchpoint (c.get (), gdbarch, tempflag, cond_string,
11238                    &catch_exec_breakpoint_ops);
11239   c->exec_pathname = NULL;
11240
11241   install_breakpoint (0, std::move (c), 1);
11242 }
11243
11244 void
11245 init_ada_exception_breakpoint (struct breakpoint *b,
11246                                struct gdbarch *gdbarch,
11247                                struct symtab_and_line sal,
11248                                const char *addr_string,
11249                                const struct breakpoint_ops *ops,
11250                                int tempflag,
11251                                int enabled,
11252                                int from_tty)
11253 {
11254   if (from_tty)
11255     {
11256       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11257       if (!loc_gdbarch)
11258         loc_gdbarch = gdbarch;
11259
11260       describe_other_breakpoints (loc_gdbarch,
11261                                   sal.pspace, sal.pc, sal.section, -1);
11262       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11263          version for exception catchpoints, because two catchpoints
11264          used for different exception names will use the same address.
11265          In this case, a "breakpoint ... also set at..." warning is
11266          unproductive.  Besides, the warning phrasing is also a bit
11267          inappropriate, we should use the word catchpoint, and tell
11268          the user what type of catchpoint it is.  The above is good
11269          enough for now, though.  */
11270     }
11271
11272   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11273
11274   b->enable_state = enabled ? bp_enabled : bp_disabled;
11275   b->disposition = tempflag ? disp_del : disp_donttouch;
11276   b->location = string_to_event_location (&addr_string,
11277                                           language_def (language_ada));
11278   b->language = language_ada;
11279 }
11280
11281 static void
11282 catch_command (const char *arg, int from_tty)
11283 {
11284   error (_("Catch requires an event name."));
11285 }
11286 \f
11287
11288 static void
11289 tcatch_command (const char *arg, int from_tty)
11290 {
11291   error (_("Catch requires an event name."));
11292 }
11293
11294 /* Compare two breakpoints and return a strcmp-like result.  */
11295
11296 static int
11297 compare_breakpoints (const breakpoint *a, const breakpoint *b)
11298 {
11299   uintptr_t ua = (uintptr_t) a;
11300   uintptr_t ub = (uintptr_t) b;
11301
11302   if (a->number < b->number)
11303     return -1;
11304   else if (a->number > b->number)
11305     return 1;
11306
11307   /* Now sort by address, in case we see, e..g, two breakpoints with
11308      the number 0.  */
11309   if (ua < ub)
11310     return -1;
11311   return ua > ub ? 1 : 0;
11312 }
11313
11314 /* Delete breakpoints by address or line.  */
11315
11316 static void
11317 clear_command (const char *arg, int from_tty)
11318 {
11319   struct breakpoint *b;
11320   int default_match;
11321
11322   std::vector<symtab_and_line> decoded_sals;
11323   symtab_and_line last_sal;
11324   gdb::array_view<symtab_and_line> sals;
11325   if (arg)
11326     {
11327       decoded_sals
11328         = decode_line_with_current_source (arg,
11329                                            (DECODE_LINE_FUNFIRSTLINE
11330                                             | DECODE_LINE_LIST_MODE));
11331       default_match = 0;
11332       sals = decoded_sals;
11333     }
11334   else
11335     {
11336       /* Set sal's line, symtab, pc, and pspace to the values
11337          corresponding to the last call to print_frame_info.  If the
11338          codepoint is not valid, this will set all the fields to 0.  */
11339       last_sal = get_last_displayed_sal ();
11340       if (last_sal.symtab == 0)
11341         error (_("No source file specified."));
11342
11343       default_match = 1;
11344       sals = last_sal;
11345     }
11346
11347   /* We don't call resolve_sal_pc here.  That's not as bad as it
11348      seems, because all existing breakpoints typically have both
11349      file/line and pc set.  So, if clear is given file/line, we can
11350      match this to existing breakpoint without obtaining pc at all.
11351
11352      We only support clearing given the address explicitly 
11353      present in breakpoint table.  Say, we've set breakpoint 
11354      at file:line.  There were several PC values for that file:line,
11355      due to optimization, all in one block.
11356
11357      We've picked one PC value.  If "clear" is issued with another
11358      PC corresponding to the same file:line, the breakpoint won't
11359      be cleared.  We probably can still clear the breakpoint, but 
11360      since the other PC value is never presented to user, user
11361      can only find it by guessing, and it does not seem important
11362      to support that.  */
11363
11364   /* For each line spec given, delete bps which correspond to it.  Do
11365      it in two passes, solely to preserve the current behavior that
11366      from_tty is forced true if we delete more than one
11367      breakpoint.  */
11368
11369   std::vector<struct breakpoint *> found;
11370   for (const auto &sal : sals)
11371     {
11372       const char *sal_fullname;
11373
11374       /* If exact pc given, clear bpts at that pc.
11375          If line given (pc == 0), clear all bpts on specified line.
11376          If defaulting, clear all bpts on default line
11377          or at default pc.
11378
11379          defaulting    sal.pc != 0    tests to do
11380
11381          0              1             pc
11382          1              1             pc _and_ line
11383          0              0             line
11384          1              0             <can't happen> */
11385
11386       sal_fullname = (sal.symtab == NULL
11387                       ? NULL : symtab_to_fullname (sal.symtab));
11388
11389       /* Find all matching breakpoints and add them to 'found'.  */
11390       ALL_BREAKPOINTS (b)
11391         {
11392           int match = 0;
11393           /* Are we going to delete b?  */
11394           if (b->type != bp_none && !is_watchpoint (b))
11395             {
11396               struct bp_location *loc = b->loc;
11397               for (; loc; loc = loc->next)
11398                 {
11399                   /* If the user specified file:line, don't allow a PC
11400                      match.  This matches historical gdb behavior.  */
11401                   int pc_match = (!sal.explicit_line
11402                                   && sal.pc
11403                                   && (loc->pspace == sal.pspace)
11404                                   && (loc->address == sal.pc)
11405                                   && (!section_is_overlay (loc->section)
11406                                       || loc->section == sal.section));
11407                   int line_match = 0;
11408
11409                   if ((default_match || sal.explicit_line)
11410                       && loc->symtab != NULL
11411                       && sal_fullname != NULL
11412                       && sal.pspace == loc->pspace
11413                       && loc->line_number == sal.line
11414                       && filename_cmp (symtab_to_fullname (loc->symtab),
11415                                        sal_fullname) == 0)
11416                     line_match = 1;
11417
11418                   if (pc_match || line_match)
11419                     {
11420                       match = 1;
11421                       break;
11422                     }
11423                 }
11424             }
11425
11426           if (match)
11427             found.push_back (b);
11428         }
11429     }
11430
11431   /* Now go thru the 'found' chain and delete them.  */
11432   if (found.empty ())
11433     {
11434       if (arg)
11435         error (_("No breakpoint at %s."), arg);
11436       else
11437         error (_("No breakpoint at this line."));
11438     }
11439
11440   /* Remove duplicates from the vec.  */
11441   std::sort (found.begin (), found.end (),
11442              [] (const breakpoint *bp_a, const breakpoint *bp_b)
11443              {
11444                return compare_breakpoints (bp_a, bp_b) < 0;
11445              });
11446   found.erase (std::unique (found.begin (), found.end (),
11447                             [] (const breakpoint *bp_a, const breakpoint *bp_b)
11448                             {
11449                               return compare_breakpoints (bp_a, bp_b) == 0;
11450                             }),
11451                found.end ());
11452
11453   if (found.size () > 1)
11454     from_tty = 1;       /* Always report if deleted more than one.  */
11455   if (from_tty)
11456     {
11457       if (found.size () == 1)
11458         printf_unfiltered (_("Deleted breakpoint "));
11459       else
11460         printf_unfiltered (_("Deleted breakpoints "));
11461     }
11462
11463   for (breakpoint *iter : found)
11464     {
11465       if (from_tty)
11466         printf_unfiltered ("%d ", iter->number);
11467       delete_breakpoint (iter);
11468     }
11469   if (from_tty)
11470     putchar_unfiltered ('\n');
11471 }
11472 \f
11473 /* Delete breakpoint in BS if they are `delete' breakpoints and
11474    all breakpoints that are marked for deletion, whether hit or not.
11475    This is called after any breakpoint is hit, or after errors.  */
11476
11477 void
11478 breakpoint_auto_delete (bpstat bs)
11479 {
11480   struct breakpoint *b, *b_tmp;
11481
11482   for (; bs; bs = bs->next)
11483     if (bs->breakpoint_at
11484         && bs->breakpoint_at->disposition == disp_del
11485         && bs->stop)
11486       delete_breakpoint (bs->breakpoint_at);
11487
11488   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11489   {
11490     if (b->disposition == disp_del_at_next_stop)
11491       delete_breakpoint (b);
11492   }
11493 }
11494
11495 /* A comparison function for bp_location AP and BP being interfaced to
11496    qsort.  Sort elements primarily by their ADDRESS (no matter what
11497    does breakpoint_address_is_meaningful say for its OWNER),
11498    secondarily by ordering first permanent elements and
11499    terciarily just ensuring the array is sorted stable way despite
11500    qsort being an unstable algorithm.  */
11501
11502 static int
11503 bp_locations_compare (const void *ap, const void *bp)
11504 {
11505   const struct bp_location *a = *(const struct bp_location **) ap;
11506   const struct bp_location *b = *(const struct bp_location **) bp;
11507
11508   if (a->address != b->address)
11509     return (a->address > b->address) - (a->address < b->address);
11510
11511   /* Sort locations at the same address by their pspace number, keeping
11512      locations of the same inferior (in a multi-inferior environment)
11513      grouped.  */
11514
11515   if (a->pspace->num != b->pspace->num)
11516     return ((a->pspace->num > b->pspace->num)
11517             - (a->pspace->num < b->pspace->num));
11518
11519   /* Sort permanent breakpoints first.  */
11520   if (a->permanent != b->permanent)
11521     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
11522
11523   /* Make the internal GDB representation stable across GDB runs
11524      where A and B memory inside GDB can differ.  Breakpoint locations of
11525      the same type at the same address can be sorted in arbitrary order.  */
11526
11527   if (a->owner->number != b->owner->number)
11528     return ((a->owner->number > b->owner->number)
11529             - (a->owner->number < b->owner->number));
11530
11531   return (a > b) - (a < b);
11532 }
11533
11534 /* Set bp_locations_placed_address_before_address_max and
11535    bp_locations_shadow_len_after_address_max according to the current
11536    content of the bp_locations array.  */
11537
11538 static void
11539 bp_locations_target_extensions_update (void)
11540 {
11541   struct bp_location *bl, **blp_tmp;
11542
11543   bp_locations_placed_address_before_address_max = 0;
11544   bp_locations_shadow_len_after_address_max = 0;
11545
11546   ALL_BP_LOCATIONS (bl, blp_tmp)
11547     {
11548       CORE_ADDR start, end, addr;
11549
11550       if (!bp_location_has_shadow (bl))
11551         continue;
11552
11553       start = bl->target_info.placed_address;
11554       end = start + bl->target_info.shadow_len;
11555
11556       gdb_assert (bl->address >= start);
11557       addr = bl->address - start;
11558       if (addr > bp_locations_placed_address_before_address_max)
11559         bp_locations_placed_address_before_address_max = addr;
11560
11561       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11562
11563       gdb_assert (bl->address < end);
11564       addr = end - bl->address;
11565       if (addr > bp_locations_shadow_len_after_address_max)
11566         bp_locations_shadow_len_after_address_max = addr;
11567     }
11568 }
11569
11570 /* Download tracepoint locations if they haven't been.  */
11571
11572 static void
11573 download_tracepoint_locations (void)
11574 {
11575   struct breakpoint *b;
11576   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11577
11578   scoped_restore_current_pspace_and_thread restore_pspace_thread;
11579
11580   ALL_TRACEPOINTS (b)
11581     {
11582       struct bp_location *bl;
11583       struct tracepoint *t;
11584       int bp_location_downloaded = 0;
11585
11586       if ((b->type == bp_fast_tracepoint
11587            ? !may_insert_fast_tracepoints
11588            : !may_insert_tracepoints))
11589         continue;
11590
11591       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11592         {
11593           if (target_can_download_tracepoint ())
11594             can_download_tracepoint = TRIBOOL_TRUE;
11595           else
11596             can_download_tracepoint = TRIBOOL_FALSE;
11597         }
11598
11599       if (can_download_tracepoint == TRIBOOL_FALSE)
11600         break;
11601
11602       for (bl = b->loc; bl; bl = bl->next)
11603         {
11604           /* In tracepoint, locations are _never_ duplicated, so
11605              should_be_inserted is equivalent to
11606              unduplicated_should_be_inserted.  */
11607           if (!should_be_inserted (bl) || bl->inserted)
11608             continue;
11609
11610           switch_to_program_space_and_thread (bl->pspace);
11611
11612           target_download_tracepoint (bl);
11613
11614           bl->inserted = 1;
11615           bp_location_downloaded = 1;
11616         }
11617       t = (struct tracepoint *) b;
11618       t->number_on_target = b->number;
11619       if (bp_location_downloaded)
11620         gdb::observers::breakpoint_modified.notify (b);
11621     }
11622 }
11623
11624 /* Swap the insertion/duplication state between two locations.  */
11625
11626 static void
11627 swap_insertion (struct bp_location *left, struct bp_location *right)
11628 {
11629   const int left_inserted = left->inserted;
11630   const int left_duplicate = left->duplicate;
11631   const int left_needs_update = left->needs_update;
11632   const struct bp_target_info left_target_info = left->target_info;
11633
11634   /* Locations of tracepoints can never be duplicated.  */
11635   if (is_tracepoint (left->owner))
11636     gdb_assert (!left->duplicate);
11637   if (is_tracepoint (right->owner))
11638     gdb_assert (!right->duplicate);
11639
11640   left->inserted = right->inserted;
11641   left->duplicate = right->duplicate;
11642   left->needs_update = right->needs_update;
11643   left->target_info = right->target_info;
11644   right->inserted = left_inserted;
11645   right->duplicate = left_duplicate;
11646   right->needs_update = left_needs_update;
11647   right->target_info = left_target_info;
11648 }
11649
11650 /* Force the re-insertion of the locations at ADDRESS.  This is called
11651    once a new/deleted/modified duplicate location is found and we are evaluating
11652    conditions on the target's side.  Such conditions need to be updated on
11653    the target.  */
11654
11655 static void
11656 force_breakpoint_reinsertion (struct bp_location *bl)
11657 {
11658   struct bp_location **locp = NULL, **loc2p;
11659   struct bp_location *loc;
11660   CORE_ADDR address = 0;
11661   int pspace_num;
11662
11663   address = bl->address;
11664   pspace_num = bl->pspace->num;
11665
11666   /* This is only meaningful if the target is
11667      evaluating conditions and if the user has
11668      opted for condition evaluation on the target's
11669      side.  */
11670   if (gdb_evaluates_breakpoint_condition_p ()
11671       || !target_supports_evaluation_of_breakpoint_conditions ())
11672     return;
11673
11674   /* Flag all breakpoint locations with this address and
11675      the same program space as the location
11676      as "its condition has changed".  We need to
11677      update the conditions on the target's side.  */
11678   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11679     {
11680       loc = *loc2p;
11681
11682       if (!is_breakpoint (loc->owner)
11683           || pspace_num != loc->pspace->num)
11684         continue;
11685
11686       /* Flag the location appropriately.  We use a different state to
11687          let everyone know that we already updated the set of locations
11688          with addr bl->address and program space bl->pspace.  This is so
11689          we don't have to keep calling these functions just to mark locations
11690          that have already been marked.  */
11691       loc->condition_changed = condition_updated;
11692
11693       /* Free the agent expression bytecode as well.  We will compute
11694          it later on.  */
11695       loc->cond_bytecode.reset ();
11696     }
11697 }
11698 /* Called whether new breakpoints are created, or existing breakpoints
11699    deleted, to update the global location list and recompute which
11700    locations are duplicate of which.
11701
11702    The INSERT_MODE flag determines whether locations may not, may, or
11703    shall be inserted now.  See 'enum ugll_insert_mode' for more
11704    info.  */
11705
11706 static void
11707 update_global_location_list (enum ugll_insert_mode insert_mode)
11708 {
11709   struct breakpoint *b;
11710   struct bp_location **locp, *loc;
11711   /* Last breakpoint location address that was marked for update.  */
11712   CORE_ADDR last_addr = 0;
11713   /* Last breakpoint location program space that was marked for update.  */
11714   int last_pspace_num = -1;
11715
11716   /* Used in the duplicates detection below.  When iterating over all
11717      bp_locations, points to the first bp_location of a given address.
11718      Breakpoints and watchpoints of different types are never
11719      duplicates of each other.  Keep one pointer for each type of
11720      breakpoint/watchpoint, so we only need to loop over all locations
11721      once.  */
11722   struct bp_location *bp_loc_first;  /* breakpoint */
11723   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11724   struct bp_location *awp_loc_first; /* access watchpoint */
11725   struct bp_location *rwp_loc_first; /* read watchpoint */
11726
11727   /* Saved former bp_locations array which we compare against the newly
11728      built bp_locations from the current state of ALL_BREAKPOINTS.  */
11729   struct bp_location **old_locp;
11730   unsigned old_locations_count;
11731   gdb::unique_xmalloc_ptr<struct bp_location *> old_locations (bp_locations);
11732
11733   old_locations_count = bp_locations_count;
11734   bp_locations = NULL;
11735   bp_locations_count = 0;
11736
11737   ALL_BREAKPOINTS (b)
11738     for (loc = b->loc; loc; loc = loc->next)
11739       bp_locations_count++;
11740
11741   bp_locations = XNEWVEC (struct bp_location *, bp_locations_count);
11742   locp = bp_locations;
11743   ALL_BREAKPOINTS (b)
11744     for (loc = b->loc; loc; loc = loc->next)
11745       *locp++ = loc;
11746   qsort (bp_locations, bp_locations_count, sizeof (*bp_locations),
11747          bp_locations_compare);
11748
11749   bp_locations_target_extensions_update ();
11750
11751   /* Identify bp_location instances that are no longer present in the
11752      new list, and therefore should be freed.  Note that it's not
11753      necessary that those locations should be removed from inferior --
11754      if there's another location at the same address (previously
11755      marked as duplicate), we don't need to remove/insert the
11756      location.
11757      
11758      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11759      and former bp_location array state respectively.  */
11760
11761   locp = bp_locations;
11762   for (old_locp = old_locations.get ();
11763        old_locp < old_locations.get () + old_locations_count;
11764        old_locp++)
11765     {
11766       struct bp_location *old_loc = *old_locp;
11767       struct bp_location **loc2p;
11768
11769       /* Tells if 'old_loc' is found among the new locations.  If
11770          not, we have to free it.  */
11771       int found_object = 0;
11772       /* Tells if the location should remain inserted in the target.  */
11773       int keep_in_target = 0;
11774       int removed = 0;
11775
11776       /* Skip LOCP entries which will definitely never be needed.
11777          Stop either at or being the one matching OLD_LOC.  */
11778       while (locp < bp_locations + bp_locations_count
11779              && (*locp)->address < old_loc->address)
11780         locp++;
11781
11782       for (loc2p = locp;
11783            (loc2p < bp_locations + bp_locations_count
11784             && (*loc2p)->address == old_loc->address);
11785            loc2p++)
11786         {
11787           /* Check if this is a new/duplicated location or a duplicated
11788              location that had its condition modified.  If so, we want to send
11789              its condition to the target if evaluation of conditions is taking
11790              place there.  */
11791           if ((*loc2p)->condition_changed == condition_modified
11792               && (last_addr != old_loc->address
11793                   || last_pspace_num != old_loc->pspace->num))
11794             {
11795               force_breakpoint_reinsertion (*loc2p);
11796               last_pspace_num = old_loc->pspace->num;
11797             }
11798
11799           if (*loc2p == old_loc)
11800             found_object = 1;
11801         }
11802
11803       /* We have already handled this address, update it so that we don't
11804          have to go through updates again.  */
11805       last_addr = old_loc->address;
11806
11807       /* Target-side condition evaluation: Handle deleted locations.  */
11808       if (!found_object)
11809         force_breakpoint_reinsertion (old_loc);
11810
11811       /* If this location is no longer present, and inserted, look if
11812          there's maybe a new location at the same address.  If so,
11813          mark that one inserted, and don't remove this one.  This is
11814          needed so that we don't have a time window where a breakpoint
11815          at certain location is not inserted.  */
11816
11817       if (old_loc->inserted)
11818         {
11819           /* If the location is inserted now, we might have to remove
11820              it.  */
11821
11822           if (found_object && should_be_inserted (old_loc))
11823             {
11824               /* The location is still present in the location list,
11825                  and still should be inserted.  Don't do anything.  */
11826               keep_in_target = 1;
11827             }
11828           else
11829             {
11830               /* This location still exists, but it won't be kept in the
11831                  target since it may have been disabled.  We proceed to
11832                  remove its target-side condition.  */
11833
11834               /* The location is either no longer present, or got
11835                  disabled.  See if there's another location at the
11836                  same address, in which case we don't need to remove
11837                  this one from the target.  */
11838
11839               /* OLD_LOC comes from existing struct breakpoint.  */
11840               if (breakpoint_address_is_meaningful (old_loc->owner))
11841                 {
11842                   for (loc2p = locp;
11843                        (loc2p < bp_locations + bp_locations_count
11844                         && (*loc2p)->address == old_loc->address);
11845                        loc2p++)
11846                     {
11847                       struct bp_location *loc2 = *loc2p;
11848
11849                       if (breakpoint_locations_match (loc2, old_loc))
11850                         {
11851                           /* Read watchpoint locations are switched to
11852                              access watchpoints, if the former are not
11853                              supported, but the latter are.  */
11854                           if (is_hardware_watchpoint (old_loc->owner))
11855                             {
11856                               gdb_assert (is_hardware_watchpoint (loc2->owner));
11857                               loc2->watchpoint_type = old_loc->watchpoint_type;
11858                             }
11859
11860                           /* loc2 is a duplicated location. We need to check
11861                              if it should be inserted in case it will be
11862                              unduplicated.  */
11863                           if (loc2 != old_loc
11864                               && unduplicated_should_be_inserted (loc2))
11865                             {
11866                               swap_insertion (old_loc, loc2);
11867                               keep_in_target = 1;
11868                               break;
11869                             }
11870                         }
11871                     }
11872                 }
11873             }
11874
11875           if (!keep_in_target)
11876             {
11877               if (remove_breakpoint (old_loc))
11878                 {
11879                   /* This is just about all we can do.  We could keep
11880                      this location on the global list, and try to
11881                      remove it next time, but there's no particular
11882                      reason why we will succeed next time.
11883                      
11884                      Note that at this point, old_loc->owner is still
11885                      valid, as delete_breakpoint frees the breakpoint
11886                      only after calling us.  */
11887                   printf_filtered (_("warning: Error removing "
11888                                      "breakpoint %d\n"), 
11889                                    old_loc->owner->number);
11890                 }
11891               removed = 1;
11892             }
11893         }
11894
11895       if (!found_object)
11896         {
11897           if (removed && target_is_non_stop_p ()
11898               && need_moribund_for_location_type (old_loc))
11899             {
11900               /* This location was removed from the target.  In
11901                  non-stop mode, a race condition is possible where
11902                  we've removed a breakpoint, but stop events for that
11903                  breakpoint are already queued and will arrive later.
11904                  We apply an heuristic to be able to distinguish such
11905                  SIGTRAPs from other random SIGTRAPs: we keep this
11906                  breakpoint location for a bit, and will retire it
11907                  after we see some number of events.  The theory here
11908                  is that reporting of events should, "on the average",
11909                  be fair, so after a while we'll see events from all
11910                  threads that have anything of interest, and no longer
11911                  need to keep this breakpoint location around.  We
11912                  don't hold locations forever so to reduce chances of
11913                  mistaking a non-breakpoint SIGTRAP for a breakpoint
11914                  SIGTRAP.
11915
11916                  The heuristic failing can be disastrous on
11917                  decr_pc_after_break targets.
11918
11919                  On decr_pc_after_break targets, like e.g., x86-linux,
11920                  if we fail to recognize a late breakpoint SIGTRAP,
11921                  because events_till_retirement has reached 0 too
11922                  soon, we'll fail to do the PC adjustment, and report
11923                  a random SIGTRAP to the user.  When the user resumes
11924                  the inferior, it will most likely immediately crash
11925                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
11926                  corrupted, because of being resumed e.g., in the
11927                  middle of a multi-byte instruction, or skipped a
11928                  one-byte instruction.  This was actually seen happen
11929                  on native x86-linux, and should be less rare on
11930                  targets that do not support new thread events, like
11931                  remote, due to the heuristic depending on
11932                  thread_count.
11933
11934                  Mistaking a random SIGTRAP for a breakpoint trap
11935                  causes similar symptoms (PC adjustment applied when
11936                  it shouldn't), but then again, playing with SIGTRAPs
11937                  behind the debugger's back is asking for trouble.
11938
11939                  Since hardware watchpoint traps are always
11940                  distinguishable from other traps, so we don't need to
11941                  apply keep hardware watchpoint moribund locations
11942                  around.  We simply always ignore hardware watchpoint
11943                  traps we can no longer explain.  */
11944
11945               old_loc->events_till_retirement = 3 * (thread_count () + 1);
11946               old_loc->owner = NULL;
11947
11948               moribund_locations.push_back (old_loc);
11949             }
11950           else
11951             {
11952               old_loc->owner = NULL;
11953               decref_bp_location (&old_loc);
11954             }
11955         }
11956     }
11957
11958   /* Rescan breakpoints at the same address and section, marking the
11959      first one as "first" and any others as "duplicates".  This is so
11960      that the bpt instruction is only inserted once.  If we have a
11961      permanent breakpoint at the same place as BPT, make that one the
11962      official one, and the rest as duplicates.  Permanent breakpoints
11963      are sorted first for the same address.
11964
11965      Do the same for hardware watchpoints, but also considering the
11966      watchpoint's type (regular/access/read) and length.  */
11967
11968   bp_loc_first = NULL;
11969   wp_loc_first = NULL;
11970   awp_loc_first = NULL;
11971   rwp_loc_first = NULL;
11972   ALL_BP_LOCATIONS (loc, locp)
11973     {
11974       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
11975          non-NULL.  */
11976       struct bp_location **loc_first_p;
11977       b = loc->owner;
11978
11979       if (!unduplicated_should_be_inserted (loc)
11980           || !breakpoint_address_is_meaningful (b)
11981           /* Don't detect duplicate for tracepoint locations because they are
11982            never duplicated.  See the comments in field `duplicate' of
11983            `struct bp_location'.  */
11984           || is_tracepoint (b))
11985         {
11986           /* Clear the condition modification flag.  */
11987           loc->condition_changed = condition_unchanged;
11988           continue;
11989         }
11990
11991       if (b->type == bp_hardware_watchpoint)
11992         loc_first_p = &wp_loc_first;
11993       else if (b->type == bp_read_watchpoint)
11994         loc_first_p = &rwp_loc_first;
11995       else if (b->type == bp_access_watchpoint)
11996         loc_first_p = &awp_loc_first;
11997       else
11998         loc_first_p = &bp_loc_first;
11999
12000       if (*loc_first_p == NULL
12001           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12002           || !breakpoint_locations_match (loc, *loc_first_p))
12003         {
12004           *loc_first_p = loc;
12005           loc->duplicate = 0;
12006
12007           if (is_breakpoint (loc->owner) && loc->condition_changed)
12008             {
12009               loc->needs_update = 1;
12010               /* Clear the condition modification flag.  */
12011               loc->condition_changed = condition_unchanged;
12012             }
12013           continue;
12014         }
12015
12016
12017       /* This and the above ensure the invariant that the first location
12018          is not duplicated, and is the inserted one.
12019          All following are marked as duplicated, and are not inserted.  */
12020       if (loc->inserted)
12021         swap_insertion (loc, *loc_first_p);
12022       loc->duplicate = 1;
12023
12024       /* Clear the condition modification flag.  */
12025       loc->condition_changed = condition_unchanged;
12026     }
12027
12028   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12029     {
12030       if (insert_mode != UGLL_DONT_INSERT)
12031         insert_breakpoint_locations ();
12032       else
12033         {
12034           /* Even though the caller told us to not insert new
12035              locations, we may still need to update conditions on the
12036              target's side of breakpoints that were already inserted
12037              if the target is evaluating breakpoint conditions.  We
12038              only update conditions for locations that are marked
12039              "needs_update".  */
12040           update_inserted_breakpoint_locations ();
12041         }
12042     }
12043
12044   if (insert_mode != UGLL_DONT_INSERT)
12045     download_tracepoint_locations ();
12046 }
12047
12048 void
12049 breakpoint_retire_moribund (void)
12050 {
12051   for (int ix = 0; ix < moribund_locations.size (); ++ix)
12052     {
12053       struct bp_location *loc = moribund_locations[ix];
12054       if (--(loc->events_till_retirement) == 0)
12055         {
12056           decref_bp_location (&loc);
12057           unordered_remove (moribund_locations, ix);
12058           --ix;
12059         }
12060     }
12061 }
12062
12063 static void
12064 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12065 {
12066
12067   TRY
12068     {
12069       update_global_location_list (insert_mode);
12070     }
12071   CATCH (e, RETURN_MASK_ERROR)
12072     {
12073     }
12074   END_CATCH
12075 }
12076
12077 /* Clear BKP from a BPS.  */
12078
12079 static void
12080 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12081 {
12082   bpstat bs;
12083
12084   for (bs = bps; bs; bs = bs->next)
12085     if (bs->breakpoint_at == bpt)
12086       {
12087         bs->breakpoint_at = NULL;
12088         bs->old_val = NULL;
12089         /* bs->commands will be freed later.  */
12090       }
12091 }
12092
12093 /* Callback for iterate_over_threads.  */
12094 static int
12095 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12096 {
12097   struct breakpoint *bpt = (struct breakpoint *) data;
12098
12099   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12100   return 0;
12101 }
12102
12103 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12104    callbacks.  */
12105
12106 static void
12107 say_where (struct breakpoint *b)
12108 {
12109   struct value_print_options opts;
12110
12111   get_user_print_options (&opts);
12112
12113   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12114      single string.  */
12115   if (b->loc == NULL)
12116     {
12117       /* For pending locations, the output differs slightly based
12118          on b->extra_string.  If this is non-NULL, it contains either
12119          a condition or dprintf arguments.  */
12120       if (b->extra_string == NULL)
12121         {
12122           printf_filtered (_(" (%s) pending."),
12123                            event_location_to_string (b->location.get ()));
12124         }
12125       else if (b->type == bp_dprintf)
12126         {
12127           printf_filtered (_(" (%s,%s) pending."),
12128                            event_location_to_string (b->location.get ()),
12129                            b->extra_string);
12130         }
12131       else
12132         {
12133           printf_filtered (_(" (%s %s) pending."),
12134                            event_location_to_string (b->location.get ()),
12135                            b->extra_string);
12136         }
12137     }
12138   else
12139     {
12140       if (opts.addressprint || b->loc->symtab == NULL)
12141         {
12142           printf_filtered (" at ");
12143           fputs_styled (paddress (b->loc->gdbarch, b->loc->address),
12144                         address_style.style (),
12145                         gdb_stdout);
12146         }
12147       if (b->loc->symtab != NULL)
12148         {
12149           /* If there is a single location, we can print the location
12150              more nicely.  */
12151           if (b->loc->next == NULL)
12152             {
12153               puts_filtered (": file ");
12154               fputs_styled (symtab_to_filename_for_display (b->loc->symtab),
12155                             file_name_style.style (),
12156                             gdb_stdout);
12157               printf_filtered (", line %d.",
12158                                b->loc->line_number);
12159             }
12160           else
12161             /* This is not ideal, but each location may have a
12162                different file name, and this at least reflects the
12163                real situation somewhat.  */
12164             printf_filtered (": %s.",
12165                              event_location_to_string (b->location.get ()));
12166         }
12167
12168       if (b->loc->next)
12169         {
12170           struct bp_location *loc = b->loc;
12171           int n = 0;
12172           for (; loc; loc = loc->next)
12173             ++n;
12174           printf_filtered (" (%d locations)", n);
12175         }
12176     }
12177 }
12178
12179 bp_location::~bp_location ()
12180 {
12181   xfree (function_name);
12182 }
12183
12184 /* Destructor for the breakpoint base class.  */
12185
12186 breakpoint::~breakpoint ()
12187 {
12188   xfree (this->cond_string);
12189   xfree (this->extra_string);
12190   xfree (this->filter);
12191 }
12192
12193 static struct bp_location *
12194 base_breakpoint_allocate_location (struct breakpoint *self)
12195 {
12196   return new bp_location (self);
12197 }
12198
12199 static void
12200 base_breakpoint_re_set (struct breakpoint *b)
12201 {
12202   /* Nothing to re-set. */
12203 }
12204
12205 #define internal_error_pure_virtual_called() \
12206   gdb_assert_not_reached ("pure virtual function called")
12207
12208 static int
12209 base_breakpoint_insert_location (struct bp_location *bl)
12210 {
12211   internal_error_pure_virtual_called ();
12212 }
12213
12214 static int
12215 base_breakpoint_remove_location (struct bp_location *bl,
12216                                  enum remove_bp_reason reason)
12217 {
12218   internal_error_pure_virtual_called ();
12219 }
12220
12221 static int
12222 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12223                                 const address_space *aspace,
12224                                 CORE_ADDR bp_addr,
12225                                 const struct target_waitstatus *ws)
12226 {
12227   internal_error_pure_virtual_called ();
12228 }
12229
12230 static void
12231 base_breakpoint_check_status (bpstat bs)
12232 {
12233   /* Always stop.   */
12234 }
12235
12236 /* A "works_in_software_mode" breakpoint_ops method that just internal
12237    errors.  */
12238
12239 static int
12240 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12241 {
12242   internal_error_pure_virtual_called ();
12243 }
12244
12245 /* A "resources_needed" breakpoint_ops method that just internal
12246    errors.  */
12247
12248 static int
12249 base_breakpoint_resources_needed (const struct bp_location *bl)
12250 {
12251   internal_error_pure_virtual_called ();
12252 }
12253
12254 static enum print_stop_action
12255 base_breakpoint_print_it (bpstat bs)
12256 {
12257   internal_error_pure_virtual_called ();
12258 }
12259
12260 static void
12261 base_breakpoint_print_one_detail (const struct breakpoint *self,
12262                                   struct ui_out *uiout)
12263 {
12264   /* nothing */
12265 }
12266
12267 static void
12268 base_breakpoint_print_mention (struct breakpoint *b)
12269 {
12270   internal_error_pure_virtual_called ();
12271 }
12272
12273 static void
12274 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12275 {
12276   internal_error_pure_virtual_called ();
12277 }
12278
12279 static void
12280 base_breakpoint_create_sals_from_location
12281   (const struct event_location *location,
12282    struct linespec_result *canonical,
12283    enum bptype type_wanted)
12284 {
12285   internal_error_pure_virtual_called ();
12286 }
12287
12288 static void
12289 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12290                                         struct linespec_result *c,
12291                                         gdb::unique_xmalloc_ptr<char> cond_string,
12292                                         gdb::unique_xmalloc_ptr<char> extra_string,
12293                                         enum bptype type_wanted,
12294                                         enum bpdisp disposition,
12295                                         int thread,
12296                                         int task, int ignore_count,
12297                                         const struct breakpoint_ops *o,
12298                                         int from_tty, int enabled,
12299                                         int internal, unsigned flags)
12300 {
12301   internal_error_pure_virtual_called ();
12302 }
12303
12304 static std::vector<symtab_and_line>
12305 base_breakpoint_decode_location (struct breakpoint *b,
12306                                  const struct event_location *location,
12307                                  struct program_space *search_pspace)
12308 {
12309   internal_error_pure_virtual_called ();
12310 }
12311
12312 /* The default 'explains_signal' method.  */
12313
12314 static int
12315 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12316 {
12317   return 1;
12318 }
12319
12320 /* The default "after_condition_true" method.  */
12321
12322 static void
12323 base_breakpoint_after_condition_true (struct bpstats *bs)
12324 {
12325   /* Nothing to do.   */
12326 }
12327
12328 struct breakpoint_ops base_breakpoint_ops =
12329 {
12330   base_breakpoint_allocate_location,
12331   base_breakpoint_re_set,
12332   base_breakpoint_insert_location,
12333   base_breakpoint_remove_location,
12334   base_breakpoint_breakpoint_hit,
12335   base_breakpoint_check_status,
12336   base_breakpoint_resources_needed,
12337   base_breakpoint_works_in_software_mode,
12338   base_breakpoint_print_it,
12339   NULL,
12340   base_breakpoint_print_one_detail,
12341   base_breakpoint_print_mention,
12342   base_breakpoint_print_recreate,
12343   base_breakpoint_create_sals_from_location,
12344   base_breakpoint_create_breakpoints_sal,
12345   base_breakpoint_decode_location,
12346   base_breakpoint_explains_signal,
12347   base_breakpoint_after_condition_true,
12348 };
12349
12350 /* Default breakpoint_ops methods.  */
12351
12352 static void
12353 bkpt_re_set (struct breakpoint *b)
12354 {
12355   /* FIXME: is this still reachable?  */
12356   if (breakpoint_event_location_empty_p (b))
12357     {
12358       /* Anything without a location can't be re-set.  */
12359       delete_breakpoint (b);
12360       return;
12361     }
12362
12363   breakpoint_re_set_default (b);
12364 }
12365
12366 static int
12367 bkpt_insert_location (struct bp_location *bl)
12368 {
12369   CORE_ADDR addr = bl->target_info.reqstd_address;
12370
12371   bl->target_info.kind = breakpoint_kind (bl, &addr);
12372   bl->target_info.placed_address = addr;
12373
12374   if (bl->loc_type == bp_loc_hardware_breakpoint)
12375     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12376   else
12377     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12378 }
12379
12380 static int
12381 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
12382 {
12383   if (bl->loc_type == bp_loc_hardware_breakpoint)
12384     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12385   else
12386     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12387 }
12388
12389 static int
12390 bkpt_breakpoint_hit (const struct bp_location *bl,
12391                      const address_space *aspace, CORE_ADDR bp_addr,
12392                      const struct target_waitstatus *ws)
12393 {
12394   if (ws->kind != TARGET_WAITKIND_STOPPED
12395       || ws->value.sig != GDB_SIGNAL_TRAP)
12396     return 0;
12397
12398   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12399                                  aspace, bp_addr))
12400     return 0;
12401
12402   if (overlay_debugging         /* unmapped overlay section */
12403       && section_is_overlay (bl->section)
12404       && !section_is_mapped (bl->section))
12405     return 0;
12406
12407   return 1;
12408 }
12409
12410 static int
12411 dprintf_breakpoint_hit (const struct bp_location *bl,
12412                         const address_space *aspace, CORE_ADDR bp_addr,
12413                         const struct target_waitstatus *ws)
12414 {
12415   if (dprintf_style == dprintf_style_agent
12416       && target_can_run_breakpoint_commands ())
12417     {
12418       /* An agent-style dprintf never causes a stop.  If we see a trap
12419          for this address it must be for a breakpoint that happens to
12420          be set at the same address.  */
12421       return 0;
12422     }
12423
12424   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12425 }
12426
12427 static int
12428 bkpt_resources_needed (const struct bp_location *bl)
12429 {
12430   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12431
12432   return 1;
12433 }
12434
12435 static enum print_stop_action
12436 bkpt_print_it (bpstat bs)
12437 {
12438   struct breakpoint *b;
12439   const struct bp_location *bl;
12440   int bp_temp;
12441   struct ui_out *uiout = current_uiout;
12442
12443   gdb_assert (bs->bp_location_at != NULL);
12444
12445   bl = bs->bp_location_at;
12446   b = bs->breakpoint_at;
12447
12448   bp_temp = b->disposition == disp_del;
12449   if (bl->address != bl->requested_address)
12450     breakpoint_adjustment_warning (bl->requested_address,
12451                                    bl->address,
12452                                    b->number, 1);
12453   annotate_breakpoint (b->number);
12454   maybe_print_thread_hit_breakpoint (uiout);
12455
12456   if (bp_temp)
12457     uiout->text ("Temporary breakpoint ");
12458   else
12459     uiout->text ("Breakpoint ");
12460   if (uiout->is_mi_like_p ())
12461     {
12462       uiout->field_string ("reason",
12463                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12464       uiout->field_string ("disp", bpdisp_text (b->disposition));
12465     }
12466   uiout->field_int ("bkptno", b->number);
12467   uiout->text (", ");
12468
12469   return PRINT_SRC_AND_LOC;
12470 }
12471
12472 static void
12473 bkpt_print_mention (struct breakpoint *b)
12474 {
12475   if (current_uiout->is_mi_like_p ())
12476     return;
12477
12478   switch (b->type)
12479     {
12480     case bp_breakpoint:
12481     case bp_gnu_ifunc_resolver:
12482       if (b->disposition == disp_del)
12483         printf_filtered (_("Temporary breakpoint"));
12484       else
12485         printf_filtered (_("Breakpoint"));
12486       printf_filtered (_(" %d"), b->number);
12487       if (b->type == bp_gnu_ifunc_resolver)
12488         printf_filtered (_(" at gnu-indirect-function resolver"));
12489       break;
12490     case bp_hardware_breakpoint:
12491       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12492       break;
12493     case bp_dprintf:
12494       printf_filtered (_("Dprintf %d"), b->number);
12495       break;
12496     }
12497
12498   say_where (b);
12499 }
12500
12501 static void
12502 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12503 {
12504   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12505     fprintf_unfiltered (fp, "tbreak");
12506   else if (tp->type == bp_breakpoint)
12507     fprintf_unfiltered (fp, "break");
12508   else if (tp->type == bp_hardware_breakpoint
12509            && tp->disposition == disp_del)
12510     fprintf_unfiltered (fp, "thbreak");
12511   else if (tp->type == bp_hardware_breakpoint)
12512     fprintf_unfiltered (fp, "hbreak");
12513   else
12514     internal_error (__FILE__, __LINE__,
12515                     _("unhandled breakpoint type %d"), (int) tp->type);
12516
12517   fprintf_unfiltered (fp, " %s",
12518                       event_location_to_string (tp->location.get ()));
12519
12520   /* Print out extra_string if this breakpoint is pending.  It might
12521      contain, for example, conditions that were set by the user.  */
12522   if (tp->loc == NULL && tp->extra_string != NULL)
12523     fprintf_unfiltered (fp, " %s", tp->extra_string);
12524
12525   print_recreate_thread (tp, fp);
12526 }
12527
12528 static void
12529 bkpt_create_sals_from_location (const struct event_location *location,
12530                                 struct linespec_result *canonical,
12531                                 enum bptype type_wanted)
12532 {
12533   create_sals_from_location_default (location, canonical, type_wanted);
12534 }
12535
12536 static void
12537 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12538                              struct linespec_result *canonical,
12539                              gdb::unique_xmalloc_ptr<char> cond_string,
12540                              gdb::unique_xmalloc_ptr<char> extra_string,
12541                              enum bptype type_wanted,
12542                              enum bpdisp disposition,
12543                              int thread,
12544                              int task, int ignore_count,
12545                              const struct breakpoint_ops *ops,
12546                              int from_tty, int enabled,
12547                              int internal, unsigned flags)
12548 {
12549   create_breakpoints_sal_default (gdbarch, canonical,
12550                                   std::move (cond_string),
12551                                   std::move (extra_string),
12552                                   type_wanted,
12553                                   disposition, thread, task,
12554                                   ignore_count, ops, from_tty,
12555                                   enabled, internal, flags);
12556 }
12557
12558 static std::vector<symtab_and_line>
12559 bkpt_decode_location (struct breakpoint *b,
12560                       const struct event_location *location,
12561                       struct program_space *search_pspace)
12562 {
12563   return decode_location_default (b, location, search_pspace);
12564 }
12565
12566 /* Virtual table for internal breakpoints.  */
12567
12568 static void
12569 internal_bkpt_re_set (struct breakpoint *b)
12570 {
12571   switch (b->type)
12572     {
12573       /* Delete overlay event and longjmp master breakpoints; they
12574          will be reset later by breakpoint_re_set.  */
12575     case bp_overlay_event:
12576     case bp_longjmp_master:
12577     case bp_std_terminate_master:
12578     case bp_exception_master:
12579       delete_breakpoint (b);
12580       break;
12581
12582       /* This breakpoint is special, it's set up when the inferior
12583          starts and we really don't want to touch it.  */
12584     case bp_shlib_event:
12585
12586       /* Like bp_shlib_event, this breakpoint type is special.  Once
12587          it is set up, we do not want to touch it.  */
12588     case bp_thread_event:
12589       break;
12590     }
12591 }
12592
12593 static void
12594 internal_bkpt_check_status (bpstat bs)
12595 {
12596   if (bs->breakpoint_at->type == bp_shlib_event)
12597     {
12598       /* If requested, stop when the dynamic linker notifies GDB of
12599          events.  This allows the user to get control and place
12600          breakpoints in initializer routines for dynamically loaded
12601          objects (among other things).  */
12602       bs->stop = stop_on_solib_events;
12603       bs->print = stop_on_solib_events;
12604     }
12605   else
12606     bs->stop = 0;
12607 }
12608
12609 static enum print_stop_action
12610 internal_bkpt_print_it (bpstat bs)
12611 {
12612   struct breakpoint *b;
12613
12614   b = bs->breakpoint_at;
12615
12616   switch (b->type)
12617     {
12618     case bp_shlib_event:
12619       /* Did we stop because the user set the stop_on_solib_events
12620          variable?  (If so, we report this as a generic, "Stopped due
12621          to shlib event" message.) */
12622       print_solib_event (0);
12623       break;
12624
12625     case bp_thread_event:
12626       /* Not sure how we will get here.
12627          GDB should not stop for these breakpoints.  */
12628       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12629       break;
12630
12631     case bp_overlay_event:
12632       /* By analogy with the thread event, GDB should not stop for these.  */
12633       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12634       break;
12635
12636     case bp_longjmp_master:
12637       /* These should never be enabled.  */
12638       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12639       break;
12640
12641     case bp_std_terminate_master:
12642       /* These should never be enabled.  */
12643       printf_filtered (_("std::terminate Master Breakpoint: "
12644                          "gdb should not stop!\n"));
12645       break;
12646
12647     case bp_exception_master:
12648       /* These should never be enabled.  */
12649       printf_filtered (_("Exception Master Breakpoint: "
12650                          "gdb should not stop!\n"));
12651       break;
12652     }
12653
12654   return PRINT_NOTHING;
12655 }
12656
12657 static void
12658 internal_bkpt_print_mention (struct breakpoint *b)
12659 {
12660   /* Nothing to mention.  These breakpoints are internal.  */
12661 }
12662
12663 /* Virtual table for momentary breakpoints  */
12664
12665 static void
12666 momentary_bkpt_re_set (struct breakpoint *b)
12667 {
12668   /* Keep temporary breakpoints, which can be encountered when we step
12669      over a dlopen call and solib_add is resetting the breakpoints.
12670      Otherwise these should have been blown away via the cleanup chain
12671      or by breakpoint_init_inferior when we rerun the executable.  */
12672 }
12673
12674 static void
12675 momentary_bkpt_check_status (bpstat bs)
12676 {
12677   /* Nothing.  The point of these breakpoints is causing a stop.  */
12678 }
12679
12680 static enum print_stop_action
12681 momentary_bkpt_print_it (bpstat bs)
12682 {
12683   return PRINT_UNKNOWN;
12684 }
12685
12686 static void
12687 momentary_bkpt_print_mention (struct breakpoint *b)
12688 {
12689   /* Nothing to mention.  These breakpoints are internal.  */
12690 }
12691
12692 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12693
12694    It gets cleared already on the removal of the first one of such placed
12695    breakpoints.  This is OK as they get all removed altogether.  */
12696
12697 longjmp_breakpoint::~longjmp_breakpoint ()
12698 {
12699   thread_info *tp = find_thread_global_id (this->thread);
12700
12701   if (tp != NULL)
12702     tp->initiating_frame = null_frame_id;
12703 }
12704
12705 /* Specific methods for probe breakpoints.  */
12706
12707 static int
12708 bkpt_probe_insert_location (struct bp_location *bl)
12709 {
12710   int v = bkpt_insert_location (bl);
12711
12712   if (v == 0)
12713     {
12714       /* The insertion was successful, now let's set the probe's semaphore
12715          if needed.  */
12716       bl->probe.prob->set_semaphore (bl->probe.objfile, bl->gdbarch);
12717     }
12718
12719   return v;
12720 }
12721
12722 static int
12723 bkpt_probe_remove_location (struct bp_location *bl,
12724                             enum remove_bp_reason reason)
12725 {
12726   /* Let's clear the semaphore before removing the location.  */
12727   bl->probe.prob->clear_semaphore (bl->probe.objfile, bl->gdbarch);
12728
12729   return bkpt_remove_location (bl, reason);
12730 }
12731
12732 static void
12733 bkpt_probe_create_sals_from_location (const struct event_location *location,
12734                                       struct linespec_result *canonical,
12735                                       enum bptype type_wanted)
12736 {
12737   struct linespec_sals lsal;
12738
12739   lsal.sals = parse_probes (location, NULL, canonical);
12740   lsal.canonical
12741     = xstrdup (event_location_to_string (canonical->location.get ()));
12742   canonical->lsals.push_back (std::move (lsal));
12743 }
12744
12745 static std::vector<symtab_and_line>
12746 bkpt_probe_decode_location (struct breakpoint *b,
12747                             const struct event_location *location,
12748                             struct program_space *search_pspace)
12749 {
12750   std::vector<symtab_and_line> sals = parse_probes (location, search_pspace, NULL);
12751   if (sals.empty ())
12752     error (_("probe not found"));
12753   return sals;
12754 }
12755
12756 /* The breakpoint_ops structure to be used in tracepoints.  */
12757
12758 static void
12759 tracepoint_re_set (struct breakpoint *b)
12760 {
12761   breakpoint_re_set_default (b);
12762 }
12763
12764 static int
12765 tracepoint_breakpoint_hit (const struct bp_location *bl,
12766                            const address_space *aspace, CORE_ADDR bp_addr,
12767                            const struct target_waitstatus *ws)
12768 {
12769   /* By definition, the inferior does not report stops at
12770      tracepoints.  */
12771   return 0;
12772 }
12773
12774 static void
12775 tracepoint_print_one_detail (const struct breakpoint *self,
12776                              struct ui_out *uiout)
12777 {
12778   struct tracepoint *tp = (struct tracepoint *) self;
12779   if (!tp->static_trace_marker_id.empty ())
12780     {
12781       gdb_assert (self->type == bp_static_tracepoint);
12782
12783       uiout->text ("\tmarker id is ");
12784       uiout->field_string ("static-tracepoint-marker-string-id",
12785                            tp->static_trace_marker_id);
12786       uiout->text ("\n");
12787     }
12788 }
12789
12790 static void
12791 tracepoint_print_mention (struct breakpoint *b)
12792 {
12793   if (current_uiout->is_mi_like_p ())
12794     return;
12795
12796   switch (b->type)
12797     {
12798     case bp_tracepoint:
12799       printf_filtered (_("Tracepoint"));
12800       printf_filtered (_(" %d"), b->number);
12801       break;
12802     case bp_fast_tracepoint:
12803       printf_filtered (_("Fast tracepoint"));
12804       printf_filtered (_(" %d"), b->number);
12805       break;
12806     case bp_static_tracepoint:
12807       printf_filtered (_("Static tracepoint"));
12808       printf_filtered (_(" %d"), b->number);
12809       break;
12810     default:
12811       internal_error (__FILE__, __LINE__,
12812                       _("unhandled tracepoint type %d"), (int) b->type);
12813     }
12814
12815   say_where (b);
12816 }
12817
12818 static void
12819 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
12820 {
12821   struct tracepoint *tp = (struct tracepoint *) self;
12822
12823   if (self->type == bp_fast_tracepoint)
12824     fprintf_unfiltered (fp, "ftrace");
12825   else if (self->type == bp_static_tracepoint)
12826     fprintf_unfiltered (fp, "strace");
12827   else if (self->type == bp_tracepoint)
12828     fprintf_unfiltered (fp, "trace");
12829   else
12830     internal_error (__FILE__, __LINE__,
12831                     _("unhandled tracepoint type %d"), (int) self->type);
12832
12833   fprintf_unfiltered (fp, " %s",
12834                       event_location_to_string (self->location.get ()));
12835   print_recreate_thread (self, fp);
12836
12837   if (tp->pass_count)
12838     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
12839 }
12840
12841 static void
12842 tracepoint_create_sals_from_location (const struct event_location *location,
12843                                       struct linespec_result *canonical,
12844                                       enum bptype type_wanted)
12845 {
12846   create_sals_from_location_default (location, canonical, type_wanted);
12847 }
12848
12849 static void
12850 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12851                                    struct linespec_result *canonical,
12852                                    gdb::unique_xmalloc_ptr<char> cond_string,
12853                                    gdb::unique_xmalloc_ptr<char> extra_string,
12854                                    enum bptype type_wanted,
12855                                    enum bpdisp disposition,
12856                                    int thread,
12857                                    int task, int ignore_count,
12858                                    const struct breakpoint_ops *ops,
12859                                    int from_tty, int enabled,
12860                                    int internal, unsigned flags)
12861 {
12862   create_breakpoints_sal_default (gdbarch, canonical,
12863                                   std::move (cond_string),
12864                                   std::move (extra_string),
12865                                   type_wanted,
12866                                   disposition, thread, task,
12867                                   ignore_count, ops, from_tty,
12868                                   enabled, internal, flags);
12869 }
12870
12871 static std::vector<symtab_and_line>
12872 tracepoint_decode_location (struct breakpoint *b,
12873                             const struct event_location *location,
12874                             struct program_space *search_pspace)
12875 {
12876   return decode_location_default (b, location, search_pspace);
12877 }
12878
12879 struct breakpoint_ops tracepoint_breakpoint_ops;
12880
12881 /* The breakpoint_ops structure to be use on tracepoints placed in a
12882    static probe.  */
12883
12884 static void
12885 tracepoint_probe_create_sals_from_location
12886   (const struct event_location *location,
12887    struct linespec_result *canonical,
12888    enum bptype type_wanted)
12889 {
12890   /* We use the same method for breakpoint on probes.  */
12891   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
12892 }
12893
12894 static std::vector<symtab_and_line>
12895 tracepoint_probe_decode_location (struct breakpoint *b,
12896                                   const struct event_location *location,
12897                                   struct program_space *search_pspace)
12898 {
12899   /* We use the same method for breakpoint on probes.  */
12900   return bkpt_probe_decode_location (b, location, search_pspace);
12901 }
12902
12903 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
12904
12905 /* Dprintf breakpoint_ops methods.  */
12906
12907 static void
12908 dprintf_re_set (struct breakpoint *b)
12909 {
12910   breakpoint_re_set_default (b);
12911
12912   /* extra_string should never be non-NULL for dprintf.  */
12913   gdb_assert (b->extra_string != NULL);
12914
12915   /* 1 - connect to target 1, that can run breakpoint commands.
12916      2 - create a dprintf, which resolves fine.
12917      3 - disconnect from target 1
12918      4 - connect to target 2, that can NOT run breakpoint commands.
12919
12920      After steps #3/#4, you'll want the dprintf command list to
12921      be updated, because target 1 and 2 may well return different
12922      answers for target_can_run_breakpoint_commands().
12923      Given absence of finer grained resetting, we get to do
12924      it all the time.  */
12925   if (b->extra_string != NULL)
12926     update_dprintf_command_list (b);
12927 }
12928
12929 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
12930
12931 static void
12932 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12933 {
12934   fprintf_unfiltered (fp, "dprintf %s,%s",
12935                       event_location_to_string (tp->location.get ()),
12936                       tp->extra_string);
12937   print_recreate_thread (tp, fp);
12938 }
12939
12940 /* Implement the "after_condition_true" breakpoint_ops method for
12941    dprintf.
12942
12943    dprintf's are implemented with regular commands in their command
12944    list, but we run the commands here instead of before presenting the
12945    stop to the user, as dprintf's don't actually cause a stop.  This
12946    also makes it so that the commands of multiple dprintfs at the same
12947    address are all handled.  */
12948
12949 static void
12950 dprintf_after_condition_true (struct bpstats *bs)
12951 {
12952   struct bpstats tmp_bs;
12953   struct bpstats *tmp_bs_p = &tmp_bs;
12954
12955   /* dprintf's never cause a stop.  This wasn't set in the
12956      check_status hook instead because that would make the dprintf's
12957      condition not be evaluated.  */
12958   bs->stop = 0;
12959
12960   /* Run the command list here.  Take ownership of it instead of
12961      copying.  We never want these commands to run later in
12962      bpstat_do_actions, if a breakpoint that causes a stop happens to
12963      be set at same address as this dprintf, or even if running the
12964      commands here throws.  */
12965   tmp_bs.commands = bs->commands;
12966   bs->commands = NULL;
12967
12968   bpstat_do_actions_1 (&tmp_bs_p);
12969
12970   /* 'tmp_bs.commands' will usually be NULL by now, but
12971      bpstat_do_actions_1 may return early without processing the whole
12972      list.  */
12973 }
12974
12975 /* The breakpoint_ops structure to be used on static tracepoints with
12976    markers (`-m').  */
12977
12978 static void
12979 strace_marker_create_sals_from_location (const struct event_location *location,
12980                                          struct linespec_result *canonical,
12981                                          enum bptype type_wanted)
12982 {
12983   struct linespec_sals lsal;
12984   const char *arg_start, *arg;
12985
12986   arg = arg_start = get_linespec_location (location)->spec_string;
12987   lsal.sals = decode_static_tracepoint_spec (&arg);
12988
12989   std::string str (arg_start, arg - arg_start);
12990   const char *ptr = str.c_str ();
12991   canonical->location
12992     = new_linespec_location (&ptr, symbol_name_match_type::FULL);
12993
12994   lsal.canonical
12995     = xstrdup (event_location_to_string (canonical->location.get ()));
12996   canonical->lsals.push_back (std::move (lsal));
12997 }
12998
12999 static void
13000 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13001                                       struct linespec_result *canonical,
13002                                       gdb::unique_xmalloc_ptr<char> cond_string,
13003                                       gdb::unique_xmalloc_ptr<char> extra_string,
13004                                       enum bptype type_wanted,
13005                                       enum bpdisp disposition,
13006                                       int thread,
13007                                       int task, int ignore_count,
13008                                       const struct breakpoint_ops *ops,
13009                                       int from_tty, int enabled,
13010                                       int internal, unsigned flags)
13011 {
13012   const linespec_sals &lsal = canonical->lsals[0];
13013
13014   /* If the user is creating a static tracepoint by marker id
13015      (strace -m MARKER_ID), then store the sals index, so that
13016      breakpoint_re_set can try to match up which of the newly
13017      found markers corresponds to this one, and, don't try to
13018      expand multiple locations for each sal, given than SALS
13019      already should contain all sals for MARKER_ID.  */
13020
13021   for (size_t i = 0; i < lsal.sals.size (); i++)
13022     {
13023       event_location_up location
13024         = copy_event_location (canonical->location.get ());
13025
13026       std::unique_ptr<tracepoint> tp (new tracepoint ());
13027       init_breakpoint_sal (tp.get (), gdbarch, lsal.sals[i],
13028                            std::move (location), NULL,
13029                            std::move (cond_string),
13030                            std::move (extra_string),
13031                            type_wanted, disposition,
13032                            thread, task, ignore_count, ops,
13033                            from_tty, enabled, internal, flags,
13034                            canonical->special_display);
13035       /* Given that its possible to have multiple markers with
13036          the same string id, if the user is creating a static
13037          tracepoint by marker id ("strace -m MARKER_ID"), then
13038          store the sals index, so that breakpoint_re_set can
13039          try to match up which of the newly found markers
13040          corresponds to this one  */
13041       tp->static_trace_marker_id_idx = i;
13042
13043       install_breakpoint (internal, std::move (tp), 0);
13044     }
13045 }
13046
13047 static std::vector<symtab_and_line>
13048 strace_marker_decode_location (struct breakpoint *b,
13049                                const struct event_location *location,
13050                                struct program_space *search_pspace)
13051 {
13052   struct tracepoint *tp = (struct tracepoint *) b;
13053   const char *s = get_linespec_location (location)->spec_string;
13054
13055   std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
13056   if (sals.size () > tp->static_trace_marker_id_idx)
13057     {
13058       sals[0] = sals[tp->static_trace_marker_id_idx];
13059       sals.resize (1);
13060       return sals;
13061     }
13062   else
13063     error (_("marker %s not found"), tp->static_trace_marker_id.c_str ());
13064 }
13065
13066 static struct breakpoint_ops strace_marker_breakpoint_ops;
13067
13068 static int
13069 strace_marker_p (struct breakpoint *b)
13070 {
13071   return b->ops == &strace_marker_breakpoint_ops;
13072 }
13073
13074 /* Delete a breakpoint and clean up all traces of it in the data
13075    structures.  */
13076
13077 void
13078 delete_breakpoint (struct breakpoint *bpt)
13079 {
13080   struct breakpoint *b;
13081
13082   gdb_assert (bpt != NULL);
13083
13084   /* Has this bp already been deleted?  This can happen because
13085      multiple lists can hold pointers to bp's.  bpstat lists are
13086      especial culprits.
13087
13088      One example of this happening is a watchpoint's scope bp.  When
13089      the scope bp triggers, we notice that the watchpoint is out of
13090      scope, and delete it.  We also delete its scope bp.  But the
13091      scope bp is marked "auto-deleting", and is already on a bpstat.
13092      That bpstat is then checked for auto-deleting bp's, which are
13093      deleted.
13094
13095      A real solution to this problem might involve reference counts in
13096      bp's, and/or giving them pointers back to their referencing
13097      bpstat's, and teaching delete_breakpoint to only free a bp's
13098      storage when no more references were extent.  A cheaper bandaid
13099      was chosen.  */
13100   if (bpt->type == bp_none)
13101     return;
13102
13103   /* At least avoid this stale reference until the reference counting
13104      of breakpoints gets resolved.  */
13105   if (bpt->related_breakpoint != bpt)
13106     {
13107       struct breakpoint *related;
13108       struct watchpoint *w;
13109
13110       if (bpt->type == bp_watchpoint_scope)
13111         w = (struct watchpoint *) bpt->related_breakpoint;
13112       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13113         w = (struct watchpoint *) bpt;
13114       else
13115         w = NULL;
13116       if (w != NULL)
13117         watchpoint_del_at_next_stop (w);
13118
13119       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13120       for (related = bpt; related->related_breakpoint != bpt;
13121            related = related->related_breakpoint);
13122       related->related_breakpoint = bpt->related_breakpoint;
13123       bpt->related_breakpoint = bpt;
13124     }
13125
13126   /* watch_command_1 creates a watchpoint but only sets its number if
13127      update_watchpoint succeeds in creating its bp_locations.  If there's
13128      a problem in that process, we'll be asked to delete the half-created
13129      watchpoint.  In that case, don't announce the deletion.  */
13130   if (bpt->number)
13131     gdb::observers::breakpoint_deleted.notify (bpt);
13132
13133   if (breakpoint_chain == bpt)
13134     breakpoint_chain = bpt->next;
13135
13136   ALL_BREAKPOINTS (b)
13137     if (b->next == bpt)
13138     {
13139       b->next = bpt->next;
13140       break;
13141     }
13142
13143   /* Be sure no bpstat's are pointing at the breakpoint after it's
13144      been freed.  */
13145   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13146      in all threads for now.  Note that we cannot just remove bpstats
13147      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13148      commands are associated with the bpstat; if we remove it here,
13149      then the later call to bpstat_do_actions (&stop_bpstat); in
13150      event-top.c won't do anything, and temporary breakpoints with
13151      commands won't work.  */
13152
13153   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13154
13155   /* Now that breakpoint is removed from breakpoint list, update the
13156      global location list.  This will remove locations that used to
13157      belong to this breakpoint.  Do this before freeing the breakpoint
13158      itself, since remove_breakpoint looks at location's owner.  It
13159      might be better design to have location completely
13160      self-contained, but it's not the case now.  */
13161   update_global_location_list (UGLL_DONT_INSERT);
13162
13163   /* On the chance that someone will soon try again to delete this
13164      same bp, we mark it as deleted before freeing its storage.  */
13165   bpt->type = bp_none;
13166   delete bpt;
13167 }
13168
13169 /* Iterator function to call a user-provided callback function once
13170    for each of B and its related breakpoints.  */
13171
13172 static void
13173 iterate_over_related_breakpoints (struct breakpoint *b,
13174                                   gdb::function_view<void (breakpoint *)> function)
13175 {
13176   struct breakpoint *related;
13177
13178   related = b;
13179   do
13180     {
13181       struct breakpoint *next;
13182
13183       /* FUNCTION may delete RELATED.  */
13184       next = related->related_breakpoint;
13185
13186       if (next == related)
13187         {
13188           /* RELATED is the last ring entry.  */
13189           function (related);
13190
13191           /* FUNCTION may have deleted it, so we'd never reach back to
13192              B.  There's nothing left to do anyway, so just break
13193              out.  */
13194           break;
13195         }
13196       else
13197         function (related);
13198
13199       related = next;
13200     }
13201   while (related != b);
13202 }
13203
13204 static void
13205 delete_command (const char *arg, int from_tty)
13206 {
13207   struct breakpoint *b, *b_tmp;
13208
13209   dont_repeat ();
13210
13211   if (arg == 0)
13212     {
13213       int breaks_to_delete = 0;
13214
13215       /* Delete all breakpoints if no argument.  Do not delete
13216          internal breakpoints, these have to be deleted with an
13217          explicit breakpoint number argument.  */
13218       ALL_BREAKPOINTS (b)
13219         if (user_breakpoint_p (b))
13220           {
13221             breaks_to_delete = 1;
13222             break;
13223           }
13224
13225       /* Ask user only if there are some breakpoints to delete.  */
13226       if (!from_tty
13227           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13228         {
13229           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13230             if (user_breakpoint_p (b))
13231               delete_breakpoint (b);
13232         }
13233     }
13234   else
13235     map_breakpoint_numbers
13236       (arg, [&] (breakpoint *br)
13237        {
13238          iterate_over_related_breakpoints (br, delete_breakpoint);
13239        });
13240 }
13241
13242 /* Return true if all locations of B bound to PSPACE are pending.  If
13243    PSPACE is NULL, all locations of all program spaces are
13244    considered.  */
13245
13246 static int
13247 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13248 {
13249   struct bp_location *loc;
13250
13251   for (loc = b->loc; loc != NULL; loc = loc->next)
13252     if ((pspace == NULL
13253          || loc->pspace == pspace)
13254         && !loc->shlib_disabled
13255         && !loc->pspace->executing_startup)
13256       return 0;
13257   return 1;
13258 }
13259
13260 /* Subroutine of update_breakpoint_locations to simplify it.
13261    Return non-zero if multiple fns in list LOC have the same name.
13262    Null names are ignored.  */
13263
13264 static int
13265 ambiguous_names_p (struct bp_location *loc)
13266 {
13267   struct bp_location *l;
13268   htab_t htab = htab_create_alloc (13, htab_hash_string, streq_hash, NULL,
13269                                    xcalloc, xfree);
13270
13271   for (l = loc; l != NULL; l = l->next)
13272     {
13273       const char **slot;
13274       const char *name = l->function_name;
13275
13276       /* Allow for some names to be NULL, ignore them.  */
13277       if (name == NULL)
13278         continue;
13279
13280       slot = (const char **) htab_find_slot (htab, (const void *) name,
13281                                              INSERT);
13282       /* NOTE: We can assume slot != NULL here because xcalloc never
13283          returns NULL.  */
13284       if (*slot != NULL)
13285         {
13286           htab_delete (htab);
13287           return 1;
13288         }
13289       *slot = name;
13290     }
13291
13292   htab_delete (htab);
13293   return 0;
13294 }
13295
13296 /* When symbols change, it probably means the sources changed as well,
13297    and it might mean the static tracepoint markers are no longer at
13298    the same address or line numbers they used to be at last we
13299    checked.  Losing your static tracepoints whenever you rebuild is
13300    undesirable.  This function tries to resync/rematch gdb static
13301    tracepoints with the markers on the target, for static tracepoints
13302    that have not been set by marker id.  Static tracepoint that have
13303    been set by marker id are reset by marker id in breakpoint_re_set.
13304    The heuristic is:
13305
13306    1) For a tracepoint set at a specific address, look for a marker at
13307    the old PC.  If one is found there, assume to be the same marker.
13308    If the name / string id of the marker found is different from the
13309    previous known name, assume that means the user renamed the marker
13310    in the sources, and output a warning.
13311
13312    2) For a tracepoint set at a given line number, look for a marker
13313    at the new address of the old line number.  If one is found there,
13314    assume to be the same marker.  If the name / string id of the
13315    marker found is different from the previous known name, assume that
13316    means the user renamed the marker in the sources, and output a
13317    warning.
13318
13319    3) If a marker is no longer found at the same address or line, it
13320    may mean the marker no longer exists.  But it may also just mean
13321    the code changed a bit.  Maybe the user added a few lines of code
13322    that made the marker move up or down (in line number terms).  Ask
13323    the target for info about the marker with the string id as we knew
13324    it.  If found, update line number and address in the matching
13325    static tracepoint.  This will get confused if there's more than one
13326    marker with the same ID (possible in UST, although unadvised
13327    precisely because it confuses tools).  */
13328
13329 static struct symtab_and_line
13330 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13331 {
13332   struct tracepoint *tp = (struct tracepoint *) b;
13333   struct static_tracepoint_marker marker;
13334   CORE_ADDR pc;
13335
13336   pc = sal.pc;
13337   if (sal.line)
13338     find_line_pc (sal.symtab, sal.line, &pc);
13339
13340   if (target_static_tracepoint_marker_at (pc, &marker))
13341     {
13342       if (tp->static_trace_marker_id != marker.str_id)
13343         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13344                  b->number, tp->static_trace_marker_id.c_str (),
13345                  marker.str_id.c_str ());
13346
13347       tp->static_trace_marker_id = std::move (marker.str_id);
13348
13349       return sal;
13350     }
13351
13352   /* Old marker wasn't found on target at lineno.  Try looking it up
13353      by string ID.  */
13354   if (!sal.explicit_pc
13355       && sal.line != 0
13356       && sal.symtab != NULL
13357       && !tp->static_trace_marker_id.empty ())
13358     {
13359       std::vector<static_tracepoint_marker> markers
13360         = target_static_tracepoint_markers_by_strid
13361             (tp->static_trace_marker_id.c_str ());
13362
13363       if (!markers.empty ())
13364         {
13365           struct symbol *sym;
13366           struct static_tracepoint_marker *tpmarker;
13367           struct ui_out *uiout = current_uiout;
13368           struct explicit_location explicit_loc;
13369
13370           tpmarker = &markers[0];
13371
13372           tp->static_trace_marker_id = std::move (tpmarker->str_id);
13373
13374           warning (_("marker for static tracepoint %d (%s) not "
13375                      "found at previous line number"),
13376                    b->number, tp->static_trace_marker_id.c_str ());
13377
13378           symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
13379           sym = find_pc_sect_function (tpmarker->address, NULL);
13380           uiout->text ("Now in ");
13381           if (sym)
13382             {
13383               uiout->field_string ("func", SYMBOL_PRINT_NAME (sym),
13384                                    ui_out_style_kind::FUNCTION);
13385               uiout->text (" at ");
13386             }
13387           uiout->field_string ("file",
13388                                symtab_to_filename_for_display (sal2.symtab),
13389                                ui_out_style_kind::FILE);
13390           uiout->text (":");
13391
13392           if (uiout->is_mi_like_p ())
13393             {
13394               const char *fullname = symtab_to_fullname (sal2.symtab);
13395
13396               uiout->field_string ("fullname", fullname);
13397             }
13398
13399           uiout->field_int ("line", sal2.line);
13400           uiout->text ("\n");
13401
13402           b->loc->line_number = sal2.line;
13403           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13404
13405           b->location.reset (NULL);
13406           initialize_explicit_location (&explicit_loc);
13407           explicit_loc.source_filename
13408             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
13409           explicit_loc.line_offset.offset = b->loc->line_number;
13410           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
13411           b->location = new_explicit_location (&explicit_loc);
13412
13413           /* Might be nice to check if function changed, and warn if
13414              so.  */
13415         }
13416     }
13417   return sal;
13418 }
13419
13420 /* Returns 1 iff locations A and B are sufficiently same that
13421    we don't need to report breakpoint as changed.  */
13422
13423 static int
13424 locations_are_equal (struct bp_location *a, struct bp_location *b)
13425 {
13426   while (a && b)
13427     {
13428       if (a->address != b->address)
13429         return 0;
13430
13431       if (a->shlib_disabled != b->shlib_disabled)
13432         return 0;
13433
13434       if (a->enabled != b->enabled)
13435         return 0;
13436
13437       a = a->next;
13438       b = b->next;
13439     }
13440
13441   if ((a == NULL) != (b == NULL))
13442     return 0;
13443
13444   return 1;
13445 }
13446
13447 /* Split all locations of B that are bound to PSPACE out of B's
13448    location list to a separate list and return that list's head.  If
13449    PSPACE is NULL, hoist out all locations of B.  */
13450
13451 static struct bp_location *
13452 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
13453 {
13454   struct bp_location head;
13455   struct bp_location *i = b->loc;
13456   struct bp_location **i_link = &b->loc;
13457   struct bp_location *hoisted = &head;
13458
13459   if (pspace == NULL)
13460     {
13461       i = b->loc;
13462       b->loc = NULL;
13463       return i;
13464     }
13465
13466   head.next = NULL;
13467
13468   while (i != NULL)
13469     {
13470       if (i->pspace == pspace)
13471         {
13472           *i_link = i->next;
13473           i->next = NULL;
13474           hoisted->next = i;
13475           hoisted = i;
13476         }
13477       else
13478         i_link = &i->next;
13479       i = *i_link;
13480     }
13481
13482   return head.next;
13483 }
13484
13485 /* Create new breakpoint locations for B (a hardware or software
13486    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
13487    zero, then B is a ranged breakpoint.  Only recreates locations for
13488    FILTER_PSPACE.  Locations of other program spaces are left
13489    untouched.  */
13490
13491 void
13492 update_breakpoint_locations (struct breakpoint *b,
13493                              struct program_space *filter_pspace,
13494                              gdb::array_view<const symtab_and_line> sals,
13495                              gdb::array_view<const symtab_and_line> sals_end)
13496 {
13497   struct bp_location *existing_locations;
13498
13499   if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
13500     {
13501       /* Ranged breakpoints have only one start location and one end
13502          location.  */
13503       b->enable_state = bp_disabled;
13504       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13505                            "multiple locations found\n"),
13506                          b->number);
13507       return;
13508     }
13509
13510   /* If there's no new locations, and all existing locations are
13511      pending, don't do anything.  This optimizes the common case where
13512      all locations are in the same shared library, that was unloaded.
13513      We'd like to retain the location, so that when the library is
13514      loaded again, we don't loose the enabled/disabled status of the
13515      individual locations.  */
13516   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
13517     return;
13518
13519   existing_locations = hoist_existing_locations (b, filter_pspace);
13520
13521   for (const auto &sal : sals)
13522     {
13523       struct bp_location *new_loc;
13524
13525       switch_to_program_space_and_thread (sal.pspace);
13526
13527       new_loc = add_location_to_breakpoint (b, &sal);
13528
13529       /* Reparse conditions, they might contain references to the
13530          old symtab.  */
13531       if (b->cond_string != NULL)
13532         {
13533           const char *s;
13534
13535           s = b->cond_string;
13536           TRY
13537             {
13538               new_loc->cond = parse_exp_1 (&s, sal.pc,
13539                                            block_for_pc (sal.pc),
13540                                            0);
13541             }
13542           CATCH (e, RETURN_MASK_ERROR)
13543             {
13544               warning (_("failed to reevaluate condition "
13545                          "for breakpoint %d: %s"), 
13546                        b->number, e.message);
13547               new_loc->enabled = 0;
13548             }
13549           END_CATCH
13550         }
13551
13552       if (!sals_end.empty ())
13553         {
13554           CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13555
13556           new_loc->length = end - sals[0].pc + 1;
13557         }
13558     }
13559
13560   /* If possible, carry over 'disable' status from existing
13561      breakpoints.  */
13562   {
13563     struct bp_location *e = existing_locations;
13564     /* If there are multiple breakpoints with the same function name,
13565        e.g. for inline functions, comparing function names won't work.
13566        Instead compare pc addresses; this is just a heuristic as things
13567        may have moved, but in practice it gives the correct answer
13568        often enough until a better solution is found.  */
13569     int have_ambiguous_names = ambiguous_names_p (b->loc);
13570
13571     for (; e; e = e->next)
13572       {
13573         if (!e->enabled && e->function_name)
13574           {
13575             struct bp_location *l = b->loc;
13576             if (have_ambiguous_names)
13577               {
13578                 for (; l; l = l->next)
13579                   if (breakpoint_locations_match (e, l))
13580                     {
13581                       l->enabled = 0;
13582                       break;
13583                     }
13584               }
13585             else
13586               {
13587                 for (; l; l = l->next)
13588                   if (l->function_name
13589                       && strcmp (e->function_name, l->function_name) == 0)
13590                     {
13591                       l->enabled = 0;
13592                       break;
13593                     }
13594               }
13595           }
13596       }
13597   }
13598
13599   if (!locations_are_equal (existing_locations, b->loc))
13600     gdb::observers::breakpoint_modified.notify (b);
13601 }
13602
13603 /* Find the SaL locations corresponding to the given LOCATION.
13604    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13605
13606 static std::vector<symtab_and_line>
13607 location_to_sals (struct breakpoint *b, struct event_location *location,
13608                   struct program_space *search_pspace, int *found)
13609 {
13610   struct gdb_exception exception = exception_none;
13611
13612   gdb_assert (b->ops != NULL);
13613
13614   std::vector<symtab_and_line> sals;
13615
13616   TRY
13617     {
13618       sals = b->ops->decode_location (b, location, search_pspace);
13619     }
13620   CATCH (e, RETURN_MASK_ERROR)
13621     {
13622       int not_found_and_ok = 0;
13623
13624       exception = e;
13625
13626       /* For pending breakpoints, it's expected that parsing will
13627          fail until the right shared library is loaded.  User has
13628          already told to create pending breakpoints and don't need
13629          extra messages.  If breakpoint is in bp_shlib_disabled
13630          state, then user already saw the message about that
13631          breakpoint being disabled, and don't want to see more
13632          errors.  */
13633       if (e.error == NOT_FOUND_ERROR
13634           && (b->condition_not_parsed
13635               || (b->loc != NULL
13636                   && search_pspace != NULL
13637                   && b->loc->pspace != search_pspace)
13638               || (b->loc && b->loc->shlib_disabled)
13639               || (b->loc && b->loc->pspace->executing_startup)
13640               || b->enable_state == bp_disabled))
13641         not_found_and_ok = 1;
13642
13643       if (!not_found_and_ok)
13644         {
13645           /* We surely don't want to warn about the same breakpoint
13646              10 times.  One solution, implemented here, is disable
13647              the breakpoint on error.  Another solution would be to
13648              have separate 'warning emitted' flag.  Since this
13649              happens only when a binary has changed, I don't know
13650              which approach is better.  */
13651           b->enable_state = bp_disabled;
13652           throw_exception (e);
13653         }
13654     }
13655   END_CATCH
13656
13657   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13658     {
13659       for (auto &sal : sals)
13660         resolve_sal_pc (&sal);
13661       if (b->condition_not_parsed && b->extra_string != NULL)
13662         {
13663           char *cond_string, *extra_string;
13664           int thread, task;
13665
13666           find_condition_and_thread (b->extra_string, sals[0].pc,
13667                                      &cond_string, &thread, &task,
13668                                      &extra_string);
13669           gdb_assert (b->cond_string == NULL);
13670           if (cond_string)
13671             b->cond_string = cond_string;
13672           b->thread = thread;
13673           b->task = task;
13674           if (extra_string)
13675             {
13676               xfree (b->extra_string);
13677               b->extra_string = extra_string;
13678             }
13679           b->condition_not_parsed = 0;
13680         }
13681
13682       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13683         sals[0] = update_static_tracepoint (b, sals[0]);
13684
13685       *found = 1;
13686     }
13687   else
13688     *found = 0;
13689
13690   return sals;
13691 }
13692
13693 /* The default re_set method, for typical hardware or software
13694    breakpoints.  Reevaluate the breakpoint and recreate its
13695    locations.  */
13696
13697 static void
13698 breakpoint_re_set_default (struct breakpoint *b)
13699 {
13700   struct program_space *filter_pspace = current_program_space;
13701   std::vector<symtab_and_line> expanded, expanded_end;
13702
13703   int found;
13704   std::vector<symtab_and_line> sals = location_to_sals (b, b->location.get (),
13705                                                         filter_pspace, &found);
13706   if (found)
13707     expanded = std::move (sals);
13708
13709   if (b->location_range_end != NULL)
13710     {
13711       std::vector<symtab_and_line> sals_end
13712         = location_to_sals (b, b->location_range_end.get (),
13713                             filter_pspace, &found);
13714       if (found)
13715         expanded_end = std::move (sals_end);
13716     }
13717
13718   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
13719 }
13720
13721 /* Default method for creating SALs from an address string.  It basically
13722    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13723
13724 static void
13725 create_sals_from_location_default (const struct event_location *location,
13726                                    struct linespec_result *canonical,
13727                                    enum bptype type_wanted)
13728 {
13729   parse_breakpoint_sals (location, canonical);
13730 }
13731
13732 /* Call create_breakpoints_sal for the given arguments.  This is the default
13733    function for the `create_breakpoints_sal' method of
13734    breakpoint_ops.  */
13735
13736 static void
13737 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13738                                 struct linespec_result *canonical,
13739                                 gdb::unique_xmalloc_ptr<char> cond_string,
13740                                 gdb::unique_xmalloc_ptr<char> extra_string,
13741                                 enum bptype type_wanted,
13742                                 enum bpdisp disposition,
13743                                 int thread,
13744                                 int task, int ignore_count,
13745                                 const struct breakpoint_ops *ops,
13746                                 int from_tty, int enabled,
13747                                 int internal, unsigned flags)
13748 {
13749   create_breakpoints_sal (gdbarch, canonical,
13750                           std::move (cond_string),
13751                           std::move (extra_string),
13752                           type_wanted, disposition,
13753                           thread, task, ignore_count, ops, from_tty,
13754                           enabled, internal, flags);
13755 }
13756
13757 /* Decode the line represented by S by calling decode_line_full.  This is the
13758    default function for the `decode_location' method of breakpoint_ops.  */
13759
13760 static std::vector<symtab_and_line>
13761 decode_location_default (struct breakpoint *b,
13762                          const struct event_location *location,
13763                          struct program_space *search_pspace)
13764 {
13765   struct linespec_result canonical;
13766
13767   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
13768                     (struct symtab *) NULL, 0,
13769                     &canonical, multiple_symbols_all,
13770                     b->filter);
13771
13772   /* We should get 0 or 1 resulting SALs.  */
13773   gdb_assert (canonical.lsals.size () < 2);
13774
13775   if (!canonical.lsals.empty ())
13776     {
13777       const linespec_sals &lsal = canonical.lsals[0];
13778       return std::move (lsal.sals);
13779     }
13780   return {};
13781 }
13782
13783 /* Reset a breakpoint.  */
13784
13785 static void
13786 breakpoint_re_set_one (breakpoint *b)
13787 {
13788   input_radix = b->input_radix;
13789   set_language (b->language);
13790
13791   b->ops->re_set (b);
13792 }
13793
13794 /* Re-set breakpoint locations for the current program space.
13795    Locations bound to other program spaces are left untouched.  */
13796
13797 void
13798 breakpoint_re_set (void)
13799 {
13800   struct breakpoint *b, *b_tmp;
13801
13802   {
13803     scoped_restore_current_language save_language;
13804     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
13805     scoped_restore_current_pspace_and_thread restore_pspace_thread;
13806
13807     /* breakpoint_re_set_one sets the current_language to the language
13808        of the breakpoint it is resetting (see prepare_re_set_context)
13809        before re-evaluating the breakpoint's location.  This change can
13810        unfortunately get undone by accident if the language_mode is set
13811        to auto, and we either switch frames, or more likely in this context,
13812        we select the current frame.
13813
13814        We prevent this by temporarily turning the language_mode to
13815        language_mode_manual.  We restore it once all breakpoints
13816        have been reset.  */
13817     scoped_restore save_language_mode = make_scoped_restore (&language_mode);
13818     language_mode = language_mode_manual;
13819
13820     /* Note: we must not try to insert locations until after all
13821        breakpoints have been re-set.  Otherwise, e.g., when re-setting
13822        breakpoint 1, we'd insert the locations of breakpoint 2, which
13823        hadn't been re-set yet, and thus may have stale locations.  */
13824
13825     ALL_BREAKPOINTS_SAFE (b, b_tmp)
13826       {
13827         TRY
13828           {
13829             breakpoint_re_set_one (b);
13830           }
13831         CATCH (ex, RETURN_MASK_ALL)
13832           {
13833             exception_fprintf (gdb_stderr, ex,
13834                                "Error in re-setting breakpoint %d: ",
13835                                b->number);
13836           }
13837         END_CATCH
13838       }
13839
13840     jit_breakpoint_re_set ();
13841   }
13842
13843   create_overlay_event_breakpoint ();
13844   create_longjmp_master_breakpoint ();
13845   create_std_terminate_master_breakpoint ();
13846   create_exception_master_breakpoint ();
13847
13848   /* Now we can insert.  */
13849   update_global_location_list (UGLL_MAY_INSERT);
13850 }
13851 \f
13852 /* Reset the thread number of this breakpoint:
13853
13854    - If the breakpoint is for all threads, leave it as-is.
13855    - Else, reset it to the current thread for inferior_ptid.  */
13856 void
13857 breakpoint_re_set_thread (struct breakpoint *b)
13858 {
13859   if (b->thread != -1)
13860     {
13861       b->thread = inferior_thread ()->global_num;
13862
13863       /* We're being called after following a fork.  The new fork is
13864          selected as current, and unless this was a vfork will have a
13865          different program space from the original thread.  Reset that
13866          as well.  */
13867       b->loc->pspace = current_program_space;
13868     }
13869 }
13870
13871 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13872    If from_tty is nonzero, it prints a message to that effect,
13873    which ends with a period (no newline).  */
13874
13875 void
13876 set_ignore_count (int bptnum, int count, int from_tty)
13877 {
13878   struct breakpoint *b;
13879
13880   if (count < 0)
13881     count = 0;
13882
13883   ALL_BREAKPOINTS (b)
13884     if (b->number == bptnum)
13885     {
13886       if (is_tracepoint (b))
13887         {
13888           if (from_tty && count != 0)
13889             printf_filtered (_("Ignore count ignored for tracepoint %d."),
13890                              bptnum);
13891           return;
13892         }
13893       
13894       b->ignore_count = count;
13895       if (from_tty)
13896         {
13897           if (count == 0)
13898             printf_filtered (_("Will stop next time "
13899                                "breakpoint %d is reached."),
13900                              bptnum);
13901           else if (count == 1)
13902             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
13903                              bptnum);
13904           else
13905             printf_filtered (_("Will ignore next %d "
13906                                "crossings of breakpoint %d."),
13907                              count, bptnum);
13908         }
13909       gdb::observers::breakpoint_modified.notify (b);
13910       return;
13911     }
13912
13913   error (_("No breakpoint number %d."), bptnum);
13914 }
13915
13916 /* Command to set ignore-count of breakpoint N to COUNT.  */
13917
13918 static void
13919 ignore_command (const char *args, int from_tty)
13920 {
13921   const char *p = args;
13922   int num;
13923
13924   if (p == 0)
13925     error_no_arg (_("a breakpoint number"));
13926
13927   num = get_number (&p);
13928   if (num == 0)
13929     error (_("bad breakpoint number: '%s'"), args);
13930   if (*p == 0)
13931     error (_("Second argument (specified ignore-count) is missing."));
13932
13933   set_ignore_count (num,
13934                     longest_to_int (value_as_long (parse_and_eval (p))),
13935                     from_tty);
13936   if (from_tty)
13937     printf_filtered ("\n");
13938 }
13939 \f
13940
13941 /* Call FUNCTION on each of the breakpoints with numbers in the range
13942    defined by BP_NUM_RANGE (an inclusive range).  */
13943
13944 static void
13945 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
13946                              gdb::function_view<void (breakpoint *)> function)
13947 {
13948   if (bp_num_range.first == 0)
13949     {
13950       warning (_("bad breakpoint number at or near '%d'"),
13951                bp_num_range.first);
13952     }
13953   else
13954     {
13955       struct breakpoint *b, *tmp;
13956
13957       for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
13958         {
13959           bool match = false;
13960
13961           ALL_BREAKPOINTS_SAFE (b, tmp)
13962             if (b->number == i)
13963               {
13964                 match = true;
13965                 function (b);
13966                 break;
13967               }
13968           if (!match)
13969             printf_unfiltered (_("No breakpoint number %d.\n"), i);
13970         }
13971     }
13972 }
13973
13974 /* Call FUNCTION on each of the breakpoints whose numbers are given in
13975    ARGS.  */
13976
13977 static void
13978 map_breakpoint_numbers (const char *args,
13979                         gdb::function_view<void (breakpoint *)> function)
13980 {
13981   if (args == NULL || *args == '\0')
13982     error_no_arg (_("one or more breakpoint numbers"));
13983
13984   number_or_range_parser parser (args);
13985
13986   while (!parser.finished ())
13987     {
13988       int num = parser.get_number ();
13989       map_breakpoint_number_range (std::make_pair (num, num), function);
13990     }
13991 }
13992
13993 /* Return the breakpoint location structure corresponding to the
13994    BP_NUM and LOC_NUM values.  */
13995
13996 static struct bp_location *
13997 find_location_by_number (int bp_num, int loc_num)
13998 {
13999   struct breakpoint *b;
14000
14001   ALL_BREAKPOINTS (b)
14002     if (b->number == bp_num)
14003       {
14004         break;
14005       }
14006
14007   if (!b || b->number != bp_num)
14008     error (_("Bad breakpoint number '%d'"), bp_num);
14009   
14010   if (loc_num == 0)
14011     error (_("Bad breakpoint location number '%d'"), loc_num);
14012
14013   int n = 0;
14014   for (bp_location *loc = b->loc; loc != NULL; loc = loc->next)
14015     if (++n == loc_num)
14016       return loc;
14017
14018   error (_("Bad breakpoint location number '%d'"), loc_num);
14019 }
14020
14021 /* Modes of operation for extract_bp_num.  */
14022 enum class extract_bp_kind
14023 {
14024   /* Extracting a breakpoint number.  */
14025   bp,
14026
14027   /* Extracting a location number.  */
14028   loc,
14029 };
14030
14031 /* Extract a breakpoint or location number (as determined by KIND)
14032    from the string starting at START.  TRAILER is a character which
14033    can be found after the number.  If you don't want a trailer, use
14034    '\0'.  If END_OUT is not NULL, it is set to point after the parsed
14035    string.  This always returns a positive integer.  */
14036
14037 static int
14038 extract_bp_num (extract_bp_kind kind, const char *start,
14039                 int trailer, const char **end_out = NULL)
14040 {
14041   const char *end = start;
14042   int num = get_number_trailer (&end, trailer);
14043   if (num < 0)
14044     error (kind == extract_bp_kind::bp
14045            ? _("Negative breakpoint number '%.*s'")
14046            : _("Negative breakpoint location number '%.*s'"),
14047            int (end - start), start);
14048   if (num == 0)
14049     error (kind == extract_bp_kind::bp
14050            ? _("Bad breakpoint number '%.*s'")
14051            : _("Bad breakpoint location number '%.*s'"),
14052            int (end - start), start);
14053
14054   if (end_out != NULL)
14055     *end_out = end;
14056   return num;
14057 }
14058
14059 /* Extract a breakpoint or location range (as determined by KIND) in
14060    the form NUM1-NUM2 stored at &ARG[arg_offset].  Returns a std::pair
14061    representing the (inclusive) range.  The returned pair's elements
14062    are always positive integers.  */
14063
14064 static std::pair<int, int>
14065 extract_bp_or_bp_range (extract_bp_kind kind,
14066                         const std::string &arg,
14067                         std::string::size_type arg_offset)
14068 {
14069   std::pair<int, int> range;
14070   const char *bp_loc = &arg[arg_offset];
14071   std::string::size_type dash = arg.find ('-', arg_offset);
14072   if (dash != std::string::npos)
14073     {
14074       /* bp_loc is a range (x-z).  */
14075       if (arg.length () == dash + 1)
14076         error (kind == extract_bp_kind::bp
14077                ? _("Bad breakpoint number at or near: '%s'")
14078                : _("Bad breakpoint location number at or near: '%s'"),
14079                bp_loc);
14080
14081       const char *end;
14082       const char *start_first = bp_loc;
14083       const char *start_second = &arg[dash + 1];
14084       range.first = extract_bp_num (kind, start_first, '-');
14085       range.second = extract_bp_num (kind, start_second, '\0', &end);
14086
14087       if (range.first > range.second)
14088         error (kind == extract_bp_kind::bp
14089                ? _("Inverted breakpoint range at '%.*s'")
14090                : _("Inverted breakpoint location range at '%.*s'"),
14091                int (end - start_first), start_first);
14092     }
14093   else
14094     {
14095       /* bp_loc is a single value.  */
14096       range.first = extract_bp_num (kind, bp_loc, '\0');
14097       range.second = range.first;
14098     }
14099   return range;
14100 }
14101
14102 /* Extract the breakpoint/location range specified by ARG.  Returns
14103    the breakpoint range in BP_NUM_RANGE, and the location range in
14104    BP_LOC_RANGE.
14105
14106    ARG may be in any of the following forms:
14107
14108    x     where 'x' is a breakpoint number.
14109    x-y   where 'x' and 'y' specify a breakpoint numbers range.
14110    x.y   where 'x' is a breakpoint number and 'y' a location number.
14111    x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
14112          location number range.
14113 */
14114
14115 static void
14116 extract_bp_number_and_location (const std::string &arg,
14117                                 std::pair<int, int> &bp_num_range,
14118                                 std::pair<int, int> &bp_loc_range)
14119 {
14120   std::string::size_type dot = arg.find ('.');
14121
14122   if (dot != std::string::npos)
14123     {
14124       /* Handle 'x.y' and 'x.y-z' cases.  */
14125
14126       if (arg.length () == dot + 1 || dot == 0)
14127         error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
14128
14129       bp_num_range.first
14130         = extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
14131       bp_num_range.second = bp_num_range.first;
14132
14133       bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
14134                                              arg, dot + 1);
14135     }
14136   else
14137     {
14138       /* Handle x and x-y cases.  */
14139
14140       bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
14141       bp_loc_range.first = 0;
14142       bp_loc_range.second = 0;
14143     }
14144 }
14145
14146 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM.  ENABLE
14147    specifies whether to enable or disable.  */
14148
14149 static void
14150 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
14151 {
14152   struct bp_location *loc = find_location_by_number (bp_num, loc_num);
14153   if (loc != NULL)
14154     {
14155       if (loc->enabled != enable)
14156         {
14157           loc->enabled = enable;
14158           mark_breakpoint_location_modified (loc);
14159         }
14160       if (target_supports_enable_disable_tracepoint ()
14161           && current_trace_status ()->running && loc->owner
14162           && is_tracepoint (loc->owner))
14163         target_disable_tracepoint (loc);
14164     }
14165   update_global_location_list (UGLL_DONT_INSERT);
14166
14167   gdb::observers::breakpoint_modified.notify (loc->owner);
14168 }
14169
14170 /* Enable or disable a range of breakpoint locations.  BP_NUM is the
14171    number of the breakpoint, and BP_LOC_RANGE specifies the
14172    (inclusive) range of location numbers of that breakpoint to
14173    enable/disable.  ENABLE specifies whether to enable or disable the
14174    location.  */
14175
14176 static void
14177 enable_disable_breakpoint_location_range (int bp_num,
14178                                           std::pair<int, int> &bp_loc_range,
14179                                           bool enable)
14180 {
14181   for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
14182     enable_disable_bp_num_loc (bp_num, i, enable);
14183 }
14184
14185 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14186    If from_tty is nonzero, it prints a message to that effect,
14187    which ends with a period (no newline).  */
14188
14189 void
14190 disable_breakpoint (struct breakpoint *bpt)
14191 {
14192   /* Never disable a watchpoint scope breakpoint; we want to
14193      hit them when we leave scope so we can delete both the
14194      watchpoint and its scope breakpoint at that time.  */
14195   if (bpt->type == bp_watchpoint_scope)
14196     return;
14197
14198   bpt->enable_state = bp_disabled;
14199
14200   /* Mark breakpoint locations modified.  */
14201   mark_breakpoint_modified (bpt);
14202
14203   if (target_supports_enable_disable_tracepoint ()
14204       && current_trace_status ()->running && is_tracepoint (bpt))
14205     {
14206       struct bp_location *location;
14207      
14208       for (location = bpt->loc; location; location = location->next)
14209         target_disable_tracepoint (location);
14210     }
14211
14212   update_global_location_list (UGLL_DONT_INSERT);
14213
14214   gdb::observers::breakpoint_modified.notify (bpt);
14215 }
14216
14217 /* Enable or disable the breakpoint(s) or breakpoint location(s)
14218    specified in ARGS.  ARGS may be in any of the formats handled by
14219    extract_bp_number_and_location.  ENABLE specifies whether to enable
14220    or disable the breakpoints/locations.  */
14221
14222 static void
14223 enable_disable_command (const char *args, int from_tty, bool enable)
14224 {
14225   if (args == 0)
14226     {
14227       struct breakpoint *bpt;
14228
14229       ALL_BREAKPOINTS (bpt)
14230         if (user_breakpoint_p (bpt))
14231           {
14232             if (enable)
14233               enable_breakpoint (bpt);
14234             else
14235               disable_breakpoint (bpt);
14236           }
14237     }
14238   else
14239     {
14240       std::string num = extract_arg (&args);
14241
14242       while (!num.empty ())
14243         {
14244           std::pair<int, int> bp_num_range, bp_loc_range;
14245
14246           extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
14247
14248           if (bp_loc_range.first == bp_loc_range.second
14249               && bp_loc_range.first == 0)
14250             {
14251               /* Handle breakpoint ids with formats 'x' or 'x-z'.  */
14252               map_breakpoint_number_range (bp_num_range,
14253                                            enable
14254                                            ? enable_breakpoint
14255                                            : disable_breakpoint);
14256             }
14257           else
14258             {
14259               /* Handle breakpoint ids with formats 'x.y' or
14260                  'x.y-z'.  */
14261               enable_disable_breakpoint_location_range
14262                 (bp_num_range.first, bp_loc_range, enable);
14263             }
14264           num = extract_arg (&args);
14265         }
14266     }
14267 }
14268
14269 /* The disable command disables the specified breakpoints/locations
14270    (or all defined breakpoints) so they're no longer effective in
14271    stopping the inferior.  ARGS may be in any of the forms defined in
14272    extract_bp_number_and_location.  */
14273
14274 static void
14275 disable_command (const char *args, int from_tty)
14276 {
14277   enable_disable_command (args, from_tty, false);
14278 }
14279
14280 static void
14281 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14282                         int count)
14283 {
14284   int target_resources_ok;
14285
14286   if (bpt->type == bp_hardware_breakpoint)
14287     {
14288       int i;
14289       i = hw_breakpoint_used_count ();
14290       target_resources_ok = 
14291         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14292                                             i + 1, 0);
14293       if (target_resources_ok == 0)
14294         error (_("No hardware breakpoint support in the target."));
14295       else if (target_resources_ok < 0)
14296         error (_("Hardware breakpoints used exceeds limit."));
14297     }
14298
14299   if (is_watchpoint (bpt))
14300     {
14301       /* Initialize it just to avoid a GCC false warning.  */
14302       enum enable_state orig_enable_state = bp_disabled;
14303
14304       TRY
14305         {
14306           struct watchpoint *w = (struct watchpoint *) bpt;
14307
14308           orig_enable_state = bpt->enable_state;
14309           bpt->enable_state = bp_enabled;
14310           update_watchpoint (w, 1 /* reparse */);
14311         }
14312       CATCH (e, RETURN_MASK_ALL)
14313         {
14314           bpt->enable_state = orig_enable_state;
14315           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14316                              bpt->number);
14317           return;
14318         }
14319       END_CATCH
14320     }
14321
14322   bpt->enable_state = bp_enabled;
14323
14324   /* Mark breakpoint locations modified.  */
14325   mark_breakpoint_modified (bpt);
14326
14327   if (target_supports_enable_disable_tracepoint ()
14328       && current_trace_status ()->running && is_tracepoint (bpt))
14329     {
14330       struct bp_location *location;
14331
14332       for (location = bpt->loc; location; location = location->next)
14333         target_enable_tracepoint (location);
14334     }
14335
14336   bpt->disposition = disposition;
14337   bpt->enable_count = count;
14338   update_global_location_list (UGLL_MAY_INSERT);
14339
14340   gdb::observers::breakpoint_modified.notify (bpt);
14341 }
14342
14343
14344 void
14345 enable_breakpoint (struct breakpoint *bpt)
14346 {
14347   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14348 }
14349
14350 /* The enable command enables the specified breakpoints/locations (or
14351    all defined breakpoints) so they once again become (or continue to
14352    be) effective in stopping the inferior.  ARGS may be in any of the
14353    forms defined in extract_bp_number_and_location.  */
14354
14355 static void
14356 enable_command (const char *args, int from_tty)
14357 {
14358   enable_disable_command (args, from_tty, true);
14359 }
14360
14361 static void
14362 enable_once_command (const char *args, int from_tty)
14363 {
14364   map_breakpoint_numbers
14365     (args, [&] (breakpoint *b)
14366      {
14367        iterate_over_related_breakpoints
14368          (b, [&] (breakpoint *bpt)
14369           {
14370             enable_breakpoint_disp (bpt, disp_disable, 1);
14371           });
14372      });
14373 }
14374
14375 static void
14376 enable_count_command (const char *args, int from_tty)
14377 {
14378   int count;
14379
14380   if (args == NULL)
14381     error_no_arg (_("hit count"));
14382
14383   count = get_number (&args);
14384
14385   map_breakpoint_numbers
14386     (args, [&] (breakpoint *b)
14387      {
14388        iterate_over_related_breakpoints
14389          (b, [&] (breakpoint *bpt)
14390           {
14391             enable_breakpoint_disp (bpt, disp_disable, count);
14392           });
14393      });
14394 }
14395
14396 static void
14397 enable_delete_command (const char *args, int from_tty)
14398 {
14399   map_breakpoint_numbers
14400     (args, [&] (breakpoint *b)
14401      {
14402        iterate_over_related_breakpoints
14403          (b, [&] (breakpoint *bpt)
14404           {
14405             enable_breakpoint_disp (bpt, disp_del, 1);
14406           });
14407      });
14408 }
14409 \f
14410 static void
14411 set_breakpoint_cmd (const char *args, int from_tty)
14412 {
14413 }
14414
14415 static void
14416 show_breakpoint_cmd (const char *args, int from_tty)
14417 {
14418 }
14419
14420 /* Invalidate last known value of any hardware watchpoint if
14421    the memory which that value represents has been written to by
14422    GDB itself.  */
14423
14424 static void
14425 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14426                                       CORE_ADDR addr, ssize_t len,
14427                                       const bfd_byte *data)
14428 {
14429   struct breakpoint *bp;
14430
14431   ALL_BREAKPOINTS (bp)
14432     if (bp->enable_state == bp_enabled
14433         && bp->type == bp_hardware_watchpoint)
14434       {
14435         struct watchpoint *wp = (struct watchpoint *) bp;
14436
14437         if (wp->val_valid && wp->val != nullptr)
14438           {
14439             struct bp_location *loc;
14440
14441             for (loc = bp->loc; loc != NULL; loc = loc->next)
14442               if (loc->loc_type == bp_loc_hardware_watchpoint
14443                   && loc->address + loc->length > addr
14444                   && addr + len > loc->address)
14445                 {
14446                   wp->val = NULL;
14447                   wp->val_valid = 0;
14448                 }
14449           }
14450       }
14451 }
14452
14453 /* Create and insert a breakpoint for software single step.  */
14454
14455 void
14456 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14457                                const address_space *aspace,
14458                                CORE_ADDR next_pc)
14459 {
14460   struct thread_info *tp = inferior_thread ();
14461   struct symtab_and_line sal;
14462   CORE_ADDR pc = next_pc;
14463
14464   if (tp->control.single_step_breakpoints == NULL)
14465     {
14466       tp->control.single_step_breakpoints
14467         = new_single_step_breakpoint (tp->global_num, gdbarch);
14468     }
14469
14470   sal = find_pc_line (pc, 0);
14471   sal.pc = pc;
14472   sal.section = find_pc_overlay (pc);
14473   sal.explicit_pc = 1;
14474   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14475
14476   update_global_location_list (UGLL_INSERT);
14477 }
14478
14479 /* Insert single step breakpoints according to the current state.  */
14480
14481 int
14482 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14483 {
14484   struct regcache *regcache = get_current_regcache ();
14485   std::vector<CORE_ADDR> next_pcs;
14486
14487   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14488
14489   if (!next_pcs.empty ())
14490     {
14491       struct frame_info *frame = get_current_frame ();
14492       const address_space *aspace = get_frame_address_space (frame);
14493
14494       for (CORE_ADDR pc : next_pcs)
14495         insert_single_step_breakpoint (gdbarch, aspace, pc);
14496
14497       return 1;
14498     }
14499   else
14500     return 0;
14501 }
14502
14503 /* See breakpoint.h.  */
14504
14505 int
14506 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14507                                        const address_space *aspace,
14508                                        CORE_ADDR pc)
14509 {
14510   struct bp_location *loc;
14511
14512   for (loc = bp->loc; loc != NULL; loc = loc->next)
14513     if (loc->inserted
14514         && breakpoint_location_address_match (loc, aspace, pc))
14515       return 1;
14516
14517   return 0;
14518 }
14519
14520 /* Check whether a software single-step breakpoint is inserted at
14521    PC.  */
14522
14523 int
14524 single_step_breakpoint_inserted_here_p (const address_space *aspace,
14525                                         CORE_ADDR pc)
14526 {
14527   struct breakpoint *bpt;
14528
14529   ALL_BREAKPOINTS (bpt)
14530     {
14531       if (bpt->type == bp_single_step
14532           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
14533         return 1;
14534     }
14535   return 0;
14536 }
14537
14538 /* Tracepoint-specific operations.  */
14539
14540 /* Set tracepoint count to NUM.  */
14541 static void
14542 set_tracepoint_count (int num)
14543 {
14544   tracepoint_count = num;
14545   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14546 }
14547
14548 static void
14549 trace_command (const char *arg, int from_tty)
14550 {
14551   struct breakpoint_ops *ops;
14552
14553   event_location_up location = string_to_event_location (&arg,
14554                                                          current_language);
14555   if (location != NULL
14556       && event_location_type (location.get ()) == PROBE_LOCATION)
14557     ops = &tracepoint_probe_breakpoint_ops;
14558   else
14559     ops = &tracepoint_breakpoint_ops;
14560
14561   create_breakpoint (get_current_arch (),
14562                      location.get (),
14563                      NULL, 0, arg, 1 /* parse arg */,
14564                      0 /* tempflag */,
14565                      bp_tracepoint /* type_wanted */,
14566                      0 /* Ignore count */,
14567                      pending_break_support,
14568                      ops,
14569                      from_tty,
14570                      1 /* enabled */,
14571                      0 /* internal */, 0);
14572 }
14573
14574 static void
14575 ftrace_command (const char *arg, int from_tty)
14576 {
14577   event_location_up location = string_to_event_location (&arg,
14578                                                          current_language);
14579   create_breakpoint (get_current_arch (),
14580                      location.get (),
14581                      NULL, 0, arg, 1 /* parse arg */,
14582                      0 /* tempflag */,
14583                      bp_fast_tracepoint /* type_wanted */,
14584                      0 /* Ignore count */,
14585                      pending_break_support,
14586                      &tracepoint_breakpoint_ops,
14587                      from_tty,
14588                      1 /* enabled */,
14589                      0 /* internal */, 0);
14590 }
14591
14592 /* strace command implementation.  Creates a static tracepoint.  */
14593
14594 static void
14595 strace_command (const char *arg, int from_tty)
14596 {
14597   struct breakpoint_ops *ops;
14598   event_location_up location;
14599
14600   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14601      or with a normal static tracepoint.  */
14602   if (arg && startswith (arg, "-m") && isspace (arg[2]))
14603     {
14604       ops = &strace_marker_breakpoint_ops;
14605       location = new_linespec_location (&arg, symbol_name_match_type::FULL);
14606     }
14607   else
14608     {
14609       ops = &tracepoint_breakpoint_ops;
14610       location = string_to_event_location (&arg, current_language);
14611     }
14612
14613   create_breakpoint (get_current_arch (),
14614                      location.get (),
14615                      NULL, 0, arg, 1 /* parse arg */,
14616                      0 /* tempflag */,
14617                      bp_static_tracepoint /* type_wanted */,
14618                      0 /* Ignore count */,
14619                      pending_break_support,
14620                      ops,
14621                      from_tty,
14622                      1 /* enabled */,
14623                      0 /* internal */, 0);
14624 }
14625
14626 /* Set up a fake reader function that gets command lines from a linked
14627    list that was acquired during tracepoint uploading.  */
14628
14629 static struct uploaded_tp *this_utp;
14630 static int next_cmd;
14631
14632 static char *
14633 read_uploaded_action (void)
14634 {
14635   char *rslt = nullptr;
14636
14637   if (next_cmd < this_utp->cmd_strings.size ())
14638     {
14639       rslt = this_utp->cmd_strings[next_cmd].get ();
14640       next_cmd++;
14641     }
14642
14643   return rslt;
14644 }
14645
14646 /* Given information about a tracepoint as recorded on a target (which
14647    can be either a live system or a trace file), attempt to create an
14648    equivalent GDB tracepoint.  This is not a reliable process, since
14649    the target does not necessarily have all the information used when
14650    the tracepoint was originally defined.  */
14651   
14652 struct tracepoint *
14653 create_tracepoint_from_upload (struct uploaded_tp *utp)
14654 {
14655   const char *addr_str;
14656   char small_buf[100];
14657   struct tracepoint *tp;
14658
14659   if (utp->at_string)
14660     addr_str = utp->at_string.get ();
14661   else
14662     {
14663       /* In the absence of a source location, fall back to raw
14664          address.  Since there is no way to confirm that the address
14665          means the same thing as when the trace was started, warn the
14666          user.  */
14667       warning (_("Uploaded tracepoint %d has no "
14668                  "source location, using raw address"),
14669                utp->number);
14670       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14671       addr_str = small_buf;
14672     }
14673
14674   /* There's not much we can do with a sequence of bytecodes.  */
14675   if (utp->cond && !utp->cond_string)
14676     warning (_("Uploaded tracepoint %d condition "
14677                "has no source form, ignoring it"),
14678              utp->number);
14679
14680   event_location_up location = string_to_event_location (&addr_str,
14681                                                          current_language);
14682   if (!create_breakpoint (get_current_arch (),
14683                           location.get (),
14684                           utp->cond_string.get (), -1, addr_str,
14685                           0 /* parse cond/thread */,
14686                           0 /* tempflag */,
14687                           utp->type /* type_wanted */,
14688                           0 /* Ignore count */,
14689                           pending_break_support,
14690                           &tracepoint_breakpoint_ops,
14691                           0 /* from_tty */,
14692                           utp->enabled /* enabled */,
14693                           0 /* internal */,
14694                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14695     return NULL;
14696
14697   /* Get the tracepoint we just created.  */
14698   tp = get_tracepoint (tracepoint_count);
14699   gdb_assert (tp != NULL);
14700
14701   if (utp->pass > 0)
14702     {
14703       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14704                  tp->number);
14705
14706       trace_pass_command (small_buf, 0);
14707     }
14708
14709   /* If we have uploaded versions of the original commands, set up a
14710      special-purpose "reader" function and call the usual command line
14711      reader, then pass the result to the breakpoint command-setting
14712      function.  */
14713   if (!utp->cmd_strings.empty ())
14714     {
14715       counted_command_line cmd_list;
14716
14717       this_utp = utp;
14718       next_cmd = 0;
14719
14720       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL);
14721
14722       breakpoint_set_commands (tp, std::move (cmd_list));
14723     }
14724   else if (!utp->actions.empty ()
14725            || !utp->step_actions.empty ())
14726     warning (_("Uploaded tracepoint %d actions "
14727                "have no source form, ignoring them"),
14728              utp->number);
14729
14730   /* Copy any status information that might be available.  */
14731   tp->hit_count = utp->hit_count;
14732   tp->traceframe_usage = utp->traceframe_usage;
14733
14734   return tp;
14735 }
14736   
14737 /* Print information on tracepoint number TPNUM_EXP, or all if
14738    omitted.  */
14739
14740 static void
14741 info_tracepoints_command (const char *args, int from_tty)
14742 {
14743   struct ui_out *uiout = current_uiout;
14744   int num_printed;
14745
14746   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14747
14748   if (num_printed == 0)
14749     {
14750       if (args == NULL || *args == '\0')
14751         uiout->message ("No tracepoints.\n");
14752       else
14753         uiout->message ("No tracepoint matching '%s'.\n", args);
14754     }
14755
14756   default_collect_info ();
14757 }
14758
14759 /* The 'enable trace' command enables tracepoints.
14760    Not supported by all targets.  */
14761 static void
14762 enable_trace_command (const char *args, int from_tty)
14763 {
14764   enable_command (args, from_tty);
14765 }
14766
14767 /* The 'disable trace' command disables tracepoints.
14768    Not supported by all targets.  */
14769 static void
14770 disable_trace_command (const char *args, int from_tty)
14771 {
14772   disable_command (args, from_tty);
14773 }
14774
14775 /* Remove a tracepoint (or all if no argument).  */
14776 static void
14777 delete_trace_command (const char *arg, int from_tty)
14778 {
14779   struct breakpoint *b, *b_tmp;
14780
14781   dont_repeat ();
14782
14783   if (arg == 0)
14784     {
14785       int breaks_to_delete = 0;
14786
14787       /* Delete all breakpoints if no argument.
14788          Do not delete internal or call-dummy breakpoints, these
14789          have to be deleted with an explicit breakpoint number 
14790          argument.  */
14791       ALL_TRACEPOINTS (b)
14792         if (is_tracepoint (b) && user_breakpoint_p (b))
14793           {
14794             breaks_to_delete = 1;
14795             break;
14796           }
14797
14798       /* Ask user only if there are some breakpoints to delete.  */
14799       if (!from_tty
14800           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14801         {
14802           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14803             if (is_tracepoint (b) && user_breakpoint_p (b))
14804               delete_breakpoint (b);
14805         }
14806     }
14807   else
14808     map_breakpoint_numbers
14809       (arg, [&] (breakpoint *br)
14810        {
14811          iterate_over_related_breakpoints (br, delete_breakpoint);
14812        });
14813 }
14814
14815 /* Helper function for trace_pass_command.  */
14816
14817 static void
14818 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14819 {
14820   tp->pass_count = count;
14821   gdb::observers::breakpoint_modified.notify (tp);
14822   if (from_tty)
14823     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
14824                      tp->number, count);
14825 }
14826
14827 /* Set passcount for tracepoint.
14828
14829    First command argument is passcount, second is tracepoint number.
14830    If tracepoint number omitted, apply to most recently defined.
14831    Also accepts special argument "all".  */
14832
14833 static void
14834 trace_pass_command (const char *args, int from_tty)
14835 {
14836   struct tracepoint *t1;
14837   ULONGEST count;
14838
14839   if (args == 0 || *args == 0)
14840     error (_("passcount command requires an "
14841              "argument (count + optional TP num)"));
14842
14843   count = strtoulst (args, &args, 10);  /* Count comes first, then TP num.  */
14844
14845   args = skip_spaces (args);
14846   if (*args && strncasecmp (args, "all", 3) == 0)
14847     {
14848       struct breakpoint *b;
14849
14850       args += 3;                        /* Skip special argument "all".  */
14851       if (*args)
14852         error (_("Junk at end of arguments."));
14853
14854       ALL_TRACEPOINTS (b)
14855       {
14856         t1 = (struct tracepoint *) b;
14857         trace_pass_set_count (t1, count, from_tty);
14858       }
14859     }
14860   else if (*args == '\0')
14861     {
14862       t1 = get_tracepoint_by_number (&args, NULL);
14863       if (t1)
14864         trace_pass_set_count (t1, count, from_tty);
14865     }
14866   else
14867     {
14868       number_or_range_parser parser (args);
14869       while (!parser.finished ())
14870         {
14871           t1 = get_tracepoint_by_number (&args, &parser);
14872           if (t1)
14873             trace_pass_set_count (t1, count, from_tty);
14874         }
14875     }
14876 }
14877
14878 struct tracepoint *
14879 get_tracepoint (int num)
14880 {
14881   struct breakpoint *t;
14882
14883   ALL_TRACEPOINTS (t)
14884     if (t->number == num)
14885       return (struct tracepoint *) t;
14886
14887   return NULL;
14888 }
14889
14890 /* Find the tracepoint with the given target-side number (which may be
14891    different from the tracepoint number after disconnecting and
14892    reconnecting).  */
14893
14894 struct tracepoint *
14895 get_tracepoint_by_number_on_target (int num)
14896 {
14897   struct breakpoint *b;
14898
14899   ALL_TRACEPOINTS (b)
14900     {
14901       struct tracepoint *t = (struct tracepoint *) b;
14902
14903       if (t->number_on_target == num)
14904         return t;
14905     }
14906
14907   return NULL;
14908 }
14909
14910 /* Utility: parse a tracepoint number and look it up in the list.
14911    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14912    If the argument is missing, the most recent tracepoint
14913    (tracepoint_count) is returned.  */
14914
14915 struct tracepoint *
14916 get_tracepoint_by_number (const char **arg,
14917                           number_or_range_parser *parser)
14918 {
14919   struct breakpoint *t;
14920   int tpnum;
14921   const char *instring = arg == NULL ? NULL : *arg;
14922
14923   if (parser != NULL)
14924     {
14925       gdb_assert (!parser->finished ());
14926       tpnum = parser->get_number ();
14927     }
14928   else if (arg == NULL || *arg == NULL || ! **arg)
14929     tpnum = tracepoint_count;
14930   else
14931     tpnum = get_number (arg);
14932
14933   if (tpnum <= 0)
14934     {
14935       if (instring && *instring)
14936         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
14937                          instring);
14938       else
14939         printf_filtered (_("No previous tracepoint\n"));
14940       return NULL;
14941     }
14942
14943   ALL_TRACEPOINTS (t)
14944     if (t->number == tpnum)
14945     {
14946       return (struct tracepoint *) t;
14947     }
14948
14949   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
14950   return NULL;
14951 }
14952
14953 void
14954 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
14955 {
14956   if (b->thread != -1)
14957     fprintf_unfiltered (fp, " thread %d", b->thread);
14958
14959   if (b->task != 0)
14960     fprintf_unfiltered (fp, " task %d", b->task);
14961
14962   fprintf_unfiltered (fp, "\n");
14963 }
14964
14965 /* Save information on user settable breakpoints (watchpoints, etc) to
14966    a new script file named FILENAME.  If FILTER is non-NULL, call it
14967    on each breakpoint and only include the ones for which it returns
14968    non-zero.  */
14969
14970 static void
14971 save_breakpoints (const char *filename, int from_tty,
14972                   int (*filter) (const struct breakpoint *))
14973 {
14974   struct breakpoint *tp;
14975   int any = 0;
14976   int extra_trace_bits = 0;
14977
14978   if (filename == 0 || *filename == 0)
14979     error (_("Argument required (file name in which to save)"));
14980
14981   /* See if we have anything to save.  */
14982   ALL_BREAKPOINTS (tp)
14983   {
14984     /* Skip internal and momentary breakpoints.  */
14985     if (!user_breakpoint_p (tp))
14986       continue;
14987
14988     /* If we have a filter, only save the breakpoints it accepts.  */
14989     if (filter && !filter (tp))
14990       continue;
14991
14992     any = 1;
14993
14994     if (is_tracepoint (tp))
14995       {
14996         extra_trace_bits = 1;
14997
14998         /* We can stop searching.  */
14999         break;
15000       }
15001   }
15002
15003   if (!any)
15004     {
15005       warning (_("Nothing to save."));
15006       return;
15007     }
15008
15009   gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
15010
15011   stdio_file fp;
15012
15013   if (!fp.open (expanded_filename.get (), "w"))
15014     error (_("Unable to open file '%s' for saving (%s)"),
15015            expanded_filename.get (), safe_strerror (errno));
15016
15017   if (extra_trace_bits)
15018     save_trace_state_variables (&fp);
15019
15020   ALL_BREAKPOINTS (tp)
15021   {
15022     /* Skip internal and momentary breakpoints.  */
15023     if (!user_breakpoint_p (tp))
15024       continue;
15025
15026     /* If we have a filter, only save the breakpoints it accepts.  */
15027     if (filter && !filter (tp))
15028       continue;
15029
15030     tp->ops->print_recreate (tp, &fp);
15031
15032     /* Note, we can't rely on tp->number for anything, as we can't
15033        assume the recreated breakpoint numbers will match.  Use $bpnum
15034        instead.  */
15035
15036     if (tp->cond_string)
15037       fp.printf ("  condition $bpnum %s\n", tp->cond_string);
15038
15039     if (tp->ignore_count)
15040       fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15041
15042     if (tp->type != bp_dprintf && tp->commands)
15043       {
15044         fp.puts ("  commands\n");
15045         
15046         current_uiout->redirect (&fp);
15047         TRY
15048           {
15049             print_command_lines (current_uiout, tp->commands.get (), 2);
15050           }
15051         CATCH (ex, RETURN_MASK_ALL)
15052           {
15053           current_uiout->redirect (NULL);
15054             throw_exception (ex);
15055           }
15056         END_CATCH
15057
15058         current_uiout->redirect (NULL);
15059         fp.puts ("  end\n");
15060       }
15061
15062     if (tp->enable_state == bp_disabled)
15063       fp.puts ("disable $bpnum\n");
15064
15065     /* If this is a multi-location breakpoint, check if the locations
15066        should be individually disabled.  Watchpoint locations are
15067        special, and not user visible.  */
15068     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15069       {
15070         struct bp_location *loc;
15071         int n = 1;
15072
15073         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15074           if (!loc->enabled)
15075             fp.printf ("disable $bpnum.%d\n", n);
15076       }
15077   }
15078
15079   if (extra_trace_bits && *default_collect)
15080     fp.printf ("set default-collect %s\n", default_collect);
15081
15082   if (from_tty)
15083     printf_filtered (_("Saved to file '%s'.\n"), expanded_filename.get ());
15084 }
15085
15086 /* The `save breakpoints' command.  */
15087
15088 static void
15089 save_breakpoints_command (const char *args, int from_tty)
15090 {
15091   save_breakpoints (args, from_tty, NULL);
15092 }
15093
15094 /* The `save tracepoints' command.  */
15095
15096 static void
15097 save_tracepoints_command (const char *args, int from_tty)
15098 {
15099   save_breakpoints (args, from_tty, is_tracepoint);
15100 }
15101
15102 /* Create a vector of all tracepoints.  */
15103
15104 std::vector<breakpoint *>
15105 all_tracepoints (void)
15106 {
15107   std::vector<breakpoint *> tp_vec;
15108   struct breakpoint *tp;
15109
15110   ALL_TRACEPOINTS (tp)
15111   {
15112     tp_vec.push_back (tp);
15113   }
15114
15115   return tp_vec;
15116 }
15117
15118 \f
15119 /* This help string is used to consolidate all the help string for specifying
15120    locations used by several commands.  */
15121
15122 #define LOCATION_HELP_STRING \
15123 "Linespecs are colon-separated lists of location parameters, such as\n\
15124 source filename, function name, label name, and line number.\n\
15125 Example: To specify the start of a label named \"the_top\" in the\n\
15126 function \"fact\" in the file \"factorial.c\", use\n\
15127 \"factorial.c:fact:the_top\".\n\
15128 \n\
15129 Address locations begin with \"*\" and specify an exact address in the\n\
15130 program.  Example: To specify the fourth byte past the start function\n\
15131 \"main\", use \"*main + 4\".\n\
15132 \n\
15133 Explicit locations are similar to linespecs but use an option/argument\n\
15134 syntax to specify location parameters.\n\
15135 Example: To specify the start of the label named \"the_top\" in the\n\
15136 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15137 -function fact -label the_top\".\n\
15138 \n\
15139 By default, a specified function is matched against the program's\n\
15140 functions in all scopes.  For C++, this means in all namespaces and\n\
15141 classes.  For Ada, this means in all packages.  E.g., in C++,\n\
15142 \"func()\" matches \"A::func()\", \"A::B::func()\", etc.  The\n\
15143 \"-qualified\" flag overrides this behavior, making GDB interpret the\n\
15144 specified name as a complete fully-qualified name instead.\n"
15145
15146 /* This help string is used for the break, hbreak, tbreak and thbreak
15147    commands.  It is defined as a macro to prevent duplication.
15148    COMMAND should be a string constant containing the name of the
15149    command.  */
15150
15151 #define BREAK_ARGS_HELP(command) \
15152 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15153 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15154 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15155 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15156 `-probe-dtrace' (for a DTrace probe).\n\
15157 LOCATION may be a linespec, address, or explicit location as described\n\
15158 below.\n\
15159 \n\
15160 With no LOCATION, uses current execution address of the selected\n\
15161 stack frame.  This is useful for breaking on return to a stack frame.\n\
15162 \n\
15163 THREADNUM is the number from \"info threads\".\n\
15164 CONDITION is a boolean expression.\n\
15165 \n" LOCATION_HELP_STRING "\n\
15166 Multiple breakpoints at one place are permitted, and useful if their\n\
15167 conditions are different.\n\
15168 \n\
15169 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15170
15171 /* List of subcommands for "catch".  */
15172 static struct cmd_list_element *catch_cmdlist;
15173
15174 /* List of subcommands for "tcatch".  */
15175 static struct cmd_list_element *tcatch_cmdlist;
15176
15177 void
15178 add_catch_command (const char *name, const char *docstring,
15179                    cmd_const_sfunc_ftype *sfunc,
15180                    completer_ftype *completer,
15181                    void *user_data_catch,
15182                    void *user_data_tcatch)
15183 {
15184   struct cmd_list_element *command;
15185
15186   command = add_cmd (name, class_breakpoint, docstring,
15187                      &catch_cmdlist);
15188   set_cmd_sfunc (command, sfunc);
15189   set_cmd_context (command, user_data_catch);
15190   set_cmd_completer (command, completer);
15191
15192   command = add_cmd (name, class_breakpoint, docstring,
15193                      &tcatch_cmdlist);
15194   set_cmd_sfunc (command, sfunc);
15195   set_cmd_context (command, user_data_tcatch);
15196   set_cmd_completer (command, completer);
15197 }
15198
15199 static void
15200 save_command (const char *arg, int from_tty)
15201 {
15202   printf_unfiltered (_("\"save\" must be followed by "
15203                        "the name of a save subcommand.\n"));
15204   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15205 }
15206
15207 struct breakpoint *
15208 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15209                           void *data)
15210 {
15211   struct breakpoint *b, *b_tmp;
15212
15213   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15214     {
15215       if ((*callback) (b, data))
15216         return b;
15217     }
15218
15219   return NULL;
15220 }
15221
15222 /* Zero if any of the breakpoint's locations could be a location where
15223    functions have been inlined, nonzero otherwise.  */
15224
15225 static int
15226 is_non_inline_function (struct breakpoint *b)
15227 {
15228   /* The shared library event breakpoint is set on the address of a
15229      non-inline function.  */
15230   if (b->type == bp_shlib_event)
15231     return 1;
15232
15233   return 0;
15234 }
15235
15236 /* Nonzero if the specified PC cannot be a location where functions
15237    have been inlined.  */
15238
15239 int
15240 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
15241                            const struct target_waitstatus *ws)
15242 {
15243   struct breakpoint *b;
15244   struct bp_location *bl;
15245
15246   ALL_BREAKPOINTS (b)
15247     {
15248       if (!is_non_inline_function (b))
15249         continue;
15250
15251       for (bl = b->loc; bl != NULL; bl = bl->next)
15252         {
15253           if (!bl->shlib_disabled
15254               && bpstat_check_location (bl, aspace, pc, ws))
15255             return 1;
15256         }
15257     }
15258
15259   return 0;
15260 }
15261
15262 /* Remove any references to OBJFILE which is going to be freed.  */
15263
15264 void
15265 breakpoint_free_objfile (struct objfile *objfile)
15266 {
15267   struct bp_location **locp, *loc;
15268
15269   ALL_BP_LOCATIONS (loc, locp)
15270     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15271       loc->symtab = NULL;
15272 }
15273
15274 void
15275 initialize_breakpoint_ops (void)
15276 {
15277   static int initialized = 0;
15278
15279   struct breakpoint_ops *ops;
15280
15281   if (initialized)
15282     return;
15283   initialized = 1;
15284
15285   /* The breakpoint_ops structure to be inherit by all kinds of
15286      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15287      internal and momentary breakpoints, etc.).  */
15288   ops = &bkpt_base_breakpoint_ops;
15289   *ops = base_breakpoint_ops;
15290   ops->re_set = bkpt_re_set;
15291   ops->insert_location = bkpt_insert_location;
15292   ops->remove_location = bkpt_remove_location;
15293   ops->breakpoint_hit = bkpt_breakpoint_hit;
15294   ops->create_sals_from_location = bkpt_create_sals_from_location;
15295   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15296   ops->decode_location = bkpt_decode_location;
15297
15298   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15299   ops = &bkpt_breakpoint_ops;
15300   *ops = bkpt_base_breakpoint_ops;
15301   ops->re_set = bkpt_re_set;
15302   ops->resources_needed = bkpt_resources_needed;
15303   ops->print_it = bkpt_print_it;
15304   ops->print_mention = bkpt_print_mention;
15305   ops->print_recreate = bkpt_print_recreate;
15306
15307   /* Ranged breakpoints.  */
15308   ops = &ranged_breakpoint_ops;
15309   *ops = bkpt_breakpoint_ops;
15310   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15311   ops->resources_needed = resources_needed_ranged_breakpoint;
15312   ops->print_it = print_it_ranged_breakpoint;
15313   ops->print_one = print_one_ranged_breakpoint;
15314   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15315   ops->print_mention = print_mention_ranged_breakpoint;
15316   ops->print_recreate = print_recreate_ranged_breakpoint;
15317
15318   /* Internal breakpoints.  */
15319   ops = &internal_breakpoint_ops;
15320   *ops = bkpt_base_breakpoint_ops;
15321   ops->re_set = internal_bkpt_re_set;
15322   ops->check_status = internal_bkpt_check_status;
15323   ops->print_it = internal_bkpt_print_it;
15324   ops->print_mention = internal_bkpt_print_mention;
15325
15326   /* Momentary breakpoints.  */
15327   ops = &momentary_breakpoint_ops;
15328   *ops = bkpt_base_breakpoint_ops;
15329   ops->re_set = momentary_bkpt_re_set;
15330   ops->check_status = momentary_bkpt_check_status;
15331   ops->print_it = momentary_bkpt_print_it;
15332   ops->print_mention = momentary_bkpt_print_mention;
15333
15334   /* Probe breakpoints.  */
15335   ops = &bkpt_probe_breakpoint_ops;
15336   *ops = bkpt_breakpoint_ops;
15337   ops->insert_location = bkpt_probe_insert_location;
15338   ops->remove_location = bkpt_probe_remove_location;
15339   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15340   ops->decode_location = bkpt_probe_decode_location;
15341
15342   /* Watchpoints.  */
15343   ops = &watchpoint_breakpoint_ops;
15344   *ops = base_breakpoint_ops;
15345   ops->re_set = re_set_watchpoint;
15346   ops->insert_location = insert_watchpoint;
15347   ops->remove_location = remove_watchpoint;
15348   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15349   ops->check_status = check_status_watchpoint;
15350   ops->resources_needed = resources_needed_watchpoint;
15351   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15352   ops->print_it = print_it_watchpoint;
15353   ops->print_mention = print_mention_watchpoint;
15354   ops->print_recreate = print_recreate_watchpoint;
15355   ops->explains_signal = explains_signal_watchpoint;
15356
15357   /* Masked watchpoints.  */
15358   ops = &masked_watchpoint_breakpoint_ops;
15359   *ops = watchpoint_breakpoint_ops;
15360   ops->insert_location = insert_masked_watchpoint;
15361   ops->remove_location = remove_masked_watchpoint;
15362   ops->resources_needed = resources_needed_masked_watchpoint;
15363   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15364   ops->print_it = print_it_masked_watchpoint;
15365   ops->print_one_detail = print_one_detail_masked_watchpoint;
15366   ops->print_mention = print_mention_masked_watchpoint;
15367   ops->print_recreate = print_recreate_masked_watchpoint;
15368
15369   /* Tracepoints.  */
15370   ops = &tracepoint_breakpoint_ops;
15371   *ops = base_breakpoint_ops;
15372   ops->re_set = tracepoint_re_set;
15373   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15374   ops->print_one_detail = tracepoint_print_one_detail;
15375   ops->print_mention = tracepoint_print_mention;
15376   ops->print_recreate = tracepoint_print_recreate;
15377   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15378   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15379   ops->decode_location = tracepoint_decode_location;
15380
15381   /* Probe tracepoints.  */
15382   ops = &tracepoint_probe_breakpoint_ops;
15383   *ops = tracepoint_breakpoint_ops;
15384   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15385   ops->decode_location = tracepoint_probe_decode_location;
15386
15387   /* Static tracepoints with marker (`-m').  */
15388   ops = &strace_marker_breakpoint_ops;
15389   *ops = tracepoint_breakpoint_ops;
15390   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15391   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15392   ops->decode_location = strace_marker_decode_location;
15393
15394   /* Fork catchpoints.  */
15395   ops = &catch_fork_breakpoint_ops;
15396   *ops = base_breakpoint_ops;
15397   ops->insert_location = insert_catch_fork;
15398   ops->remove_location = remove_catch_fork;
15399   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15400   ops->print_it = print_it_catch_fork;
15401   ops->print_one = print_one_catch_fork;
15402   ops->print_mention = print_mention_catch_fork;
15403   ops->print_recreate = print_recreate_catch_fork;
15404
15405   /* Vfork catchpoints.  */
15406   ops = &catch_vfork_breakpoint_ops;
15407   *ops = base_breakpoint_ops;
15408   ops->insert_location = insert_catch_vfork;
15409   ops->remove_location = remove_catch_vfork;
15410   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15411   ops->print_it = print_it_catch_vfork;
15412   ops->print_one = print_one_catch_vfork;
15413   ops->print_mention = print_mention_catch_vfork;
15414   ops->print_recreate = print_recreate_catch_vfork;
15415
15416   /* Exec catchpoints.  */
15417   ops = &catch_exec_breakpoint_ops;
15418   *ops = base_breakpoint_ops;
15419   ops->insert_location = insert_catch_exec;
15420   ops->remove_location = remove_catch_exec;
15421   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15422   ops->print_it = print_it_catch_exec;
15423   ops->print_one = print_one_catch_exec;
15424   ops->print_mention = print_mention_catch_exec;
15425   ops->print_recreate = print_recreate_catch_exec;
15426
15427   /* Solib-related catchpoints.  */
15428   ops = &catch_solib_breakpoint_ops;
15429   *ops = base_breakpoint_ops;
15430   ops->insert_location = insert_catch_solib;
15431   ops->remove_location = remove_catch_solib;
15432   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15433   ops->check_status = check_status_catch_solib;
15434   ops->print_it = print_it_catch_solib;
15435   ops->print_one = print_one_catch_solib;
15436   ops->print_mention = print_mention_catch_solib;
15437   ops->print_recreate = print_recreate_catch_solib;
15438
15439   ops = &dprintf_breakpoint_ops;
15440   *ops = bkpt_base_breakpoint_ops;
15441   ops->re_set = dprintf_re_set;
15442   ops->resources_needed = bkpt_resources_needed;
15443   ops->print_it = bkpt_print_it;
15444   ops->print_mention = bkpt_print_mention;
15445   ops->print_recreate = dprintf_print_recreate;
15446   ops->after_condition_true = dprintf_after_condition_true;
15447   ops->breakpoint_hit = dprintf_breakpoint_hit;
15448 }
15449
15450 /* Chain containing all defined "enable breakpoint" subcommands.  */
15451
15452 static struct cmd_list_element *enablebreaklist = NULL;
15453
15454 /* See breakpoint.h.  */
15455
15456 cmd_list_element *commands_cmd_element = nullptr;
15457
15458 void
15459 _initialize_breakpoint (void)
15460 {
15461   struct cmd_list_element *c;
15462
15463   initialize_breakpoint_ops ();
15464
15465   gdb::observers::solib_unloaded.attach (disable_breakpoints_in_unloaded_shlib);
15466   gdb::observers::free_objfile.attach (disable_breakpoints_in_freed_objfile);
15467   gdb::observers::memory_changed.attach (invalidate_bp_value_on_memory_change);
15468
15469   breakpoint_objfile_key
15470     = register_objfile_data_with_cleanup (NULL, free_breakpoint_objfile_data);
15471
15472   breakpoint_chain = 0;
15473   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15474      before a breakpoint is set.  */
15475   breakpoint_count = 0;
15476
15477   tracepoint_count = 0;
15478
15479   add_com ("ignore", class_breakpoint, ignore_command, _("\
15480 Set ignore-count of breakpoint number N to COUNT.\n\
15481 Usage is `ignore N COUNT'."));
15482
15483   commands_cmd_element = add_com ("commands", class_breakpoint,
15484                                   commands_command, _("\
15485 Set commands to be executed when the given breakpoints are hit.\n\
15486 Give a space-separated breakpoint list as argument after \"commands\".\n\
15487 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
15488 (e.g. `5-7').\n\
15489 With no argument, the targeted breakpoint is the last one set.\n\
15490 The commands themselves follow starting on the next line.\n\
15491 Type a line containing \"end\" to indicate the end of them.\n\
15492 Give \"silent\" as the first line to make the breakpoint silent;\n\
15493 then no output is printed when it is hit, except what the commands print."));
15494
15495   c = add_com ("condition", class_breakpoint, condition_command, _("\
15496 Specify breakpoint number N to break only if COND is true.\n\
15497 Usage is `condition N COND', where N is an integer and COND is an\n\
15498 expression to be evaluated whenever breakpoint N is reached."));
15499   set_cmd_completer (c, condition_completer);
15500
15501   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15502 Set a temporary breakpoint.\n\
15503 Like \"break\" except the breakpoint is only temporary,\n\
15504 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15505 by using \"enable delete\" on the breakpoint number.\n\
15506 \n"
15507 BREAK_ARGS_HELP ("tbreak")));
15508   set_cmd_completer (c, location_completer);
15509
15510   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15511 Set a hardware assisted breakpoint.\n\
15512 Like \"break\" except the breakpoint requires hardware support,\n\
15513 some target hardware may not have this support.\n\
15514 \n"
15515 BREAK_ARGS_HELP ("hbreak")));
15516   set_cmd_completer (c, location_completer);
15517
15518   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15519 Set a temporary hardware assisted breakpoint.\n\
15520 Like \"hbreak\" except the breakpoint is only temporary,\n\
15521 so it will be deleted when hit.\n\
15522 \n"
15523 BREAK_ARGS_HELP ("thbreak")));
15524   set_cmd_completer (c, location_completer);
15525
15526   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15527 Enable some breakpoints.\n\
15528 Give breakpoint numbers (separated by spaces) as arguments.\n\
15529 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15530 This is used to cancel the effect of the \"disable\" command.\n\
15531 With a subcommand you can enable temporarily."),
15532                   &enablelist, "enable ", 1, &cmdlist);
15533
15534   add_com_alias ("en", "enable", class_breakpoint, 1);
15535
15536   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15537 Enable some breakpoints.\n\
15538 Give breakpoint numbers (separated by spaces) as arguments.\n\
15539 This is used to cancel the effect of the \"disable\" command.\n\
15540 May be abbreviated to simply \"enable\".\n"),
15541                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15542
15543   add_cmd ("once", no_class, enable_once_command, _("\
15544 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15545 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15546            &enablebreaklist);
15547
15548   add_cmd ("delete", no_class, enable_delete_command, _("\
15549 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15550 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15551            &enablebreaklist);
15552
15553   add_cmd ("count", no_class, enable_count_command, _("\
15554 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15555 If a breakpoint is hit while enabled in this fashion,\n\
15556 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15557            &enablebreaklist);
15558
15559   add_cmd ("delete", no_class, enable_delete_command, _("\
15560 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15561 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15562            &enablelist);
15563
15564   add_cmd ("once", no_class, enable_once_command, _("\
15565 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15566 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15567            &enablelist);
15568
15569   add_cmd ("count", no_class, enable_count_command, _("\
15570 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15571 If a breakpoint is hit while enabled in this fashion,\n\
15572 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15573            &enablelist);
15574
15575   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15576 Disable some breakpoints.\n\
15577 Arguments are breakpoint numbers with spaces in between.\n\
15578 To disable all breakpoints, give no argument.\n\
15579 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15580                   &disablelist, "disable ", 1, &cmdlist);
15581   add_com_alias ("dis", "disable", class_breakpoint, 1);
15582   add_com_alias ("disa", "disable", class_breakpoint, 1);
15583
15584   add_cmd ("breakpoints", class_alias, disable_command, _("\
15585 Disable some breakpoints.\n\
15586 Arguments are breakpoint numbers with spaces in between.\n\
15587 To disable all breakpoints, give no argument.\n\
15588 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15589 This command may be abbreviated \"disable\"."),
15590            &disablelist);
15591
15592   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15593 Delete some breakpoints or auto-display expressions.\n\
15594 Arguments are breakpoint numbers with spaces in between.\n\
15595 To delete all breakpoints, give no argument.\n\
15596 \n\
15597 Also a prefix command for deletion of other GDB objects.\n\
15598 The \"unset\" command is also an alias for \"delete\"."),
15599                   &deletelist, "delete ", 1, &cmdlist);
15600   add_com_alias ("d", "delete", class_breakpoint, 1);
15601   add_com_alias ("del", "delete", class_breakpoint, 1);
15602
15603   add_cmd ("breakpoints", class_alias, delete_command, _("\
15604 Delete some breakpoints or auto-display expressions.\n\
15605 Arguments are breakpoint numbers with spaces in between.\n\
15606 To delete all breakpoints, give no argument.\n\
15607 This command may be abbreviated \"delete\"."),
15608            &deletelist);
15609
15610   add_com ("clear", class_breakpoint, clear_command, _("\
15611 Clear breakpoint at specified location.\n\
15612 Argument may be a linespec, explicit, or address location as described below.\n\
15613 \n\
15614 With no argument, clears all breakpoints in the line that the selected frame\n\
15615 is executing in.\n"
15616 "\n" LOCATION_HELP_STRING "\n\
15617 See also the \"delete\" command which clears breakpoints by number."));
15618   add_com_alias ("cl", "clear", class_breakpoint, 1);
15619
15620   c = add_com ("break", class_breakpoint, break_command, _("\
15621 Set breakpoint at specified location.\n"
15622 BREAK_ARGS_HELP ("break")));
15623   set_cmd_completer (c, location_completer);
15624
15625   add_com_alias ("b", "break", class_run, 1);
15626   add_com_alias ("br", "break", class_run, 1);
15627   add_com_alias ("bre", "break", class_run, 1);
15628   add_com_alias ("brea", "break", class_run, 1);
15629
15630   if (dbx_commands)
15631     {
15632       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15633 Break in function/address or break at a line in the current file."),
15634                              &stoplist, "stop ", 1, &cmdlist);
15635       add_cmd ("in", class_breakpoint, stopin_command,
15636                _("Break in function or address."), &stoplist);
15637       add_cmd ("at", class_breakpoint, stopat_command,
15638                _("Break at a line in the current file."), &stoplist);
15639       add_com ("status", class_info, info_breakpoints_command, _("\
15640 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15641 The \"Type\" column indicates one of:\n\
15642 \tbreakpoint     - normal breakpoint\n\
15643 \twatchpoint     - watchpoint\n\
15644 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15645 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15646 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15647 address and file/line number respectively.\n\
15648 \n\
15649 Convenience variable \"$_\" and default examine address for \"x\"\n\
15650 are set to the address of the last breakpoint listed unless the command\n\
15651 is prefixed with \"server \".\n\n\
15652 Convenience variable \"$bpnum\" contains the number of the last\n\
15653 breakpoint set."));
15654     }
15655
15656   add_info ("breakpoints", info_breakpoints_command, _("\
15657 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15658 The \"Type\" column indicates one of:\n\
15659 \tbreakpoint     - normal breakpoint\n\
15660 \twatchpoint     - watchpoint\n\
15661 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15662 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15663 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15664 address and file/line number respectively.\n\
15665 \n\
15666 Convenience variable \"$_\" and default examine address for \"x\"\n\
15667 are set to the address of the last breakpoint listed unless the command\n\
15668 is prefixed with \"server \".\n\n\
15669 Convenience variable \"$bpnum\" contains the number of the last\n\
15670 breakpoint set."));
15671
15672   add_info_alias ("b", "breakpoints", 1);
15673
15674   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15675 Status of all breakpoints, or breakpoint number NUMBER.\n\
15676 The \"Type\" column indicates one of:\n\
15677 \tbreakpoint     - normal breakpoint\n\
15678 \twatchpoint     - watchpoint\n\
15679 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15680 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15681 \tuntil          - internal breakpoint used by the \"until\" command\n\
15682 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15683 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15684 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15685 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15686 address and file/line number respectively.\n\
15687 \n\
15688 Convenience variable \"$_\" and default examine address for \"x\"\n\
15689 are set to the address of the last breakpoint listed unless the command\n\
15690 is prefixed with \"server \".\n\n\
15691 Convenience variable \"$bpnum\" contains the number of the last\n\
15692 breakpoint set."),
15693            &maintenanceinfolist);
15694
15695   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15696 Set catchpoints to catch events."),
15697                   &catch_cmdlist, "catch ",
15698                   0/*allow-unknown*/, &cmdlist);
15699
15700   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15701 Set temporary catchpoints to catch events."),
15702                   &tcatch_cmdlist, "tcatch ",
15703                   0/*allow-unknown*/, &cmdlist);
15704
15705   add_catch_command ("fork", _("Catch calls to fork."),
15706                      catch_fork_command_1,
15707                      NULL,
15708                      (void *) (uintptr_t) catch_fork_permanent,
15709                      (void *) (uintptr_t) catch_fork_temporary);
15710   add_catch_command ("vfork", _("Catch calls to vfork."),
15711                      catch_fork_command_1,
15712                      NULL,
15713                      (void *) (uintptr_t) catch_vfork_permanent,
15714                      (void *) (uintptr_t) catch_vfork_temporary);
15715   add_catch_command ("exec", _("Catch calls to exec."),
15716                      catch_exec_command_1,
15717                      NULL,
15718                      CATCH_PERMANENT,
15719                      CATCH_TEMPORARY);
15720   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15721 Usage: catch load [REGEX]\n\
15722 If REGEX is given, only stop for libraries matching the regular expression."),
15723                      catch_load_command_1,
15724                      NULL,
15725                      CATCH_PERMANENT,
15726                      CATCH_TEMPORARY);
15727   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15728 Usage: catch unload [REGEX]\n\
15729 If REGEX is given, only stop for libraries matching the regular expression."),
15730                      catch_unload_command_1,
15731                      NULL,
15732                      CATCH_PERMANENT,
15733                      CATCH_TEMPORARY);
15734
15735   c = add_com ("watch", class_breakpoint, watch_command, _("\
15736 Set a watchpoint for an expression.\n\
15737 Usage: watch [-l|-location] EXPRESSION\n\
15738 A watchpoint stops execution of your program whenever the value of\n\
15739 an expression changes.\n\
15740 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15741 the memory to which it refers."));
15742   set_cmd_completer (c, expression_completer);
15743
15744   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15745 Set a read watchpoint for an expression.\n\
15746 Usage: rwatch [-l|-location] EXPRESSION\n\
15747 A watchpoint stops execution of your program whenever the value of\n\
15748 an expression is read.\n\
15749 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15750 the memory to which it refers."));
15751   set_cmd_completer (c, expression_completer);
15752
15753   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15754 Set a watchpoint for an expression.\n\
15755 Usage: awatch [-l|-location] EXPRESSION\n\
15756 A watchpoint stops execution of your program whenever the value of\n\
15757 an expression is either read or written.\n\
15758 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15759 the memory to which it refers."));
15760   set_cmd_completer (c, expression_completer);
15761
15762   add_info ("watchpoints", info_watchpoints_command, _("\
15763 Status of specified watchpoints (all watchpoints if no argument)."));
15764
15765   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15766      respond to changes - contrary to the description.  */
15767   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15768                             &can_use_hw_watchpoints, _("\
15769 Set debugger's willingness to use watchpoint hardware."), _("\
15770 Show debugger's willingness to use watchpoint hardware."), _("\
15771 If zero, gdb will not use hardware for new watchpoints, even if\n\
15772 such is available.  (However, any hardware watchpoints that were\n\
15773 created before setting this to nonzero, will continue to use watchpoint\n\
15774 hardware.)"),
15775                             NULL,
15776                             show_can_use_hw_watchpoints,
15777                             &setlist, &showlist);
15778
15779   can_use_hw_watchpoints = 1;
15780
15781   /* Tracepoint manipulation commands.  */
15782
15783   c = add_com ("trace", class_breakpoint, trace_command, _("\
15784 Set a tracepoint at specified location.\n\
15785 \n"
15786 BREAK_ARGS_HELP ("trace") "\n\
15787 Do \"help tracepoints\" for info on other tracepoint commands."));
15788   set_cmd_completer (c, location_completer);
15789
15790   add_com_alias ("tp", "trace", class_alias, 0);
15791   add_com_alias ("tr", "trace", class_alias, 1);
15792   add_com_alias ("tra", "trace", class_alias, 1);
15793   add_com_alias ("trac", "trace", class_alias, 1);
15794
15795   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15796 Set a fast tracepoint at specified location.\n\
15797 \n"
15798 BREAK_ARGS_HELP ("ftrace") "\n\
15799 Do \"help tracepoints\" for info on other tracepoint commands."));
15800   set_cmd_completer (c, location_completer);
15801
15802   c = add_com ("strace", class_breakpoint, strace_command, _("\
15803 Set a static tracepoint at location or marker.\n\
15804 \n\
15805 strace [LOCATION] [if CONDITION]\n\
15806 LOCATION may be a linespec, explicit, or address location (described below) \n\
15807 or -m MARKER_ID.\n\n\
15808 If a marker id is specified, probe the marker with that name.  With\n\
15809 no LOCATION, uses current execution address of the selected stack frame.\n\
15810 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15811 This collects arbitrary user data passed in the probe point call to the\n\
15812 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15813 by printing the $_sdata variable like any other convenience variable.\n\
15814 \n\
15815 CONDITION is a boolean expression.\n\
15816 \n" LOCATION_HELP_STRING "\n\
15817 Multiple tracepoints at one place are permitted, and useful if their\n\
15818 conditions are different.\n\
15819 \n\
15820 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15821 Do \"help tracepoints\" for info on other tracepoint commands."));
15822   set_cmd_completer (c, location_completer);
15823
15824   add_info ("tracepoints", info_tracepoints_command, _("\
15825 Status of specified tracepoints (all tracepoints if no argument).\n\
15826 Convenience variable \"$tpnum\" contains the number of the\n\
15827 last tracepoint set."));
15828
15829   add_info_alias ("tp", "tracepoints", 1);
15830
15831   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15832 Delete specified tracepoints.\n\
15833 Arguments are tracepoint numbers, separated by spaces.\n\
15834 No argument means delete all tracepoints."),
15835            &deletelist);
15836   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
15837
15838   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15839 Disable specified tracepoints.\n\
15840 Arguments are tracepoint numbers, separated by spaces.\n\
15841 No argument means disable all tracepoints."),
15842            &disablelist);
15843   deprecate_cmd (c, "disable");
15844
15845   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15846 Enable specified tracepoints.\n\
15847 Arguments are tracepoint numbers, separated by spaces.\n\
15848 No argument means enable all tracepoints."),
15849            &enablelist);
15850   deprecate_cmd (c, "enable");
15851
15852   add_com ("passcount", class_trace, trace_pass_command, _("\
15853 Set the passcount for a tracepoint.\n\
15854 The trace will end when the tracepoint has been passed 'count' times.\n\
15855 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15856 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
15857
15858   add_prefix_cmd ("save", class_breakpoint, save_command,
15859                   _("Save breakpoint definitions as a script."),
15860                   &save_cmdlist, "save ",
15861                   0/*allow-unknown*/, &cmdlist);
15862
15863   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
15864 Save current breakpoint definitions as a script.\n\
15865 This includes all types of breakpoints (breakpoints, watchpoints,\n\
15866 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
15867 session to restore them."),
15868                &save_cmdlist);
15869   set_cmd_completer (c, filename_completer);
15870
15871   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
15872 Save current tracepoint definitions as a script.\n\
15873 Use the 'source' command in another debug session to restore them."),
15874                &save_cmdlist);
15875   set_cmd_completer (c, filename_completer);
15876
15877   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
15878   deprecate_cmd (c, "save tracepoints");
15879
15880   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
15881 Breakpoint specific settings\n\
15882 Configure various breakpoint-specific variables such as\n\
15883 pending breakpoint behavior"),
15884                   &breakpoint_set_cmdlist, "set breakpoint ",
15885                   0/*allow-unknown*/, &setlist);
15886   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
15887 Breakpoint specific settings\n\
15888 Configure various breakpoint-specific variables such as\n\
15889 pending breakpoint behavior"),
15890                   &breakpoint_show_cmdlist, "show breakpoint ",
15891                   0/*allow-unknown*/, &showlist);
15892
15893   add_setshow_auto_boolean_cmd ("pending", no_class,
15894                                 &pending_break_support, _("\
15895 Set debugger's behavior regarding pending breakpoints."), _("\
15896 Show debugger's behavior regarding pending breakpoints."), _("\
15897 If on, an unrecognized breakpoint location will cause gdb to create a\n\
15898 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
15899 an error.  If auto, an unrecognized breakpoint location results in a\n\
15900 user-query to see if a pending breakpoint should be created."),
15901                                 NULL,
15902                                 show_pending_break_support,
15903                                 &breakpoint_set_cmdlist,
15904                                 &breakpoint_show_cmdlist);
15905
15906   pending_break_support = AUTO_BOOLEAN_AUTO;
15907
15908   add_setshow_boolean_cmd ("auto-hw", no_class,
15909                            &automatic_hardware_breakpoints, _("\
15910 Set automatic usage of hardware breakpoints."), _("\
15911 Show automatic usage of hardware breakpoints."), _("\
15912 If set, the debugger will automatically use hardware breakpoints for\n\
15913 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
15914 a warning will be emitted for such breakpoints."),
15915                            NULL,
15916                            show_automatic_hardware_breakpoints,
15917                            &breakpoint_set_cmdlist,
15918                            &breakpoint_show_cmdlist);
15919
15920   add_setshow_boolean_cmd ("always-inserted", class_support,
15921                            &always_inserted_mode, _("\
15922 Set mode for inserting breakpoints."), _("\
15923 Show mode for inserting breakpoints."), _("\
15924 When this mode is on, breakpoints are inserted immediately as soon as\n\
15925 they're created, kept inserted even when execution stops, and removed\n\
15926 only when the user deletes them.  When this mode is off (the default),\n\
15927 breakpoints are inserted only when execution continues, and removed\n\
15928 when execution stops."),
15929                                 NULL,
15930                                 &show_always_inserted_mode,
15931                                 &breakpoint_set_cmdlist,
15932                                 &breakpoint_show_cmdlist);
15933
15934   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
15935                         condition_evaluation_enums,
15936                         &condition_evaluation_mode_1, _("\
15937 Set mode of breakpoint condition evaluation."), _("\
15938 Show mode of breakpoint condition evaluation."), _("\
15939 When this is set to \"host\", breakpoint conditions will be\n\
15940 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
15941 breakpoint conditions will be downloaded to the target (if the target\n\
15942 supports such feature) and conditions will be evaluated on the target's side.\n\
15943 If this is set to \"auto\" (default), this will be automatically set to\n\
15944 \"target\" if it supports condition evaluation, otherwise it will\n\
15945 be set to \"gdb\""),
15946                            &set_condition_evaluation_mode,
15947                            &show_condition_evaluation_mode,
15948                            &breakpoint_set_cmdlist,
15949                            &breakpoint_show_cmdlist);
15950
15951   add_com ("break-range", class_breakpoint, break_range_command, _("\
15952 Set a breakpoint for an address range.\n\
15953 break-range START-LOCATION, END-LOCATION\n\
15954 where START-LOCATION and END-LOCATION can be one of the following:\n\
15955   LINENUM, for that line in the current file,\n\
15956   FILE:LINENUM, for that line in that file,\n\
15957   +OFFSET, for that number of lines after the current line\n\
15958            or the start of the range\n\
15959   FUNCTION, for the first line in that function,\n\
15960   FILE:FUNCTION, to distinguish among like-named static functions.\n\
15961   *ADDRESS, for the instruction at that address.\n\
15962 \n\
15963 The breakpoint will stop execution of the inferior whenever it executes\n\
15964 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
15965 range (including START-LOCATION and END-LOCATION)."));
15966
15967   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
15968 Set a dynamic printf at specified location.\n\
15969 dprintf location,format string,arg1,arg2,...\n\
15970 location may be a linespec, explicit, or address location.\n"
15971 "\n" LOCATION_HELP_STRING));
15972   set_cmd_completer (c, location_completer);
15973
15974   add_setshow_enum_cmd ("dprintf-style", class_support,
15975                         dprintf_style_enums, &dprintf_style, _("\
15976 Set the style of usage for dynamic printf."), _("\
15977 Show the style of usage for dynamic printf."), _("\
15978 This setting chooses how GDB will do a dynamic printf.\n\
15979 If the value is \"gdb\", then the printing is done by GDB to its own\n\
15980 console, as with the \"printf\" command.\n\
15981 If the value is \"call\", the print is done by calling a function in your\n\
15982 program; by default printf(), but you can choose a different function or\n\
15983 output stream by setting dprintf-function and dprintf-channel."),
15984                         update_dprintf_commands, NULL,
15985                         &setlist, &showlist);
15986
15987   dprintf_function = xstrdup ("printf");
15988   add_setshow_string_cmd ("dprintf-function", class_support,
15989                           &dprintf_function, _("\
15990 Set the function to use for dynamic printf"), _("\
15991 Show the function to use for dynamic printf"), NULL,
15992                           update_dprintf_commands, NULL,
15993                           &setlist, &showlist);
15994
15995   dprintf_channel = xstrdup ("");
15996   add_setshow_string_cmd ("dprintf-channel", class_support,
15997                           &dprintf_channel, _("\
15998 Set the channel to use for dynamic printf"), _("\
15999 Show the channel to use for dynamic printf"), NULL,
16000                           update_dprintf_commands, NULL,
16001                           &setlist, &showlist);
16002
16003   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16004                            &disconnected_dprintf, _("\
16005 Set whether dprintf continues after GDB disconnects."), _("\
16006 Show whether dprintf continues after GDB disconnects."), _("\
16007 Use this to let dprintf commands continue to hit and produce output\n\
16008 even if GDB disconnects or detaches from the target."),
16009                            NULL,
16010                            NULL,
16011                            &setlist, &showlist);
16012
16013   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16014 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16015 (target agent only) This is useful for formatted output in user-defined commands."));
16016
16017   automatic_hardware_breakpoints = 1;
16018
16019   gdb::observers::about_to_proceed.attach (breakpoint_about_to_proceed);
16020   gdb::observers::thread_exit.attach (remove_threaded_breakpoints);
16021 }