2c031c053a6601b3e308ff712939e8bd9ce685f7
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2018 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "infrun.h"
36 #include "gdbthread.h"
37 #include "target.h"
38 #include "language.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "ui-out.h"
48 #include "cli/cli-script.h"
49 #include "block.h"
50 #include "solib.h"
51 #include "solist.h"
52 #include "observable.h"
53 #include "memattr.h"
54 #include "ada-lang.h"
55 #include "top.h"
56 #include "valprint.h"
57 #include "jit.h"
58 #include "parser-defs.h"
59 #include "gdb_regex.h"
60 #include "probe.h"
61 #include "cli/cli-utils.h"
62 #include "continuations.h"
63 #include "stack.h"
64 #include "skip.h"
65 #include "ax-gdb.h"
66 #include "dummy-frame.h"
67 #include "interps.h"
68 #include "format.h"
69 #include "thread-fsm.h"
70 #include "tid-parse.h"
71
72 /* readline include files */
73 #include "readline/readline.h"
74 #include "readline/history.h"
75
76 /* readline defines this.  */
77 #undef savestring
78
79 #include "mi/mi-common.h"
80 #include "extension.h"
81 #include <algorithm>
82 #include "progspace-and-thread.h"
83 #include "common/array-view.h"
84 #include "common/gdb_optional.h"
85
86 /* Enums for exception-handling support.  */
87 enum exception_event_kind
88 {
89   EX_EVENT_THROW,
90   EX_EVENT_RETHROW,
91   EX_EVENT_CATCH
92 };
93
94 /* Prototypes for local functions.  */
95
96 static void map_breakpoint_numbers (const char *,
97                                     gdb::function_view<void (breakpoint *)>);
98
99 static void breakpoint_re_set_default (struct breakpoint *);
100
101 static void
102   create_sals_from_location_default (const struct event_location *location,
103                                      struct linespec_result *canonical,
104                                      enum bptype type_wanted);
105
106 static void create_breakpoints_sal_default (struct gdbarch *,
107                                             struct linespec_result *,
108                                             gdb::unique_xmalloc_ptr<char>,
109                                             gdb::unique_xmalloc_ptr<char>,
110                                             enum bptype,
111                                             enum bpdisp, int, int,
112                                             int,
113                                             const struct breakpoint_ops *,
114                                             int, int, int, unsigned);
115
116 static std::vector<symtab_and_line> decode_location_default
117   (struct breakpoint *b, const struct event_location *location,
118    struct program_space *search_pspace);
119
120 static int can_use_hardware_watchpoint
121     (const std::vector<value_ref_ptr> &vals);
122
123 static void mention (struct breakpoint *);
124
125 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
126                                                                enum bptype,
127                                                                const struct breakpoint_ops *);
128 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
129                                                        const struct symtab_and_line *);
130
131 /* This function is used in gdbtk sources and thus can not be made
132    static.  */
133 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
134                                        struct symtab_and_line,
135                                        enum bptype,
136                                        const struct breakpoint_ops *);
137
138 static struct breakpoint *
139   momentary_breakpoint_from_master (struct breakpoint *orig,
140                                     enum bptype type,
141                                     const struct breakpoint_ops *ops,
142                                     int loc_enabled);
143
144 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
145
146 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
147                                             CORE_ADDR bpaddr,
148                                             enum bptype bptype);
149
150 static void describe_other_breakpoints (struct gdbarch *,
151                                         struct program_space *, CORE_ADDR,
152                                         struct obj_section *, int);
153
154 static int watchpoint_locations_match (struct bp_location *loc1,
155                                        struct bp_location *loc2);
156
157 static int breakpoint_location_address_match (struct bp_location *bl,
158                                               const struct address_space *aspace,
159                                               CORE_ADDR addr);
160
161 static int breakpoint_location_address_range_overlap (struct bp_location *,
162                                                       const address_space *,
163                                                       CORE_ADDR, int);
164
165 static int remove_breakpoint (struct bp_location *);
166 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
167
168 static enum print_stop_action print_bp_stop_message (bpstat bs);
169
170 static int hw_breakpoint_used_count (void);
171
172 static int hw_watchpoint_use_count (struct breakpoint *);
173
174 static int hw_watchpoint_used_count_others (struct breakpoint *except,
175                                             enum bptype type,
176                                             int *other_type_used);
177
178 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
179                                     int count);
180
181 static void free_bp_location (struct bp_location *loc);
182 static void incref_bp_location (struct bp_location *loc);
183 static void decref_bp_location (struct bp_location **loc);
184
185 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
186
187 /* update_global_location_list's modes of operation wrt to whether to
188    insert locations now.  */
189 enum ugll_insert_mode
190 {
191   /* Don't insert any breakpoint locations into the inferior, only
192      remove already-inserted locations that no longer should be
193      inserted.  Functions that delete a breakpoint or breakpoints
194      should specify this mode, so that deleting a breakpoint doesn't
195      have the side effect of inserting the locations of other
196      breakpoints that are marked not-inserted, but should_be_inserted
197      returns true on them.
198
199      This behavior is useful is situations close to tear-down -- e.g.,
200      after an exec, while the target still has execution, but
201      breakpoint shadows of the previous executable image should *NOT*
202      be restored to the new image; or before detaching, where the
203      target still has execution and wants to delete breakpoints from
204      GDB's lists, and all breakpoints had already been removed from
205      the inferior.  */
206   UGLL_DONT_INSERT,
207
208   /* May insert breakpoints iff breakpoints_should_be_inserted_now
209      claims breakpoints should be inserted now.  */
210   UGLL_MAY_INSERT,
211
212   /* Insert locations now, irrespective of
213      breakpoints_should_be_inserted_now.  E.g., say all threads are
214      stopped right now, and the user did "continue".  We need to
215      insert breakpoints _before_ resuming the target, but
216      UGLL_MAY_INSERT wouldn't insert them, because
217      breakpoints_should_be_inserted_now returns false at that point,
218      as no thread is running yet.  */
219   UGLL_INSERT
220 };
221
222 static void update_global_location_list (enum ugll_insert_mode);
223
224 static void update_global_location_list_nothrow (enum ugll_insert_mode);
225
226 static int is_hardware_watchpoint (const struct breakpoint *bpt);
227
228 static void insert_breakpoint_locations (void);
229
230 static void trace_pass_command (const char *, int);
231
232 static void set_tracepoint_count (int num);
233
234 static int is_masked_watchpoint (const struct breakpoint *b);
235
236 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
237
238 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
239    otherwise.  */
240
241 static int strace_marker_p (struct breakpoint *b);
242
243 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
244    that are implemented on top of software or hardware breakpoints
245    (user breakpoints, internal and momentary breakpoints, etc.).  */
246 static struct breakpoint_ops bkpt_base_breakpoint_ops;
247
248 /* Internal breakpoints class type.  */
249 static struct breakpoint_ops internal_breakpoint_ops;
250
251 /* Momentary breakpoints class type.  */
252 static struct breakpoint_ops momentary_breakpoint_ops;
253
254 /* The breakpoint_ops structure to be used in regular user created
255    breakpoints.  */
256 struct breakpoint_ops bkpt_breakpoint_ops;
257
258 /* Breakpoints set on probes.  */
259 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
260
261 /* Dynamic printf class type.  */
262 struct breakpoint_ops dprintf_breakpoint_ops;
263
264 /* The style in which to perform a dynamic printf.  This is a user
265    option because different output options have different tradeoffs;
266    if GDB does the printing, there is better error handling if there
267    is a problem with any of the arguments, but using an inferior
268    function lets you have special-purpose printers and sending of
269    output to the same place as compiled-in print functions.  */
270
271 static const char dprintf_style_gdb[] = "gdb";
272 static const char dprintf_style_call[] = "call";
273 static const char dprintf_style_agent[] = "agent";
274 static const char *const dprintf_style_enums[] = {
275   dprintf_style_gdb,
276   dprintf_style_call,
277   dprintf_style_agent,
278   NULL
279 };
280 static const char *dprintf_style = dprintf_style_gdb;
281
282 /* The function to use for dynamic printf if the preferred style is to
283    call into the inferior.  The value is simply a string that is
284    copied into the command, so it can be anything that GDB can
285    evaluate to a callable address, not necessarily a function name.  */
286
287 static char *dprintf_function;
288
289 /* The channel to use for dynamic printf if the preferred style is to
290    call into the inferior; if a nonempty string, it will be passed to
291    the call as the first argument, with the format string as the
292    second.  As with the dprintf function, this can be anything that
293    GDB knows how to evaluate, so in addition to common choices like
294    "stderr", this could be an app-specific expression like
295    "mystreams[curlogger]".  */
296
297 static char *dprintf_channel;
298
299 /* True if dprintf commands should continue to operate even if GDB
300    has disconnected.  */
301 static int disconnected_dprintf = 1;
302
303 struct command_line *
304 breakpoint_commands (struct breakpoint *b)
305 {
306   return b->commands ? b->commands.get () : NULL;
307 }
308
309 /* Flag indicating that a command has proceeded the inferior past the
310    current breakpoint.  */
311
312 static int breakpoint_proceeded;
313
314 const char *
315 bpdisp_text (enum bpdisp disp)
316 {
317   /* NOTE: the following values are a part of MI protocol and
318      represent values of 'disp' field returned when inferior stops at
319      a breakpoint.  */
320   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
321
322   return bpdisps[(int) disp];
323 }
324
325 /* Prototypes for exported functions.  */
326 /* If FALSE, gdb will not use hardware support for watchpoints, even
327    if such is available.  */
328 static int can_use_hw_watchpoints;
329
330 static void
331 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
332                              struct cmd_list_element *c,
333                              const char *value)
334 {
335   fprintf_filtered (file,
336                     _("Debugger's willingness to use "
337                       "watchpoint hardware is %s.\n"),
338                     value);
339 }
340
341 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
342    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
343    for unrecognized breakpoint locations.
344    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
345 static enum auto_boolean pending_break_support;
346 static void
347 show_pending_break_support (struct ui_file *file, int from_tty,
348                             struct cmd_list_element *c,
349                             const char *value)
350 {
351   fprintf_filtered (file,
352                     _("Debugger's behavior regarding "
353                       "pending breakpoints is %s.\n"),
354                     value);
355 }
356
357 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
358    set with "break" but falling in read-only memory.
359    If 0, gdb will warn about such breakpoints, but won't automatically
360    use hardware breakpoints.  */
361 static int automatic_hardware_breakpoints;
362 static void
363 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
364                                      struct cmd_list_element *c,
365                                      const char *value)
366 {
367   fprintf_filtered (file,
368                     _("Automatic usage of hardware breakpoints is %s.\n"),
369                     value);
370 }
371
372 /* If on, GDB keeps breakpoints inserted even if the inferior is
373    stopped, and immediately inserts any new breakpoints as soon as
374    they're created.  If off (default), GDB keeps breakpoints off of
375    the target as long as possible.  That is, it delays inserting
376    breakpoints until the next resume, and removes them again when the
377    target fully stops.  This is a bit safer in case GDB crashes while
378    processing user input.  */
379 static int always_inserted_mode = 0;
380
381 static void
382 show_always_inserted_mode (struct ui_file *file, int from_tty,
383                      struct cmd_list_element *c, const char *value)
384 {
385   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
386                     value);
387 }
388
389 /* See breakpoint.h.  */
390
391 int
392 breakpoints_should_be_inserted_now (void)
393 {
394   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
395     {
396       /* If breakpoints are global, they should be inserted even if no
397          thread under gdb's control is running, or even if there are
398          no threads under GDB's control yet.  */
399       return 1;
400     }
401   else if (target_has_execution)
402     {
403       struct thread_info *tp;
404
405       if (always_inserted_mode)
406         {
407           /* The user wants breakpoints inserted even if all threads
408              are stopped.  */
409           return 1;
410         }
411
412       if (threads_are_executing ())
413         return 1;
414
415       /* Don't remove breakpoints yet if, even though all threads are
416          stopped, we still have events to process.  */
417       ALL_NON_EXITED_THREADS (tp)
418         if (tp->resumed
419             && tp->suspend.waitstatus_pending_p)
420           return 1;
421     }
422   return 0;
423 }
424
425 static const char condition_evaluation_both[] = "host or target";
426
427 /* Modes for breakpoint condition evaluation.  */
428 static const char condition_evaluation_auto[] = "auto";
429 static const char condition_evaluation_host[] = "host";
430 static const char condition_evaluation_target[] = "target";
431 static const char *const condition_evaluation_enums[] = {
432   condition_evaluation_auto,
433   condition_evaluation_host,
434   condition_evaluation_target,
435   NULL
436 };
437
438 /* Global that holds the current mode for breakpoint condition evaluation.  */
439 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
440
441 /* Global that we use to display information to the user (gets its value from
442    condition_evaluation_mode_1.  */
443 static const char *condition_evaluation_mode = condition_evaluation_auto;
444
445 /* Translate a condition evaluation mode MODE into either "host"
446    or "target".  This is used mostly to translate from "auto" to the
447    real setting that is being used.  It returns the translated
448    evaluation mode.  */
449
450 static const char *
451 translate_condition_evaluation_mode (const char *mode)
452 {
453   if (mode == condition_evaluation_auto)
454     {
455       if (target_supports_evaluation_of_breakpoint_conditions ())
456         return condition_evaluation_target;
457       else
458         return condition_evaluation_host;
459     }
460   else
461     return mode;
462 }
463
464 /* Discovers what condition_evaluation_auto translates to.  */
465
466 static const char *
467 breakpoint_condition_evaluation_mode (void)
468 {
469   return translate_condition_evaluation_mode (condition_evaluation_mode);
470 }
471
472 /* Return true if GDB should evaluate breakpoint conditions or false
473    otherwise.  */
474
475 static int
476 gdb_evaluates_breakpoint_condition_p (void)
477 {
478   const char *mode = breakpoint_condition_evaluation_mode ();
479
480   return (mode == condition_evaluation_host);
481 }
482
483 /* Are we executing breakpoint commands?  */
484 static int executing_breakpoint_commands;
485
486 /* Are overlay event breakpoints enabled? */
487 static int overlay_events_enabled;
488
489 /* See description in breakpoint.h. */
490 int target_exact_watchpoints = 0;
491
492 /* Walk the following statement or block through all breakpoints.
493    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
494    current breakpoint.  */
495
496 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
497
498 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
499         for (B = breakpoint_chain;      \
500              B ? (TMP=B->next, 1): 0;   \
501              B = TMP)
502
503 /* Similar iterator for the low-level breakpoints.  SAFE variant is
504    not provided so update_global_location_list must not be called
505    while executing the block of ALL_BP_LOCATIONS.  */
506
507 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
508         for (BP_TMP = bp_locations;                                     \
509              BP_TMP < bp_locations + bp_locations_count && (B = *BP_TMP);\
510              BP_TMP++)
511
512 /* Iterates through locations with address ADDRESS for the currently selected
513    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
514    to where the loop should start from.
515    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
516    appropriate location to start with.  */
517
518 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
519         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
520              BP_LOCP_TMP = BP_LOCP_START;                               \
521              BP_LOCP_START                                              \
522              && (BP_LOCP_TMP < bp_locations + bp_locations_count        \
523              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
524              BP_LOCP_TMP++)
525
526 /* Iterator for tracepoints only.  */
527
528 #define ALL_TRACEPOINTS(B)  \
529   for (B = breakpoint_chain; B; B = B->next)  \
530     if (is_tracepoint (B))
531
532 /* Chains of all breakpoints defined.  */
533
534 struct breakpoint *breakpoint_chain;
535
536 /* Array is sorted by bp_locations_compare - primarily by the ADDRESS.  */
537
538 static struct bp_location **bp_locations;
539
540 /* Number of elements of BP_LOCATIONS.  */
541
542 static unsigned bp_locations_count;
543
544 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
545    ADDRESS for the current elements of BP_LOCATIONS which get a valid
546    result from bp_location_has_shadow.  You can use it for roughly
547    limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
548    an address you need to read.  */
549
550 static CORE_ADDR bp_locations_placed_address_before_address_max;
551
552 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
553    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
554    BP_LOCATIONS which get a valid result from bp_location_has_shadow.
555    You can use it for roughly limiting the subrange of BP_LOCATIONS to
556    scan for shadow bytes for an address you need to read.  */
557
558 static CORE_ADDR bp_locations_shadow_len_after_address_max;
559
560 /* The locations that no longer correspond to any breakpoint, unlinked
561    from the bp_locations array, but for which a hit may still be
562    reported by a target.  */
563 VEC(bp_location_p) *moribund_locations = NULL;
564
565 /* Number of last breakpoint made.  */
566
567 static int breakpoint_count;
568
569 /* The value of `breakpoint_count' before the last command that
570    created breakpoints.  If the last (break-like) command created more
571    than one breakpoint, then the difference between BREAKPOINT_COUNT
572    and PREV_BREAKPOINT_COUNT is more than one.  */
573 static int prev_breakpoint_count;
574
575 /* Number of last tracepoint made.  */
576
577 static int tracepoint_count;
578
579 static struct cmd_list_element *breakpoint_set_cmdlist;
580 static struct cmd_list_element *breakpoint_show_cmdlist;
581 struct cmd_list_element *save_cmdlist;
582
583 /* See declaration at breakpoint.h.  */
584
585 struct breakpoint *
586 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
587                     void *user_data)
588 {
589   struct breakpoint *b = NULL;
590
591   ALL_BREAKPOINTS (b)
592     {
593       if (func (b, user_data) != 0)
594         break;
595     }
596
597   return b;
598 }
599
600 /* Return whether a breakpoint is an active enabled breakpoint.  */
601 static int
602 breakpoint_enabled (struct breakpoint *b)
603 {
604   return (b->enable_state == bp_enabled);
605 }
606
607 /* Set breakpoint count to NUM.  */
608
609 static void
610 set_breakpoint_count (int num)
611 {
612   prev_breakpoint_count = breakpoint_count;
613   breakpoint_count = num;
614   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
615 }
616
617 /* Used by `start_rbreak_breakpoints' below, to record the current
618    breakpoint count before "rbreak" creates any breakpoint.  */
619 static int rbreak_start_breakpoint_count;
620
621 /* Called at the start an "rbreak" command to record the first
622    breakpoint made.  */
623
624 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
625 {
626   rbreak_start_breakpoint_count = breakpoint_count;
627 }
628
629 /* Called at the end of an "rbreak" command to record the last
630    breakpoint made.  */
631
632 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
633 {
634   prev_breakpoint_count = rbreak_start_breakpoint_count;
635 }
636
637 /* Used in run_command to zero the hit count when a new run starts.  */
638
639 void
640 clear_breakpoint_hit_counts (void)
641 {
642   struct breakpoint *b;
643
644   ALL_BREAKPOINTS (b)
645     b->hit_count = 0;
646 }
647
648 \f
649 /* Return the breakpoint with the specified number, or NULL
650    if the number does not refer to an existing breakpoint.  */
651
652 struct breakpoint *
653 get_breakpoint (int num)
654 {
655   struct breakpoint *b;
656
657   ALL_BREAKPOINTS (b)
658     if (b->number == num)
659       return b;
660   
661   return NULL;
662 }
663
664 \f
665
666 /* Mark locations as "conditions have changed" in case the target supports
667    evaluating conditions on its side.  */
668
669 static void
670 mark_breakpoint_modified (struct breakpoint *b)
671 {
672   struct bp_location *loc;
673
674   /* This is only meaningful if the target is
675      evaluating conditions and if the user has
676      opted for condition evaluation on the target's
677      side.  */
678   if (gdb_evaluates_breakpoint_condition_p ()
679       || !target_supports_evaluation_of_breakpoint_conditions ())
680     return;
681
682   if (!is_breakpoint (b))
683     return;
684
685   for (loc = b->loc; loc; loc = loc->next)
686     loc->condition_changed = condition_modified;
687 }
688
689 /* Mark location as "conditions have changed" in case the target supports
690    evaluating conditions on its side.  */
691
692 static void
693 mark_breakpoint_location_modified (struct bp_location *loc)
694 {
695   /* This is only meaningful if the target is
696      evaluating conditions and if the user has
697      opted for condition evaluation on the target's
698      side.  */
699   if (gdb_evaluates_breakpoint_condition_p ()
700       || !target_supports_evaluation_of_breakpoint_conditions ())
701
702     return;
703
704   if (!is_breakpoint (loc->owner))
705     return;
706
707   loc->condition_changed = condition_modified;
708 }
709
710 /* Sets the condition-evaluation mode using the static global
711    condition_evaluation_mode.  */
712
713 static void
714 set_condition_evaluation_mode (const char *args, int from_tty,
715                                struct cmd_list_element *c)
716 {
717   const char *old_mode, *new_mode;
718
719   if ((condition_evaluation_mode_1 == condition_evaluation_target)
720       && !target_supports_evaluation_of_breakpoint_conditions ())
721     {
722       condition_evaluation_mode_1 = condition_evaluation_mode;
723       warning (_("Target does not support breakpoint condition evaluation.\n"
724                  "Using host evaluation mode instead."));
725       return;
726     }
727
728   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
729   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
730
731   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
732      settings was "auto".  */
733   condition_evaluation_mode = condition_evaluation_mode_1;
734
735   /* Only update the mode if the user picked a different one.  */
736   if (new_mode != old_mode)
737     {
738       struct bp_location *loc, **loc_tmp;
739       /* If the user switched to a different evaluation mode, we
740          need to synch the changes with the target as follows:
741
742          "host" -> "target": Send all (valid) conditions to the target.
743          "target" -> "host": Remove all the conditions from the target.
744       */
745
746       if (new_mode == condition_evaluation_target)
747         {
748           /* Mark everything modified and synch conditions with the
749              target.  */
750           ALL_BP_LOCATIONS (loc, loc_tmp)
751             mark_breakpoint_location_modified (loc);
752         }
753       else
754         {
755           /* Manually mark non-duplicate locations to synch conditions
756              with the target.  We do this to remove all the conditions the
757              target knows about.  */
758           ALL_BP_LOCATIONS (loc, loc_tmp)
759             if (is_breakpoint (loc->owner) && loc->inserted)
760               loc->needs_update = 1;
761         }
762
763       /* Do the update.  */
764       update_global_location_list (UGLL_MAY_INSERT);
765     }
766
767   return;
768 }
769
770 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
771    what "auto" is translating to.  */
772
773 static void
774 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
775                                 struct cmd_list_element *c, const char *value)
776 {
777   if (condition_evaluation_mode == condition_evaluation_auto)
778     fprintf_filtered (file,
779                       _("Breakpoint condition evaluation "
780                         "mode is %s (currently %s).\n"),
781                       value,
782                       breakpoint_condition_evaluation_mode ());
783   else
784     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
785                       value);
786 }
787
788 /* A comparison function for bp_location AP and BP that is used by
789    bsearch.  This comparison function only cares about addresses, unlike
790    the more general bp_locations_compare function.  */
791
792 static int
793 bp_locations_compare_addrs (const void *ap, const void *bp)
794 {
795   const struct bp_location *a = *(const struct bp_location **) ap;
796   const struct bp_location *b = *(const struct bp_location **) bp;
797
798   if (a->address == b->address)
799     return 0;
800   else
801     return ((a->address > b->address) - (a->address < b->address));
802 }
803
804 /* Helper function to skip all bp_locations with addresses
805    less than ADDRESS.  It returns the first bp_location that
806    is greater than or equal to ADDRESS.  If none is found, just
807    return NULL.  */
808
809 static struct bp_location **
810 get_first_locp_gte_addr (CORE_ADDR address)
811 {
812   struct bp_location dummy_loc;
813   struct bp_location *dummy_locp = &dummy_loc;
814   struct bp_location **locp_found = NULL;
815
816   /* Initialize the dummy location's address field.  */
817   dummy_loc.address = address;
818
819   /* Find a close match to the first location at ADDRESS.  */
820   locp_found = ((struct bp_location **)
821                 bsearch (&dummy_locp, bp_locations, bp_locations_count,
822                          sizeof (struct bp_location **),
823                          bp_locations_compare_addrs));
824
825   /* Nothing was found, nothing left to do.  */
826   if (locp_found == NULL)
827     return NULL;
828
829   /* We may have found a location that is at ADDRESS but is not the first in the
830      location's list.  Go backwards (if possible) and locate the first one.  */
831   while ((locp_found - 1) >= bp_locations
832          && (*(locp_found - 1))->address == address)
833     locp_found--;
834
835   return locp_found;
836 }
837
838 void
839 set_breakpoint_condition (struct breakpoint *b, const char *exp,
840                           int from_tty)
841 {
842   xfree (b->cond_string);
843   b->cond_string = NULL;
844
845   if (is_watchpoint (b))
846     {
847       struct watchpoint *w = (struct watchpoint *) b;
848
849       w->cond_exp.reset ();
850     }
851   else
852     {
853       struct bp_location *loc;
854
855       for (loc = b->loc; loc; loc = loc->next)
856         {
857           loc->cond.reset ();
858
859           /* No need to free the condition agent expression
860              bytecode (if we have one).  We will handle this
861              when we go through update_global_location_list.  */
862         }
863     }
864
865   if (*exp == 0)
866     {
867       if (from_tty)
868         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
869     }
870   else
871     {
872       const char *arg = exp;
873
874       /* I don't know if it matters whether this is the string the user
875          typed in or the decompiled expression.  */
876       b->cond_string = xstrdup (arg);
877       b->condition_not_parsed = 0;
878
879       if (is_watchpoint (b))
880         {
881           struct watchpoint *w = (struct watchpoint *) b;
882
883           innermost_block.reset ();
884           arg = exp;
885           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
886           if (*arg)
887             error (_("Junk at end of expression"));
888           w->cond_exp_valid_block = innermost_block.block ();
889         }
890       else
891         {
892           struct bp_location *loc;
893
894           for (loc = b->loc; loc; loc = loc->next)
895             {
896               arg = exp;
897               loc->cond =
898                 parse_exp_1 (&arg, loc->address,
899                              block_for_pc (loc->address), 0);
900               if (*arg)
901                 error (_("Junk at end of expression"));
902             }
903         }
904     }
905   mark_breakpoint_modified (b);
906
907   gdb::observers::breakpoint_modified.notify (b);
908 }
909
910 /* Completion for the "condition" command.  */
911
912 static void
913 condition_completer (struct cmd_list_element *cmd,
914                      completion_tracker &tracker,
915                      const char *text, const char *word)
916 {
917   const char *space;
918
919   text = skip_spaces (text);
920   space = skip_to_space (text);
921   if (*space == '\0')
922     {
923       int len;
924       struct breakpoint *b;
925
926       if (text[0] == '$')
927         {
928           /* We don't support completion of history indices.  */
929           if (!isdigit (text[1]))
930             complete_internalvar (tracker, &text[1]);
931           return;
932         }
933
934       /* We're completing the breakpoint number.  */
935       len = strlen (text);
936
937       ALL_BREAKPOINTS (b)
938         {
939           char number[50];
940
941           xsnprintf (number, sizeof (number), "%d", b->number);
942
943           if (strncmp (number, text, len) == 0)
944             {
945               gdb::unique_xmalloc_ptr<char> copy (xstrdup (number));
946               tracker.add_completion (std::move (copy));
947             }
948         }
949
950       return;
951     }
952
953   /* We're completing the expression part.  */
954   text = skip_spaces (space);
955   expression_completer (cmd, tracker, text, word);
956 }
957
958 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
959
960 static void
961 condition_command (const char *arg, int from_tty)
962 {
963   struct breakpoint *b;
964   const char *p;
965   int bnum;
966
967   if (arg == 0)
968     error_no_arg (_("breakpoint number"));
969
970   p = arg;
971   bnum = get_number (&p);
972   if (bnum == 0)
973     error (_("Bad breakpoint argument: '%s'"), arg);
974
975   ALL_BREAKPOINTS (b)
976     if (b->number == bnum)
977       {
978         /* Check if this breakpoint has a "stop" method implemented in an
979            extension language.  This method and conditions entered into GDB
980            from the CLI are mutually exclusive.  */
981         const struct extension_language_defn *extlang
982           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
983
984         if (extlang != NULL)
985           {
986             error (_("Only one stop condition allowed.  There is currently"
987                      " a %s stop condition defined for this breakpoint."),
988                    ext_lang_capitalized_name (extlang));
989           }
990         set_breakpoint_condition (b, p, from_tty);
991
992         if (is_breakpoint (b))
993           update_global_location_list (UGLL_MAY_INSERT);
994
995         return;
996       }
997
998   error (_("No breakpoint number %d."), bnum);
999 }
1000
1001 /* Check that COMMAND do not contain commands that are suitable
1002    only for tracepoints and not suitable for ordinary breakpoints.
1003    Throw if any such commands is found.  */
1004
1005 static void
1006 check_no_tracepoint_commands (struct command_line *commands)
1007 {
1008   struct command_line *c;
1009
1010   for (c = commands; c; c = c->next)
1011     {
1012       int i;
1013
1014       if (c->control_type == while_stepping_control)
1015         error (_("The 'while-stepping' command can "
1016                  "only be used for tracepoints"));
1017
1018       check_no_tracepoint_commands (c->body_list_0.get ());
1019       check_no_tracepoint_commands (c->body_list_1.get ());
1020
1021       /* Not that command parsing removes leading whitespace and comment
1022          lines and also empty lines.  So, we only need to check for
1023          command directly.  */
1024       if (strstr (c->line, "collect ") == c->line)
1025         error (_("The 'collect' command can only be used for tracepoints"));
1026
1027       if (strstr (c->line, "teval ") == c->line)
1028         error (_("The 'teval' command can only be used for tracepoints"));
1029     }
1030 }
1031
1032 struct longjmp_breakpoint : public breakpoint
1033 {
1034   ~longjmp_breakpoint () override;
1035 };
1036
1037 /* Encapsulate tests for different types of tracepoints.  */
1038
1039 static bool
1040 is_tracepoint_type (bptype type)
1041 {
1042   return (type == bp_tracepoint
1043           || type == bp_fast_tracepoint
1044           || type == bp_static_tracepoint);
1045 }
1046
1047 static bool
1048 is_longjmp_type (bptype type)
1049 {
1050   return type == bp_longjmp || type == bp_exception;
1051 }
1052
1053 int
1054 is_tracepoint (const struct breakpoint *b)
1055 {
1056   return is_tracepoint_type (b->type);
1057 }
1058
1059 /* Factory function to create an appropriate instance of breakpoint given
1060    TYPE.  */
1061
1062 static std::unique_ptr<breakpoint>
1063 new_breakpoint_from_type (bptype type)
1064 {
1065   breakpoint *b;
1066
1067   if (is_tracepoint_type (type))
1068     b = new tracepoint ();
1069   else if (is_longjmp_type (type))
1070     b = new longjmp_breakpoint ();
1071   else
1072     b = new breakpoint ();
1073
1074   return std::unique_ptr<breakpoint> (b);
1075 }
1076
1077 /* A helper function that validates that COMMANDS are valid for a
1078    breakpoint.  This function will throw an exception if a problem is
1079    found.  */
1080
1081 static void
1082 validate_commands_for_breakpoint (struct breakpoint *b,
1083                                   struct command_line *commands)
1084 {
1085   if (is_tracepoint (b))
1086     {
1087       struct tracepoint *t = (struct tracepoint *) b;
1088       struct command_line *c;
1089       struct command_line *while_stepping = 0;
1090
1091       /* Reset the while-stepping step count.  The previous commands
1092          might have included a while-stepping action, while the new
1093          ones might not.  */
1094       t->step_count = 0;
1095
1096       /* We need to verify that each top-level element of commands is
1097          valid for tracepoints, that there's at most one
1098          while-stepping element, and that the while-stepping's body
1099          has valid tracing commands excluding nested while-stepping.
1100          We also need to validate the tracepoint action line in the
1101          context of the tracepoint --- validate_actionline actually
1102          has side effects, like setting the tracepoint's
1103          while-stepping STEP_COUNT, in addition to checking if the
1104          collect/teval actions parse and make sense in the
1105          tracepoint's context.  */
1106       for (c = commands; c; c = c->next)
1107         {
1108           if (c->control_type == while_stepping_control)
1109             {
1110               if (b->type == bp_fast_tracepoint)
1111                 error (_("The 'while-stepping' command "
1112                          "cannot be used for fast tracepoint"));
1113               else if (b->type == bp_static_tracepoint)
1114                 error (_("The 'while-stepping' command "
1115                          "cannot be used for static tracepoint"));
1116
1117               if (while_stepping)
1118                 error (_("The 'while-stepping' command "
1119                          "can be used only once"));
1120               else
1121                 while_stepping = c;
1122             }
1123
1124           validate_actionline (c->line, b);
1125         }
1126       if (while_stepping)
1127         {
1128           struct command_line *c2;
1129
1130           gdb_assert (while_stepping->body_list_1 == nullptr);
1131           c2 = while_stepping->body_list_0.get ();
1132           for (; c2; c2 = c2->next)
1133             {
1134               if (c2->control_type == while_stepping_control)
1135                 error (_("The 'while-stepping' command cannot be nested"));
1136             }
1137         }
1138     }
1139   else
1140     {
1141       check_no_tracepoint_commands (commands);
1142     }
1143 }
1144
1145 /* Return a vector of all the static tracepoints set at ADDR.  The
1146    caller is responsible for releasing the vector.  */
1147
1148 std::vector<breakpoint *>
1149 static_tracepoints_here (CORE_ADDR addr)
1150 {
1151   struct breakpoint *b;
1152   std::vector<breakpoint *> found;
1153   struct bp_location *loc;
1154
1155   ALL_BREAKPOINTS (b)
1156     if (b->type == bp_static_tracepoint)
1157       {
1158         for (loc = b->loc; loc; loc = loc->next)
1159           if (loc->address == addr)
1160             found.push_back (b);
1161       }
1162
1163   return found;
1164 }
1165
1166 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1167    validate that only allowed commands are included.  */
1168
1169 void
1170 breakpoint_set_commands (struct breakpoint *b, 
1171                          counted_command_line &&commands)
1172 {
1173   validate_commands_for_breakpoint (b, commands.get ());
1174
1175   b->commands = std::move (commands);
1176   gdb::observers::breakpoint_modified.notify (b);
1177 }
1178
1179 /* Set the internal `silent' flag on the breakpoint.  Note that this
1180    is not the same as the "silent" that may appear in the breakpoint's
1181    commands.  */
1182
1183 void
1184 breakpoint_set_silent (struct breakpoint *b, int silent)
1185 {
1186   int old_silent = b->silent;
1187
1188   b->silent = silent;
1189   if (old_silent != silent)
1190     gdb::observers::breakpoint_modified.notify (b);
1191 }
1192
1193 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1194    breakpoint work for any thread.  */
1195
1196 void
1197 breakpoint_set_thread (struct breakpoint *b, int thread)
1198 {
1199   int old_thread = b->thread;
1200
1201   b->thread = thread;
1202   if (old_thread != thread)
1203     gdb::observers::breakpoint_modified.notify (b);
1204 }
1205
1206 /* Set the task for this breakpoint.  If TASK is 0, make the
1207    breakpoint work for any task.  */
1208
1209 void
1210 breakpoint_set_task (struct breakpoint *b, int task)
1211 {
1212   int old_task = b->task;
1213
1214   b->task = task;
1215   if (old_task != task)
1216     gdb::observers::breakpoint_modified.notify (b);
1217 }
1218
1219 static void
1220 commands_command_1 (const char *arg, int from_tty,
1221                     struct command_line *control)
1222 {
1223   counted_command_line cmd;
1224   /* cmd_read will be true once we have read cmd.  Note that cmd might still be
1225      NULL after the call to read_command_lines if the user provides an empty
1226      list of command by just typing "end".  */
1227   bool cmd_read = false;
1228
1229   std::string new_arg;
1230
1231   if (arg == NULL || !*arg)
1232     {
1233       if (breakpoint_count - prev_breakpoint_count > 1)
1234         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1235                                  breakpoint_count);
1236       else if (breakpoint_count > 0)
1237         new_arg = string_printf ("%d", breakpoint_count);
1238       arg = new_arg.c_str ();
1239     }
1240
1241   map_breakpoint_numbers
1242     (arg, [&] (breakpoint *b)
1243      {
1244        if (!cmd_read)
1245          {
1246            gdb_assert (cmd == NULL);
1247            if (control != NULL)
1248              cmd = control->body_list_0;
1249            else
1250              {
1251                std::string str
1252                  = string_printf (_("Type commands for breakpoint(s) "
1253                                     "%s, one per line."),
1254                                   arg);
1255
1256                auto do_validate = [=] (const char *line)
1257                                   {
1258                                     validate_actionline (line, b);
1259                                   };
1260                gdb::function_view<void (const char *)> validator;
1261                if (is_tracepoint (b))
1262                  validator = do_validate;
1263
1264                cmd = read_command_lines (str.c_str (), from_tty, 1, validator);
1265              }
1266            cmd_read = true;
1267          }
1268
1269        /* If a breakpoint was on the list more than once, we don't need to
1270           do anything.  */
1271        if (b->commands != cmd)
1272          {
1273            validate_commands_for_breakpoint (b, cmd.get ());
1274            b->commands = cmd;
1275            gdb::observers::breakpoint_modified.notify (b);
1276          }
1277      });
1278 }
1279
1280 static void
1281 commands_command (const char *arg, int from_tty)
1282 {
1283   commands_command_1 (arg, from_tty, NULL);
1284 }
1285
1286 /* Like commands_command, but instead of reading the commands from
1287    input stream, takes them from an already parsed command structure.
1288
1289    This is used by cli-script.c to DTRT with breakpoint commands
1290    that are part of if and while bodies.  */
1291 enum command_control_type
1292 commands_from_control_command (const char *arg, struct command_line *cmd)
1293 {
1294   commands_command_1 (arg, 0, cmd);
1295   return simple_control;
1296 }
1297
1298 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1299
1300 static int
1301 bp_location_has_shadow (struct bp_location *bl)
1302 {
1303   if (bl->loc_type != bp_loc_software_breakpoint)
1304     return 0;
1305   if (!bl->inserted)
1306     return 0;
1307   if (bl->target_info.shadow_len == 0)
1308     /* BL isn't valid, or doesn't shadow memory.  */
1309     return 0;
1310   return 1;
1311 }
1312
1313 /* Update BUF, which is LEN bytes read from the target address
1314    MEMADDR, by replacing a memory breakpoint with its shadowed
1315    contents.
1316
1317    If READBUF is not NULL, this buffer must not overlap with the of
1318    the breakpoint location's shadow_contents buffer.  Otherwise, a
1319    failed assertion internal error will be raised.  */
1320
1321 static void
1322 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1323                             const gdb_byte *writebuf_org,
1324                             ULONGEST memaddr, LONGEST len,
1325                             struct bp_target_info *target_info,
1326                             struct gdbarch *gdbarch)
1327 {
1328   /* Now do full processing of the found relevant range of elements.  */
1329   CORE_ADDR bp_addr = 0;
1330   int bp_size = 0;
1331   int bptoffset = 0;
1332
1333   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1334                                  current_program_space->aspace, 0))
1335     {
1336       /* The breakpoint is inserted in a different address space.  */
1337       return;
1338     }
1339
1340   /* Addresses and length of the part of the breakpoint that
1341      we need to copy.  */
1342   bp_addr = target_info->placed_address;
1343   bp_size = target_info->shadow_len;
1344
1345   if (bp_addr + bp_size <= memaddr)
1346     {
1347       /* The breakpoint is entirely before the chunk of memory we are
1348          reading.  */
1349       return;
1350     }
1351
1352   if (bp_addr >= memaddr + len)
1353     {
1354       /* The breakpoint is entirely after the chunk of memory we are
1355          reading.  */
1356       return;
1357     }
1358
1359   /* Offset within shadow_contents.  */
1360   if (bp_addr < memaddr)
1361     {
1362       /* Only copy the second part of the breakpoint.  */
1363       bp_size -= memaddr - bp_addr;
1364       bptoffset = memaddr - bp_addr;
1365       bp_addr = memaddr;
1366     }
1367
1368   if (bp_addr + bp_size > memaddr + len)
1369     {
1370       /* Only copy the first part of the breakpoint.  */
1371       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1372     }
1373
1374   if (readbuf != NULL)
1375     {
1376       /* Verify that the readbuf buffer does not overlap with the
1377          shadow_contents buffer.  */
1378       gdb_assert (target_info->shadow_contents >= readbuf + len
1379                   || readbuf >= (target_info->shadow_contents
1380                                  + target_info->shadow_len));
1381
1382       /* Update the read buffer with this inserted breakpoint's
1383          shadow.  */
1384       memcpy (readbuf + bp_addr - memaddr,
1385               target_info->shadow_contents + bptoffset, bp_size);
1386     }
1387   else
1388     {
1389       const unsigned char *bp;
1390       CORE_ADDR addr = target_info->reqstd_address;
1391       int placed_size;
1392
1393       /* Update the shadow with what we want to write to memory.  */
1394       memcpy (target_info->shadow_contents + bptoffset,
1395               writebuf_org + bp_addr - memaddr, bp_size);
1396
1397       /* Determine appropriate breakpoint contents and size for this
1398          address.  */
1399       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1400
1401       /* Update the final write buffer with this inserted
1402          breakpoint's INSN.  */
1403       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1404     }
1405 }
1406
1407 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1408    by replacing any memory breakpoints with their shadowed contents.
1409
1410    If READBUF is not NULL, this buffer must not overlap with any of
1411    the breakpoint location's shadow_contents buffers.  Otherwise,
1412    a failed assertion internal error will be raised.
1413
1414    The range of shadowed area by each bp_location is:
1415      bl->address - bp_locations_placed_address_before_address_max
1416      up to bl->address + bp_locations_shadow_len_after_address_max
1417    The range we were requested to resolve shadows for is:
1418      memaddr ... memaddr + len
1419    Thus the safe cutoff boundaries for performance optimization are
1420      memaddr + len <= (bl->address
1421                        - bp_locations_placed_address_before_address_max)
1422    and:
1423      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1424
1425 void
1426 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1427                         const gdb_byte *writebuf_org,
1428                         ULONGEST memaddr, LONGEST len)
1429 {
1430   /* Left boundary, right boundary and median element of our binary
1431      search.  */
1432   unsigned bc_l, bc_r, bc;
1433
1434   /* Find BC_L which is a leftmost element which may affect BUF
1435      content.  It is safe to report lower value but a failure to
1436      report higher one.  */
1437
1438   bc_l = 0;
1439   bc_r = bp_locations_count;
1440   while (bc_l + 1 < bc_r)
1441     {
1442       struct bp_location *bl;
1443
1444       bc = (bc_l + bc_r) / 2;
1445       bl = bp_locations[bc];
1446
1447       /* Check first BL->ADDRESS will not overflow due to the added
1448          constant.  Then advance the left boundary only if we are sure
1449          the BC element can in no way affect the BUF content (MEMADDR
1450          to MEMADDR + LEN range).
1451
1452          Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1453          offset so that we cannot miss a breakpoint with its shadow
1454          range tail still reaching MEMADDR.  */
1455
1456       if ((bl->address + bp_locations_shadow_len_after_address_max
1457            >= bl->address)
1458           && (bl->address + bp_locations_shadow_len_after_address_max
1459               <= memaddr))
1460         bc_l = bc;
1461       else
1462         bc_r = bc;
1463     }
1464
1465   /* Due to the binary search above, we need to make sure we pick the
1466      first location that's at BC_L's address.  E.g., if there are
1467      multiple locations at the same address, BC_L may end up pointing
1468      at a duplicate location, and miss the "master"/"inserted"
1469      location.  Say, given locations L1, L2 and L3 at addresses A and
1470      B:
1471
1472       L1@A, L2@A, L3@B, ...
1473
1474      BC_L could end up pointing at location L2, while the "master"
1475      location could be L1.  Since the `loc->inserted' flag is only set
1476      on "master" locations, we'd forget to restore the shadow of L1
1477      and L2.  */
1478   while (bc_l > 0
1479          && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1480     bc_l--;
1481
1482   /* Now do full processing of the found relevant range of elements.  */
1483
1484   for (bc = bc_l; bc < bp_locations_count; bc++)
1485   {
1486     struct bp_location *bl = bp_locations[bc];
1487
1488     /* bp_location array has BL->OWNER always non-NULL.  */
1489     if (bl->owner->type == bp_none)
1490       warning (_("reading through apparently deleted breakpoint #%d?"),
1491                bl->owner->number);
1492
1493     /* Performance optimization: any further element can no longer affect BUF
1494        content.  */
1495
1496     if (bl->address >= bp_locations_placed_address_before_address_max
1497         && memaddr + len <= (bl->address
1498                              - bp_locations_placed_address_before_address_max))
1499       break;
1500
1501     if (!bp_location_has_shadow (bl))
1502       continue;
1503
1504     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1505                                 memaddr, len, &bl->target_info, bl->gdbarch);
1506   }
1507 }
1508
1509 \f
1510
1511 /* Return true if BPT is either a software breakpoint or a hardware
1512    breakpoint.  */
1513
1514 int
1515 is_breakpoint (const struct breakpoint *bpt)
1516 {
1517   return (bpt->type == bp_breakpoint
1518           || bpt->type == bp_hardware_breakpoint
1519           || bpt->type == bp_dprintf);
1520 }
1521
1522 /* Return true if BPT is of any hardware watchpoint kind.  */
1523
1524 static int
1525 is_hardware_watchpoint (const struct breakpoint *bpt)
1526 {
1527   return (bpt->type == bp_hardware_watchpoint
1528           || bpt->type == bp_read_watchpoint
1529           || bpt->type == bp_access_watchpoint);
1530 }
1531
1532 /* Return true if BPT is of any watchpoint kind, hardware or
1533    software.  */
1534
1535 int
1536 is_watchpoint (const struct breakpoint *bpt)
1537 {
1538   return (is_hardware_watchpoint (bpt)
1539           || bpt->type == bp_watchpoint);
1540 }
1541
1542 /* Returns true if the current thread and its running state are safe
1543    to evaluate or update watchpoint B.  Watchpoints on local
1544    expressions need to be evaluated in the context of the thread that
1545    was current when the watchpoint was created, and, that thread needs
1546    to be stopped to be able to select the correct frame context.
1547    Watchpoints on global expressions can be evaluated on any thread,
1548    and in any state.  It is presently left to the target allowing
1549    memory accesses when threads are running.  */
1550
1551 static int
1552 watchpoint_in_thread_scope (struct watchpoint *b)
1553 {
1554   return (b->pspace == current_program_space
1555           && (b->watchpoint_thread == null_ptid
1556               || (inferior_ptid == b->watchpoint_thread
1557                   && !inferior_thread ()->executing)));
1558 }
1559
1560 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1561    associated bp_watchpoint_scope breakpoint.  */
1562
1563 static void
1564 watchpoint_del_at_next_stop (struct watchpoint *w)
1565 {
1566   if (w->related_breakpoint != w)
1567     {
1568       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1569       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1570       w->related_breakpoint->disposition = disp_del_at_next_stop;
1571       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1572       w->related_breakpoint = w;
1573     }
1574   w->disposition = disp_del_at_next_stop;
1575 }
1576
1577 /* Extract a bitfield value from value VAL using the bit parameters contained in
1578    watchpoint W.  */
1579
1580 static struct value *
1581 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1582 {
1583   struct value *bit_val;
1584
1585   if (val == NULL)
1586     return NULL;
1587
1588   bit_val = allocate_value (value_type (val));
1589
1590   unpack_value_bitfield (bit_val,
1591                          w->val_bitpos,
1592                          w->val_bitsize,
1593                          value_contents_for_printing (val),
1594                          value_offset (val),
1595                          val);
1596
1597   return bit_val;
1598 }
1599
1600 /* Allocate a dummy location and add it to B, which must be a software
1601    watchpoint.  This is required because even if a software watchpoint
1602    is not watching any memory, bpstat_stop_status requires a location
1603    to be able to report stops.  */
1604
1605 static void
1606 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1607                                             struct program_space *pspace)
1608 {
1609   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1610
1611   b->loc = allocate_bp_location (b);
1612   b->loc->pspace = pspace;
1613   b->loc->address = -1;
1614   b->loc->length = -1;
1615 }
1616
1617 /* Returns true if B is a software watchpoint that is not watching any
1618    memory (e.g., "watch $pc").  */
1619
1620 static int
1621 is_no_memory_software_watchpoint (struct breakpoint *b)
1622 {
1623   return (b->type == bp_watchpoint
1624           && b->loc != NULL
1625           && b->loc->next == NULL
1626           && b->loc->address == -1
1627           && b->loc->length == -1);
1628 }
1629
1630 /* Assuming that B is a watchpoint:
1631    - Reparse watchpoint expression, if REPARSE is non-zero
1632    - Evaluate expression and store the result in B->val
1633    - Evaluate the condition if there is one, and store the result
1634      in b->loc->cond.
1635    - Update the list of values that must be watched in B->loc.
1636
1637    If the watchpoint disposition is disp_del_at_next_stop, then do
1638    nothing.  If this is local watchpoint that is out of scope, delete
1639    it.
1640
1641    Even with `set breakpoint always-inserted on' the watchpoints are
1642    removed + inserted on each stop here.  Normal breakpoints must
1643    never be removed because they might be missed by a running thread
1644    when debugging in non-stop mode.  On the other hand, hardware
1645    watchpoints (is_hardware_watchpoint; processed here) are specific
1646    to each LWP since they are stored in each LWP's hardware debug
1647    registers.  Therefore, such LWP must be stopped first in order to
1648    be able to modify its hardware watchpoints.
1649
1650    Hardware watchpoints must be reset exactly once after being
1651    presented to the user.  It cannot be done sooner, because it would
1652    reset the data used to present the watchpoint hit to the user.  And
1653    it must not be done later because it could display the same single
1654    watchpoint hit during multiple GDB stops.  Note that the latter is
1655    relevant only to the hardware watchpoint types bp_read_watchpoint
1656    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1657    not user-visible - its hit is suppressed if the memory content has
1658    not changed.
1659
1660    The following constraints influence the location where we can reset
1661    hardware watchpoints:
1662
1663    * target_stopped_by_watchpoint and target_stopped_data_address are
1664      called several times when GDB stops.
1665
1666    [linux] 
1667    * Multiple hardware watchpoints can be hit at the same time,
1668      causing GDB to stop.  GDB only presents one hardware watchpoint
1669      hit at a time as the reason for stopping, and all the other hits
1670      are presented later, one after the other, each time the user
1671      requests the execution to be resumed.  Execution is not resumed
1672      for the threads still having pending hit event stored in
1673      LWP_INFO->STATUS.  While the watchpoint is already removed from
1674      the inferior on the first stop the thread hit event is kept being
1675      reported from its cached value by linux_nat_stopped_data_address
1676      until the real thread resume happens after the watchpoint gets
1677      presented and thus its LWP_INFO->STATUS gets reset.
1678
1679    Therefore the hardware watchpoint hit can get safely reset on the
1680    watchpoint removal from inferior.  */
1681
1682 static void
1683 update_watchpoint (struct watchpoint *b, int reparse)
1684 {
1685   int within_current_scope;
1686   struct frame_id saved_frame_id;
1687   int frame_saved;
1688
1689   /* If this is a local watchpoint, we only want to check if the
1690      watchpoint frame is in scope if the current thread is the thread
1691      that was used to create the watchpoint.  */
1692   if (!watchpoint_in_thread_scope (b))
1693     return;
1694
1695   if (b->disposition == disp_del_at_next_stop)
1696     return;
1697  
1698   frame_saved = 0;
1699
1700   /* Determine if the watchpoint is within scope.  */
1701   if (b->exp_valid_block == NULL)
1702     within_current_scope = 1;
1703   else
1704     {
1705       struct frame_info *fi = get_current_frame ();
1706       struct gdbarch *frame_arch = get_frame_arch (fi);
1707       CORE_ADDR frame_pc = get_frame_pc (fi);
1708
1709       /* If we're at a point where the stack has been destroyed
1710          (e.g. in a function epilogue), unwinding may not work
1711          properly. Do not attempt to recreate locations at this
1712          point.  See similar comments in watchpoint_check.  */
1713       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1714         return;
1715
1716       /* Save the current frame's ID so we can restore it after
1717          evaluating the watchpoint expression on its own frame.  */
1718       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1719          took a frame parameter, so that we didn't have to change the
1720          selected frame.  */
1721       frame_saved = 1;
1722       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1723
1724       fi = frame_find_by_id (b->watchpoint_frame);
1725       within_current_scope = (fi != NULL);
1726       if (within_current_scope)
1727         select_frame (fi);
1728     }
1729
1730   /* We don't free locations.  They are stored in the bp_location array
1731      and update_global_location_list will eventually delete them and
1732      remove breakpoints if needed.  */
1733   b->loc = NULL;
1734
1735   if (within_current_scope && reparse)
1736     {
1737       const char *s;
1738
1739       b->exp.reset ();
1740       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1741       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1742       /* If the meaning of expression itself changed, the old value is
1743          no longer relevant.  We don't want to report a watchpoint hit
1744          to the user when the old value and the new value may actually
1745          be completely different objects.  */
1746       b->val = NULL;
1747       b->val_valid = 0;
1748
1749       /* Note that unlike with breakpoints, the watchpoint's condition
1750          expression is stored in the breakpoint object, not in the
1751          locations (re)created below.  */
1752       if (b->cond_string != NULL)
1753         {
1754           b->cond_exp.reset ();
1755
1756           s = b->cond_string;
1757           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1758         }
1759     }
1760
1761   /* If we failed to parse the expression, for example because
1762      it refers to a global variable in a not-yet-loaded shared library,
1763      don't try to insert watchpoint.  We don't automatically delete
1764      such watchpoint, though, since failure to parse expression
1765      is different from out-of-scope watchpoint.  */
1766   if (!target_has_execution)
1767     {
1768       /* Without execution, memory can't change.  No use to try and
1769          set watchpoint locations.  The watchpoint will be reset when
1770          the target gains execution, through breakpoint_re_set.  */
1771       if (!can_use_hw_watchpoints)
1772         {
1773           if (b->ops->works_in_software_mode (b))
1774             b->type = bp_watchpoint;
1775           else
1776             error (_("Can't set read/access watchpoint when "
1777                      "hardware watchpoints are disabled."));
1778         }
1779     }
1780   else if (within_current_scope && b->exp)
1781     {
1782       int pc = 0;
1783       std::vector<value_ref_ptr> val_chain;
1784       struct value *v, *result, *next;
1785       struct program_space *frame_pspace;
1786
1787       fetch_subexp_value (b->exp.get (), &pc, &v, &result, &val_chain, 0);
1788
1789       /* Avoid setting b->val if it's already set.  The meaning of
1790          b->val is 'the last value' user saw, and we should update
1791          it only if we reported that last value to user.  As it
1792          happens, the code that reports it updates b->val directly.
1793          We don't keep track of the memory value for masked
1794          watchpoints.  */
1795       if (!b->val_valid && !is_masked_watchpoint (b))
1796         {
1797           if (b->val_bitsize != 0)
1798             v = extract_bitfield_from_watchpoint_value (b, v);
1799           b->val = release_value (v);
1800           b->val_valid = 1;
1801         }
1802
1803       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1804
1805       /* Look at each value on the value chain.  */
1806       gdb_assert (!val_chain.empty ());
1807       for (const value_ref_ptr &iter : val_chain)
1808         {
1809           v = iter.get ();
1810
1811           /* If it's a memory location, and GDB actually needed
1812              its contents to evaluate the expression, then we
1813              must watch it.  If the first value returned is
1814              still lazy, that means an error occurred reading it;
1815              watch it anyway in case it becomes readable.  */
1816           if (VALUE_LVAL (v) == lval_memory
1817               && (v == val_chain[0] || ! value_lazy (v)))
1818             {
1819               struct type *vtype = check_typedef (value_type (v));
1820
1821               /* We only watch structs and arrays if user asked
1822                  for it explicitly, never if they just happen to
1823                  appear in the middle of some value chain.  */
1824               if (v == result
1825                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1826                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1827                 {
1828                   CORE_ADDR addr;
1829                   enum target_hw_bp_type type;
1830                   struct bp_location *loc, **tmp;
1831                   int bitpos = 0, bitsize = 0;
1832
1833                   if (value_bitsize (v) != 0)
1834                     {
1835                       /* Extract the bit parameters out from the bitfield
1836                          sub-expression.  */
1837                       bitpos = value_bitpos (v);
1838                       bitsize = value_bitsize (v);
1839                     }
1840                   else if (v == result && b->val_bitsize != 0)
1841                     {
1842                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1843                         lvalue whose bit parameters are saved in the fields
1844                         VAL_BITPOS and VAL_BITSIZE.  */
1845                       bitpos = b->val_bitpos;
1846                       bitsize = b->val_bitsize;
1847                     }
1848
1849                   addr = value_address (v);
1850                   if (bitsize != 0)
1851                     {
1852                       /* Skip the bytes that don't contain the bitfield.  */
1853                       addr += bitpos / 8;
1854                     }
1855
1856                   type = hw_write;
1857                   if (b->type == bp_read_watchpoint)
1858                     type = hw_read;
1859                   else if (b->type == bp_access_watchpoint)
1860                     type = hw_access;
1861
1862                   loc = allocate_bp_location (b);
1863                   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
1864                     ;
1865                   *tmp = loc;
1866                   loc->gdbarch = get_type_arch (value_type (v));
1867
1868                   loc->pspace = frame_pspace;
1869                   loc->address = address_significant (loc->gdbarch, addr);
1870
1871                   if (bitsize != 0)
1872                     {
1873                       /* Just cover the bytes that make up the bitfield.  */
1874                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
1875                     }
1876                   else
1877                     loc->length = TYPE_LENGTH (value_type (v));
1878
1879                   loc->watchpoint_type = type;
1880                 }
1881             }
1882         }
1883
1884       /* Change the type of breakpoint between hardware assisted or
1885          an ordinary watchpoint depending on the hardware support
1886          and free hardware slots.  REPARSE is set when the inferior
1887          is started.  */
1888       if (reparse)
1889         {
1890           int reg_cnt;
1891           enum bp_loc_type loc_type;
1892           struct bp_location *bl;
1893
1894           reg_cnt = can_use_hardware_watchpoint (val_chain);
1895
1896           if (reg_cnt)
1897             {
1898               int i, target_resources_ok, other_type_used;
1899               enum bptype type;
1900
1901               /* Use an exact watchpoint when there's only one memory region to be
1902                  watched, and only one debug register is needed to watch it.  */
1903               b->exact = target_exact_watchpoints && reg_cnt == 1;
1904
1905               /* We need to determine how many resources are already
1906                  used for all other hardware watchpoints plus this one
1907                  to see if we still have enough resources to also fit
1908                  this watchpoint in as well.  */
1909
1910               /* If this is a software watchpoint, we try to turn it
1911                  to a hardware one -- count resources as if B was of
1912                  hardware watchpoint type.  */
1913               type = b->type;
1914               if (type == bp_watchpoint)
1915                 type = bp_hardware_watchpoint;
1916
1917               /* This watchpoint may or may not have been placed on
1918                  the list yet at this point (it won't be in the list
1919                  if we're trying to create it for the first time,
1920                  through watch_command), so always account for it
1921                  manually.  */
1922
1923               /* Count resources used by all watchpoints except B.  */
1924               i = hw_watchpoint_used_count_others (b, type, &other_type_used);
1925
1926               /* Add in the resources needed for B.  */
1927               i += hw_watchpoint_use_count (b);
1928
1929               target_resources_ok
1930                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1931               if (target_resources_ok <= 0)
1932                 {
1933                   int sw_mode = b->ops->works_in_software_mode (b);
1934
1935                   if (target_resources_ok == 0 && !sw_mode)
1936                     error (_("Target does not support this type of "
1937                              "hardware watchpoint."));
1938                   else if (target_resources_ok < 0 && !sw_mode)
1939                     error (_("There are not enough available hardware "
1940                              "resources for this watchpoint."));
1941
1942                   /* Downgrade to software watchpoint.  */
1943                   b->type = bp_watchpoint;
1944                 }
1945               else
1946                 {
1947                   /* If this was a software watchpoint, we've just
1948                      found we have enough resources to turn it to a
1949                      hardware watchpoint.  Otherwise, this is a
1950                      nop.  */
1951                   b->type = type;
1952                 }
1953             }
1954           else if (!b->ops->works_in_software_mode (b))
1955             {
1956               if (!can_use_hw_watchpoints)
1957                 error (_("Can't set read/access watchpoint when "
1958                          "hardware watchpoints are disabled."));
1959               else
1960                 error (_("Expression cannot be implemented with "
1961                          "read/access watchpoint."));
1962             }
1963           else
1964             b->type = bp_watchpoint;
1965
1966           loc_type = (b->type == bp_watchpoint? bp_loc_other
1967                       : bp_loc_hardware_watchpoint);
1968           for (bl = b->loc; bl; bl = bl->next)
1969             bl->loc_type = loc_type;
1970         }
1971
1972       /* If a software watchpoint is not watching any memory, then the
1973          above left it without any location set up.  But,
1974          bpstat_stop_status requires a location to be able to report
1975          stops, so make sure there's at least a dummy one.  */
1976       if (b->type == bp_watchpoint && b->loc == NULL)
1977         software_watchpoint_add_no_memory_location (b, frame_pspace);
1978     }
1979   else if (!within_current_scope)
1980     {
1981       printf_filtered (_("\
1982 Watchpoint %d deleted because the program has left the block\n\
1983 in which its expression is valid.\n"),
1984                        b->number);
1985       watchpoint_del_at_next_stop (b);
1986     }
1987
1988   /* Restore the selected frame.  */
1989   if (frame_saved)
1990     select_frame (frame_find_by_id (saved_frame_id));
1991 }
1992
1993
1994 /* Returns 1 iff breakpoint location should be
1995    inserted in the inferior.  We don't differentiate the type of BL's owner
1996    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1997    breakpoint_ops is not defined, because in insert_bp_location,
1998    tracepoint's insert_location will not be called.  */
1999 static int
2000 should_be_inserted (struct bp_location *bl)
2001 {
2002   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2003     return 0;
2004
2005   if (bl->owner->disposition == disp_del_at_next_stop)
2006     return 0;
2007
2008   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2009     return 0;
2010
2011   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2012     return 0;
2013
2014   /* This is set for example, when we're attached to the parent of a
2015      vfork, and have detached from the child.  The child is running
2016      free, and we expect it to do an exec or exit, at which point the
2017      OS makes the parent schedulable again (and the target reports
2018      that the vfork is done).  Until the child is done with the shared
2019      memory region, do not insert breakpoints in the parent, otherwise
2020      the child could still trip on the parent's breakpoints.  Since
2021      the parent is blocked anyway, it won't miss any breakpoint.  */
2022   if (bl->pspace->breakpoints_not_allowed)
2023     return 0;
2024
2025   /* Don't insert a breakpoint if we're trying to step past its
2026      location, except if the breakpoint is a single-step breakpoint,
2027      and the breakpoint's thread is the thread which is stepping past
2028      a breakpoint.  */
2029   if ((bl->loc_type == bp_loc_software_breakpoint
2030        || bl->loc_type == bp_loc_hardware_breakpoint)
2031       && stepping_past_instruction_at (bl->pspace->aspace,
2032                                        bl->address)
2033       /* The single-step breakpoint may be inserted at the location
2034          we're trying to step if the instruction branches to itself.
2035          However, the instruction won't be executed at all and it may
2036          break the semantics of the instruction, for example, the
2037          instruction is a conditional branch or updates some flags.
2038          We can't fix it unless GDB is able to emulate the instruction
2039          or switch to displaced stepping.  */
2040       && !(bl->owner->type == bp_single_step
2041            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2042     {
2043       if (debug_infrun)
2044         {
2045           fprintf_unfiltered (gdb_stdlog,
2046                               "infrun: skipping breakpoint: "
2047                               "stepping past insn at: %s\n",
2048                               paddress (bl->gdbarch, bl->address));
2049         }
2050       return 0;
2051     }
2052
2053   /* Don't insert watchpoints if we're trying to step past the
2054      instruction that triggered one.  */
2055   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2056       && stepping_past_nonsteppable_watchpoint ())
2057     {
2058       if (debug_infrun)
2059         {
2060           fprintf_unfiltered (gdb_stdlog,
2061                               "infrun: stepping past non-steppable watchpoint. "
2062                               "skipping watchpoint at %s:%d\n",
2063                               paddress (bl->gdbarch, bl->address),
2064                               bl->length);
2065         }
2066       return 0;
2067     }
2068
2069   return 1;
2070 }
2071
2072 /* Same as should_be_inserted but does the check assuming
2073    that the location is not duplicated.  */
2074
2075 static int
2076 unduplicated_should_be_inserted (struct bp_location *bl)
2077 {
2078   int result;
2079   const int save_duplicate = bl->duplicate;
2080
2081   bl->duplicate = 0;
2082   result = should_be_inserted (bl);
2083   bl->duplicate = save_duplicate;
2084   return result;
2085 }
2086
2087 /* Parses a conditional described by an expression COND into an
2088    agent expression bytecode suitable for evaluation
2089    by the bytecode interpreter.  Return NULL if there was
2090    any error during parsing.  */
2091
2092 static agent_expr_up
2093 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2094 {
2095   if (cond == NULL)
2096     return NULL;
2097
2098   agent_expr_up aexpr;
2099
2100   /* We don't want to stop processing, so catch any errors
2101      that may show up.  */
2102   TRY
2103     {
2104       aexpr = gen_eval_for_expr (scope, cond);
2105     }
2106
2107   CATCH (ex, RETURN_MASK_ERROR)
2108     {
2109       /* If we got here, it means the condition could not be parsed to a valid
2110          bytecode expression and thus can't be evaluated on the target's side.
2111          It's no use iterating through the conditions.  */
2112     }
2113   END_CATCH
2114
2115   /* We have a valid agent expression.  */
2116   return aexpr;
2117 }
2118
2119 /* Based on location BL, create a list of breakpoint conditions to be
2120    passed on to the target.  If we have duplicated locations with different
2121    conditions, we will add such conditions to the list.  The idea is that the
2122    target will evaluate the list of conditions and will only notify GDB when
2123    one of them is true.  */
2124
2125 static void
2126 build_target_condition_list (struct bp_location *bl)
2127 {
2128   struct bp_location **locp = NULL, **loc2p;
2129   int null_condition_or_parse_error = 0;
2130   int modified = bl->needs_update;
2131   struct bp_location *loc;
2132
2133   /* Release conditions left over from a previous insert.  */
2134   bl->target_info.conditions.clear ();
2135
2136   /* This is only meaningful if the target is
2137      evaluating conditions and if the user has
2138      opted for condition evaluation on the target's
2139      side.  */
2140   if (gdb_evaluates_breakpoint_condition_p ()
2141       || !target_supports_evaluation_of_breakpoint_conditions ())
2142     return;
2143
2144   /* Do a first pass to check for locations with no assigned
2145      conditions or conditions that fail to parse to a valid agent expression
2146      bytecode.  If any of these happen, then it's no use to send conditions
2147      to the target since this location will always trigger and generate a
2148      response back to GDB.  */
2149   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2150     {
2151       loc = (*loc2p);
2152       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2153         {
2154           if (modified)
2155             {
2156               /* Re-parse the conditions since something changed.  In that
2157                  case we already freed the condition bytecodes (see
2158                  force_breakpoint_reinsertion).  We just
2159                  need to parse the condition to bytecodes again.  */
2160               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2161                                                         loc->cond.get ());
2162             }
2163
2164           /* If we have a NULL bytecode expression, it means something
2165              went wrong or we have a null condition expression.  */
2166           if (!loc->cond_bytecode)
2167             {
2168               null_condition_or_parse_error = 1;
2169               break;
2170             }
2171         }
2172     }
2173
2174   /* If any of these happened, it means we will have to evaluate the conditions
2175      for the location's address on gdb's side.  It is no use keeping bytecodes
2176      for all the other duplicate locations, thus we free all of them here.
2177
2178      This is so we have a finer control over which locations' conditions are
2179      being evaluated by GDB or the remote stub.  */
2180   if (null_condition_or_parse_error)
2181     {
2182       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2183         {
2184           loc = (*loc2p);
2185           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2186             {
2187               /* Only go as far as the first NULL bytecode is
2188                  located.  */
2189               if (!loc->cond_bytecode)
2190                 return;
2191
2192               loc->cond_bytecode.reset ();
2193             }
2194         }
2195     }
2196
2197   /* No NULL conditions or failed bytecode generation.  Build a condition list
2198      for this location's address.  */
2199   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2200     {
2201       loc = (*loc2p);
2202       if (loc->cond
2203           && is_breakpoint (loc->owner)
2204           && loc->pspace->num == bl->pspace->num
2205           && loc->owner->enable_state == bp_enabled
2206           && loc->enabled)
2207         {
2208           /* Add the condition to the vector.  This will be used later
2209              to send the conditions to the target.  */
2210           bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2211         }
2212     }
2213
2214   return;
2215 }
2216
2217 /* Parses a command described by string CMD into an agent expression
2218    bytecode suitable for evaluation by the bytecode interpreter.
2219    Return NULL if there was any error during parsing.  */
2220
2221 static agent_expr_up
2222 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2223 {
2224   const char *cmdrest;
2225   const char *format_start, *format_end;
2226   struct gdbarch *gdbarch = get_current_arch ();
2227
2228   if (cmd == NULL)
2229     return NULL;
2230
2231   cmdrest = cmd;
2232
2233   if (*cmdrest == ',')
2234     ++cmdrest;
2235   cmdrest = skip_spaces (cmdrest);
2236
2237   if (*cmdrest++ != '"')
2238     error (_("No format string following the location"));
2239
2240   format_start = cmdrest;
2241
2242   format_pieces fpieces (&cmdrest);
2243
2244   format_end = cmdrest;
2245
2246   if (*cmdrest++ != '"')
2247     error (_("Bad format string, non-terminated '\"'."));
2248   
2249   cmdrest = skip_spaces (cmdrest);
2250
2251   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2252     error (_("Invalid argument syntax"));
2253
2254   if (*cmdrest == ',')
2255     cmdrest++;
2256   cmdrest = skip_spaces (cmdrest);
2257
2258   /* For each argument, make an expression.  */
2259
2260   std::vector<struct expression *> argvec;
2261   while (*cmdrest != '\0')
2262     {
2263       const char *cmd1;
2264
2265       cmd1 = cmdrest;
2266       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2267       argvec.push_back (expr.release ());
2268       cmdrest = cmd1;
2269       if (*cmdrest == ',')
2270         ++cmdrest;
2271     }
2272
2273   agent_expr_up aexpr;
2274
2275   /* We don't want to stop processing, so catch any errors
2276      that may show up.  */
2277   TRY
2278     {
2279       aexpr = gen_printf (scope, gdbarch, 0, 0,
2280                           format_start, format_end - format_start,
2281                           argvec.size (), argvec.data ());
2282     }
2283   CATCH (ex, RETURN_MASK_ERROR)
2284     {
2285       /* If we got here, it means the command could not be parsed to a valid
2286          bytecode expression and thus can't be evaluated on the target's side.
2287          It's no use iterating through the other commands.  */
2288     }
2289   END_CATCH
2290
2291   /* We have a valid agent expression, return it.  */
2292   return aexpr;
2293 }
2294
2295 /* Based on location BL, create a list of breakpoint commands to be
2296    passed on to the target.  If we have duplicated locations with
2297    different commands, we will add any such to the list.  */
2298
2299 static void
2300 build_target_command_list (struct bp_location *bl)
2301 {
2302   struct bp_location **locp = NULL, **loc2p;
2303   int null_command_or_parse_error = 0;
2304   int modified = bl->needs_update;
2305   struct bp_location *loc;
2306
2307   /* Clear commands left over from a previous insert.  */
2308   bl->target_info.tcommands.clear ();
2309
2310   if (!target_can_run_breakpoint_commands ())
2311     return;
2312
2313   /* For now, limit to agent-style dprintf breakpoints.  */
2314   if (dprintf_style != dprintf_style_agent)
2315     return;
2316
2317   /* For now, if we have any duplicate location that isn't a dprintf,
2318      don't install the target-side commands, as that would make the
2319      breakpoint not be reported to the core, and we'd lose
2320      control.  */
2321   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2322     {
2323       loc = (*loc2p);
2324       if (is_breakpoint (loc->owner)
2325           && loc->pspace->num == bl->pspace->num
2326           && loc->owner->type != bp_dprintf)
2327         return;
2328     }
2329
2330   /* Do a first pass to check for locations with no assigned
2331      conditions or conditions that fail to parse to a valid agent expression
2332      bytecode.  If any of these happen, then it's no use to send conditions
2333      to the target since this location will always trigger and generate a
2334      response back to GDB.  */
2335   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2336     {
2337       loc = (*loc2p);
2338       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2339         {
2340           if (modified)
2341             {
2342               /* Re-parse the commands since something changed.  In that
2343                  case we already freed the command bytecodes (see
2344                  force_breakpoint_reinsertion).  We just
2345                  need to parse the command to bytecodes again.  */
2346               loc->cmd_bytecode
2347                 = parse_cmd_to_aexpr (bl->address,
2348                                       loc->owner->extra_string);
2349             }
2350
2351           /* If we have a NULL bytecode expression, it means something
2352              went wrong or we have a null command expression.  */
2353           if (!loc->cmd_bytecode)
2354             {
2355               null_command_or_parse_error = 1;
2356               break;
2357             }
2358         }
2359     }
2360
2361   /* If anything failed, then we're not doing target-side commands,
2362      and so clean up.  */
2363   if (null_command_or_parse_error)
2364     {
2365       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2366         {
2367           loc = (*loc2p);
2368           if (is_breakpoint (loc->owner)
2369               && loc->pspace->num == bl->pspace->num)
2370             {
2371               /* Only go as far as the first NULL bytecode is
2372                  located.  */
2373               if (loc->cmd_bytecode == NULL)
2374                 return;
2375
2376               loc->cmd_bytecode.reset ();
2377             }
2378         }
2379     }
2380
2381   /* No NULL commands or failed bytecode generation.  Build a command list
2382      for this location's address.  */
2383   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2384     {
2385       loc = (*loc2p);
2386       if (loc->owner->extra_string
2387           && is_breakpoint (loc->owner)
2388           && loc->pspace->num == bl->pspace->num
2389           && loc->owner->enable_state == bp_enabled
2390           && loc->enabled)
2391         {
2392           /* Add the command to the vector.  This will be used later
2393              to send the commands to the target.  */
2394           bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2395         }
2396     }
2397
2398   bl->target_info.persist = 0;
2399   /* Maybe flag this location as persistent.  */
2400   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2401     bl->target_info.persist = 1;
2402 }
2403
2404 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2405    of breakpoint according to ADDR except single-step breakpoint.
2406    Get the kind of single-step breakpoint according to the current
2407    registers state.  */
2408
2409 static int
2410 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2411 {
2412   if (bl->owner->type == bp_single_step)
2413     {
2414       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2415       struct regcache *regcache;
2416
2417       regcache = get_thread_regcache (thr);
2418
2419       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2420                                                          regcache, addr);
2421     }
2422   else
2423     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2424 }
2425
2426 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2427    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2428    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2429    Returns 0 for success, 1 if the bp_location type is not supported or
2430    -1 for failure.
2431
2432    NOTE drow/2003-09-09: This routine could be broken down to an
2433    object-style method for each breakpoint or catchpoint type.  */
2434 static int
2435 insert_bp_location (struct bp_location *bl,
2436                     struct ui_file *tmp_error_stream,
2437                     int *disabled_breaks,
2438                     int *hw_breakpoint_error,
2439                     int *hw_bp_error_explained_already)
2440 {
2441   gdb_exception bp_excpt = exception_none;
2442
2443   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2444     return 0;
2445
2446   /* Note we don't initialize bl->target_info, as that wipes out
2447      the breakpoint location's shadow_contents if the breakpoint
2448      is still inserted at that location.  This in turn breaks
2449      target_read_memory which depends on these buffers when
2450      a memory read is requested at the breakpoint location:
2451      Once the target_info has been wiped, we fail to see that
2452      we have a breakpoint inserted at that address and thus
2453      read the breakpoint instead of returning the data saved in
2454      the breakpoint location's shadow contents.  */
2455   bl->target_info.reqstd_address = bl->address;
2456   bl->target_info.placed_address_space = bl->pspace->aspace;
2457   bl->target_info.length = bl->length;
2458
2459   /* When working with target-side conditions, we must pass all the conditions
2460      for the same breakpoint address down to the target since GDB will not
2461      insert those locations.  With a list of breakpoint conditions, the target
2462      can decide when to stop and notify GDB.  */
2463
2464   if (is_breakpoint (bl->owner))
2465     {
2466       build_target_condition_list (bl);
2467       build_target_command_list (bl);
2468       /* Reset the modification marker.  */
2469       bl->needs_update = 0;
2470     }
2471
2472   if (bl->loc_type == bp_loc_software_breakpoint
2473       || bl->loc_type == bp_loc_hardware_breakpoint)
2474     {
2475       if (bl->owner->type != bp_hardware_breakpoint)
2476         {
2477           /* If the explicitly specified breakpoint type
2478              is not hardware breakpoint, check the memory map to see
2479              if the breakpoint address is in read only memory or not.
2480
2481              Two important cases are:
2482              - location type is not hardware breakpoint, memory
2483              is readonly.  We change the type of the location to
2484              hardware breakpoint.
2485              - location type is hardware breakpoint, memory is
2486              read-write.  This means we've previously made the
2487              location hardware one, but then the memory map changed,
2488              so we undo.
2489              
2490              When breakpoints are removed, remove_breakpoints will use
2491              location types we've just set here, the only possible
2492              problem is that memory map has changed during running
2493              program, but it's not going to work anyway with current
2494              gdb.  */
2495           struct mem_region *mr 
2496             = lookup_mem_region (bl->target_info.reqstd_address);
2497           
2498           if (mr)
2499             {
2500               if (automatic_hardware_breakpoints)
2501                 {
2502                   enum bp_loc_type new_type;
2503                   
2504                   if (mr->attrib.mode != MEM_RW)
2505                     new_type = bp_loc_hardware_breakpoint;
2506                   else 
2507                     new_type = bp_loc_software_breakpoint;
2508                   
2509                   if (new_type != bl->loc_type)
2510                     {
2511                       static int said = 0;
2512
2513                       bl->loc_type = new_type;
2514                       if (!said)
2515                         {
2516                           fprintf_filtered (gdb_stdout,
2517                                             _("Note: automatically using "
2518                                               "hardware breakpoints for "
2519                                               "read-only addresses.\n"));
2520                           said = 1;
2521                         }
2522                     }
2523                 }
2524               else if (bl->loc_type == bp_loc_software_breakpoint
2525                        && mr->attrib.mode != MEM_RW)
2526                 {
2527                   fprintf_unfiltered (tmp_error_stream,
2528                                       _("Cannot insert breakpoint %d.\n"
2529                                         "Cannot set software breakpoint "
2530                                         "at read-only address %s\n"),
2531                                       bl->owner->number,
2532                                       paddress (bl->gdbarch, bl->address));
2533                   return 1;
2534                 }
2535             }
2536         }
2537         
2538       /* First check to see if we have to handle an overlay.  */
2539       if (overlay_debugging == ovly_off
2540           || bl->section == NULL
2541           || !(section_is_overlay (bl->section)))
2542         {
2543           /* No overlay handling: just set the breakpoint.  */
2544           TRY
2545             {
2546               int val;
2547
2548               val = bl->owner->ops->insert_location (bl);
2549               if (val)
2550                 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2551             }
2552           CATCH (e, RETURN_MASK_ALL)
2553             {
2554               bp_excpt = e;
2555             }
2556           END_CATCH
2557         }
2558       else
2559         {
2560           /* This breakpoint is in an overlay section.
2561              Shall we set a breakpoint at the LMA?  */
2562           if (!overlay_events_enabled)
2563             {
2564               /* Yes -- overlay event support is not active, 
2565                  so we must try to set a breakpoint at the LMA.
2566                  This will not work for a hardware breakpoint.  */
2567               if (bl->loc_type == bp_loc_hardware_breakpoint)
2568                 warning (_("hardware breakpoint %d not supported in overlay!"),
2569                          bl->owner->number);
2570               else
2571                 {
2572                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2573                                                              bl->section);
2574                   /* Set a software (trap) breakpoint at the LMA.  */
2575                   bl->overlay_target_info = bl->target_info;
2576                   bl->overlay_target_info.reqstd_address = addr;
2577
2578                   /* No overlay handling: just set the breakpoint.  */
2579                   TRY
2580                     {
2581                       int val;
2582
2583                       bl->overlay_target_info.kind
2584                         = breakpoint_kind (bl, &addr);
2585                       bl->overlay_target_info.placed_address = addr;
2586                       val = target_insert_breakpoint (bl->gdbarch,
2587                                                       &bl->overlay_target_info);
2588                       if (val)
2589                         bp_excpt
2590                           = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2591                     }
2592                   CATCH (e, RETURN_MASK_ALL)
2593                     {
2594                       bp_excpt = e;
2595                     }
2596                   END_CATCH
2597
2598                   if (bp_excpt.reason != 0)
2599                     fprintf_unfiltered (tmp_error_stream,
2600                                         "Overlay breakpoint %d "
2601                                         "failed: in ROM?\n",
2602                                         bl->owner->number);
2603                 }
2604             }
2605           /* Shall we set a breakpoint at the VMA? */
2606           if (section_is_mapped (bl->section))
2607             {
2608               /* Yes.  This overlay section is mapped into memory.  */
2609               TRY
2610                 {
2611                   int val;
2612
2613                   val = bl->owner->ops->insert_location (bl);
2614                   if (val)
2615                     bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2616                 }
2617               CATCH (e, RETURN_MASK_ALL)
2618                 {
2619                   bp_excpt = e;
2620                 }
2621               END_CATCH
2622             }
2623           else
2624             {
2625               /* No.  This breakpoint will not be inserted.  
2626                  No error, but do not mark the bp as 'inserted'.  */
2627               return 0;
2628             }
2629         }
2630
2631       if (bp_excpt.reason != 0)
2632         {
2633           /* Can't set the breakpoint.  */
2634
2635           /* In some cases, we might not be able to insert a
2636              breakpoint in a shared library that has already been
2637              removed, but we have not yet processed the shlib unload
2638              event.  Unfortunately, some targets that implement
2639              breakpoint insertion themselves can't tell why the
2640              breakpoint insertion failed (e.g., the remote target
2641              doesn't define error codes), so we must treat generic
2642              errors as memory errors.  */
2643           if (bp_excpt.reason == RETURN_ERROR
2644               && (bp_excpt.error == GENERIC_ERROR
2645                   || bp_excpt.error == MEMORY_ERROR)
2646               && bl->loc_type == bp_loc_software_breakpoint
2647               && (solib_name_from_address (bl->pspace, bl->address)
2648                   || shared_objfile_contains_address_p (bl->pspace,
2649                                                         bl->address)))
2650             {
2651               /* See also: disable_breakpoints_in_shlibs.  */
2652               bl->shlib_disabled = 1;
2653               gdb::observers::breakpoint_modified.notify (bl->owner);
2654               if (!*disabled_breaks)
2655                 {
2656                   fprintf_unfiltered (tmp_error_stream, 
2657                                       "Cannot insert breakpoint %d.\n", 
2658                                       bl->owner->number);
2659                   fprintf_unfiltered (tmp_error_stream, 
2660                                       "Temporarily disabling shared "
2661                                       "library breakpoints:\n");
2662                 }
2663               *disabled_breaks = 1;
2664               fprintf_unfiltered (tmp_error_stream,
2665                                   "breakpoint #%d\n", bl->owner->number);
2666               return 0;
2667             }
2668           else
2669             {
2670               if (bl->loc_type == bp_loc_hardware_breakpoint)
2671                 {
2672                   *hw_breakpoint_error = 1;
2673                   *hw_bp_error_explained_already = bp_excpt.message != NULL;
2674                   fprintf_unfiltered (tmp_error_stream,
2675                                       "Cannot insert hardware breakpoint %d%s",
2676                                       bl->owner->number,
2677                                       bp_excpt.message ? ":" : ".\n");
2678                   if (bp_excpt.message != NULL)
2679                     fprintf_unfiltered (tmp_error_stream, "%s.\n",
2680                                         bp_excpt.message);
2681                 }
2682               else
2683                 {
2684                   if (bp_excpt.message == NULL)
2685                     {
2686                       std::string message
2687                         = memory_error_message (TARGET_XFER_E_IO,
2688                                                 bl->gdbarch, bl->address);
2689
2690                       fprintf_unfiltered (tmp_error_stream,
2691                                           "Cannot insert breakpoint %d.\n"
2692                                           "%s\n",
2693                                           bl->owner->number, message.c_str ());
2694                     }
2695                   else
2696                     {
2697                       fprintf_unfiltered (tmp_error_stream,
2698                                           "Cannot insert breakpoint %d: %s\n",
2699                                           bl->owner->number,
2700                                           bp_excpt.message);
2701                     }
2702                 }
2703               return 1;
2704
2705             }
2706         }
2707       else
2708         bl->inserted = 1;
2709
2710       return 0;
2711     }
2712
2713   else if (bl->loc_type == bp_loc_hardware_watchpoint
2714            /* NOTE drow/2003-09-08: This state only exists for removing
2715               watchpoints.  It's not clear that it's necessary...  */
2716            && bl->owner->disposition != disp_del_at_next_stop)
2717     {
2718       int val;
2719
2720       gdb_assert (bl->owner->ops != NULL
2721                   && bl->owner->ops->insert_location != NULL);
2722
2723       val = bl->owner->ops->insert_location (bl);
2724
2725       /* If trying to set a read-watchpoint, and it turns out it's not
2726          supported, try emulating one with an access watchpoint.  */
2727       if (val == 1 && bl->watchpoint_type == hw_read)
2728         {
2729           struct bp_location *loc, **loc_temp;
2730
2731           /* But don't try to insert it, if there's already another
2732              hw_access location that would be considered a duplicate
2733              of this one.  */
2734           ALL_BP_LOCATIONS (loc, loc_temp)
2735             if (loc != bl
2736                 && loc->watchpoint_type == hw_access
2737                 && watchpoint_locations_match (bl, loc))
2738               {
2739                 bl->duplicate = 1;
2740                 bl->inserted = 1;
2741                 bl->target_info = loc->target_info;
2742                 bl->watchpoint_type = hw_access;
2743                 val = 0;
2744                 break;
2745               }
2746
2747           if (val == 1)
2748             {
2749               bl->watchpoint_type = hw_access;
2750               val = bl->owner->ops->insert_location (bl);
2751
2752               if (val)
2753                 /* Back to the original value.  */
2754                 bl->watchpoint_type = hw_read;
2755             }
2756         }
2757
2758       bl->inserted = (val == 0);
2759     }
2760
2761   else if (bl->owner->type == bp_catchpoint)
2762     {
2763       int val;
2764
2765       gdb_assert (bl->owner->ops != NULL
2766                   && bl->owner->ops->insert_location != NULL);
2767
2768       val = bl->owner->ops->insert_location (bl);
2769       if (val)
2770         {
2771           bl->owner->enable_state = bp_disabled;
2772
2773           if (val == 1)
2774             warning (_("\
2775 Error inserting catchpoint %d: Your system does not support this type\n\
2776 of catchpoint."), bl->owner->number);
2777           else
2778             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2779         }
2780
2781       bl->inserted = (val == 0);
2782
2783       /* We've already printed an error message if there was a problem
2784          inserting this catchpoint, and we've disabled the catchpoint,
2785          so just return success.  */
2786       return 0;
2787     }
2788
2789   return 0;
2790 }
2791
2792 /* This function is called when program space PSPACE is about to be
2793    deleted.  It takes care of updating breakpoints to not reference
2794    PSPACE anymore.  */
2795
2796 void
2797 breakpoint_program_space_exit (struct program_space *pspace)
2798 {
2799   struct breakpoint *b, *b_temp;
2800   struct bp_location *loc, **loc_temp;
2801
2802   /* Remove any breakpoint that was set through this program space.  */
2803   ALL_BREAKPOINTS_SAFE (b, b_temp)
2804     {
2805       if (b->pspace == pspace)
2806         delete_breakpoint (b);
2807     }
2808
2809   /* Breakpoints set through other program spaces could have locations
2810      bound to PSPACE as well.  Remove those.  */
2811   ALL_BP_LOCATIONS (loc, loc_temp)
2812     {
2813       struct bp_location *tmp;
2814
2815       if (loc->pspace == pspace)
2816         {
2817           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2818           if (loc->owner->loc == loc)
2819             loc->owner->loc = loc->next;
2820           else
2821             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2822               if (tmp->next == loc)
2823                 {
2824                   tmp->next = loc->next;
2825                   break;
2826                 }
2827         }
2828     }
2829
2830   /* Now update the global location list to permanently delete the
2831      removed locations above.  */
2832   update_global_location_list (UGLL_DONT_INSERT);
2833 }
2834
2835 /* Make sure all breakpoints are inserted in inferior.
2836    Throws exception on any error.
2837    A breakpoint that is already inserted won't be inserted
2838    again, so calling this function twice is safe.  */
2839 void
2840 insert_breakpoints (void)
2841 {
2842   struct breakpoint *bpt;
2843
2844   ALL_BREAKPOINTS (bpt)
2845     if (is_hardware_watchpoint (bpt))
2846       {
2847         struct watchpoint *w = (struct watchpoint *) bpt;
2848
2849         update_watchpoint (w, 0 /* don't reparse.  */);
2850       }
2851
2852   /* Updating watchpoints creates new locations, so update the global
2853      location list.  Explicitly tell ugll to insert locations and
2854      ignore breakpoints_always_inserted_mode.  */
2855   update_global_location_list (UGLL_INSERT);
2856 }
2857
2858 /* Invoke CALLBACK for each of bp_location.  */
2859
2860 void
2861 iterate_over_bp_locations (walk_bp_location_callback callback)
2862 {
2863   struct bp_location *loc, **loc_tmp;
2864
2865   ALL_BP_LOCATIONS (loc, loc_tmp)
2866     {
2867       callback (loc, NULL);
2868     }
2869 }
2870
2871 /* This is used when we need to synch breakpoint conditions between GDB and the
2872    target.  It is the case with deleting and disabling of breakpoints when using
2873    always-inserted mode.  */
2874
2875 static void
2876 update_inserted_breakpoint_locations (void)
2877 {
2878   struct bp_location *bl, **blp_tmp;
2879   int error_flag = 0;
2880   int val = 0;
2881   int disabled_breaks = 0;
2882   int hw_breakpoint_error = 0;
2883   int hw_bp_details_reported = 0;
2884
2885   string_file tmp_error_stream;
2886
2887   /* Explicitly mark the warning -- this will only be printed if
2888      there was an error.  */
2889   tmp_error_stream.puts ("Warning:\n");
2890
2891   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2892
2893   ALL_BP_LOCATIONS (bl, blp_tmp)
2894     {
2895       /* We only want to update software breakpoints and hardware
2896          breakpoints.  */
2897       if (!is_breakpoint (bl->owner))
2898         continue;
2899
2900       /* We only want to update locations that are already inserted
2901          and need updating.  This is to avoid unwanted insertion during
2902          deletion of breakpoints.  */
2903       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2904         continue;
2905
2906       switch_to_program_space_and_thread (bl->pspace);
2907
2908       /* For targets that support global breakpoints, there's no need
2909          to select an inferior to insert breakpoint to.  In fact, even
2910          if we aren't attached to any process yet, we should still
2911          insert breakpoints.  */
2912       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2913           && inferior_ptid == null_ptid)
2914         continue;
2915
2916       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2917                                     &hw_breakpoint_error, &hw_bp_details_reported);
2918       if (val)
2919         error_flag = val;
2920     }
2921
2922   if (error_flag)
2923     {
2924       target_terminal::ours_for_output ();
2925       error_stream (tmp_error_stream);
2926     }
2927 }
2928
2929 /* Used when starting or continuing the program.  */
2930
2931 static void
2932 insert_breakpoint_locations (void)
2933 {
2934   struct breakpoint *bpt;
2935   struct bp_location *bl, **blp_tmp;
2936   int error_flag = 0;
2937   int val = 0;
2938   int disabled_breaks = 0;
2939   int hw_breakpoint_error = 0;
2940   int hw_bp_error_explained_already = 0;
2941
2942   string_file tmp_error_stream;
2943
2944   /* Explicitly mark the warning -- this will only be printed if
2945      there was an error.  */
2946   tmp_error_stream.puts ("Warning:\n");
2947
2948   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2949
2950   ALL_BP_LOCATIONS (bl, blp_tmp)
2951     {
2952       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2953         continue;
2954
2955       /* There is no point inserting thread-specific breakpoints if
2956          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2957          has BL->OWNER always non-NULL.  */
2958       if (bl->owner->thread != -1
2959           && !valid_global_thread_id (bl->owner->thread))
2960         continue;
2961
2962       switch_to_program_space_and_thread (bl->pspace);
2963
2964       /* For targets that support global breakpoints, there's no need
2965          to select an inferior to insert breakpoint to.  In fact, even
2966          if we aren't attached to any process yet, we should still
2967          insert breakpoints.  */
2968       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2969           && inferior_ptid == null_ptid)
2970         continue;
2971
2972       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2973                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
2974       if (val)
2975         error_flag = val;
2976     }
2977
2978   /* If we failed to insert all locations of a watchpoint, remove
2979      them, as half-inserted watchpoint is of limited use.  */
2980   ALL_BREAKPOINTS (bpt)  
2981     {
2982       int some_failed = 0;
2983       struct bp_location *loc;
2984
2985       if (!is_hardware_watchpoint (bpt))
2986         continue;
2987
2988       if (!breakpoint_enabled (bpt))
2989         continue;
2990
2991       if (bpt->disposition == disp_del_at_next_stop)
2992         continue;
2993       
2994       for (loc = bpt->loc; loc; loc = loc->next)
2995         if (!loc->inserted && should_be_inserted (loc))
2996           {
2997             some_failed = 1;
2998             break;
2999           }
3000       if (some_failed)
3001         {
3002           for (loc = bpt->loc; loc; loc = loc->next)
3003             if (loc->inserted)
3004               remove_breakpoint (loc);
3005
3006           hw_breakpoint_error = 1;
3007           tmp_error_stream.printf ("Could not insert "
3008                                    "hardware watchpoint %d.\n",
3009                                    bpt->number);
3010           error_flag = -1;
3011         }
3012     }
3013
3014   if (error_flag)
3015     {
3016       /* If a hardware breakpoint or watchpoint was inserted, add a
3017          message about possibly exhausted resources.  */
3018       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3019         {
3020           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3021 You may have requested too many hardware breakpoints/watchpoints.\n");
3022         }
3023       target_terminal::ours_for_output ();
3024       error_stream (tmp_error_stream);
3025     }
3026 }
3027
3028 /* Used when the program stops.
3029    Returns zero if successful, or non-zero if there was a problem
3030    removing a breakpoint location.  */
3031
3032 int
3033 remove_breakpoints (void)
3034 {
3035   struct bp_location *bl, **blp_tmp;
3036   int val = 0;
3037
3038   ALL_BP_LOCATIONS (bl, blp_tmp)
3039   {
3040     if (bl->inserted && !is_tracepoint (bl->owner))
3041       val |= remove_breakpoint (bl);
3042   }
3043   return val;
3044 }
3045
3046 /* When a thread exits, remove breakpoints that are related to
3047    that thread.  */
3048
3049 static void
3050 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3051 {
3052   struct breakpoint *b, *b_tmp;
3053
3054   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3055     {
3056       if (b->thread == tp->global_num && user_breakpoint_p (b))
3057         {
3058           b->disposition = disp_del_at_next_stop;
3059
3060           printf_filtered (_("\
3061 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3062                            b->number, print_thread_id (tp));
3063
3064           /* Hide it from the user.  */
3065           b->number = 0;
3066        }
3067     }
3068 }
3069
3070 /* Remove breakpoints of inferior INF.  */
3071
3072 int
3073 remove_breakpoints_inf (inferior *inf)
3074 {
3075   struct bp_location *bl, **blp_tmp;
3076   int val;
3077
3078   ALL_BP_LOCATIONS (bl, blp_tmp)
3079   {
3080     if (bl->pspace != inf->pspace)
3081       continue;
3082
3083     if (bl->inserted && !bl->target_info.persist)
3084       {
3085         val = remove_breakpoint (bl);
3086         if (val != 0)
3087           return val;
3088       }
3089   }
3090   return 0;
3091 }
3092
3093 static int internal_breakpoint_number = -1;
3094
3095 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3096    If INTERNAL is non-zero, the breakpoint number will be populated
3097    from internal_breakpoint_number and that variable decremented.
3098    Otherwise the breakpoint number will be populated from
3099    breakpoint_count and that value incremented.  Internal breakpoints
3100    do not set the internal var bpnum.  */
3101 static void
3102 set_breakpoint_number (int internal, struct breakpoint *b)
3103 {
3104   if (internal)
3105     b->number = internal_breakpoint_number--;
3106   else
3107     {
3108       set_breakpoint_count (breakpoint_count + 1);
3109       b->number = breakpoint_count;
3110     }
3111 }
3112
3113 static struct breakpoint *
3114 create_internal_breakpoint (struct gdbarch *gdbarch,
3115                             CORE_ADDR address, enum bptype type,
3116                             const struct breakpoint_ops *ops)
3117 {
3118   symtab_and_line sal;
3119   sal.pc = address;
3120   sal.section = find_pc_overlay (sal.pc);
3121   sal.pspace = current_program_space;
3122
3123   breakpoint *b = set_raw_breakpoint (gdbarch, sal, type, ops);
3124   b->number = internal_breakpoint_number--;
3125   b->disposition = disp_donttouch;
3126
3127   return b;
3128 }
3129
3130 static const char *const longjmp_names[] =
3131   {
3132     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3133   };
3134 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3135
3136 /* Per-objfile data private to breakpoint.c.  */
3137 struct breakpoint_objfile_data
3138 {
3139   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3140   struct bound_minimal_symbol overlay_msym {};
3141
3142   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3143   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES] {};
3144
3145   /* True if we have looked for longjmp probes.  */
3146   int longjmp_searched = 0;
3147
3148   /* SystemTap probe points for longjmp (if any).  These are non-owning
3149      references.  */
3150   std::vector<probe *> longjmp_probes;
3151
3152   /* Minimal symbol for "std::terminate()" (if any).  */
3153   struct bound_minimal_symbol terminate_msym {};
3154
3155   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3156   struct bound_minimal_symbol exception_msym {};
3157
3158   /* True if we have looked for exception probes.  */
3159   int exception_searched = 0;
3160
3161   /* SystemTap probe points for unwinding (if any).  These are non-owning
3162      references.  */
3163   std::vector<probe *> exception_probes;
3164 };
3165
3166 static const struct objfile_data *breakpoint_objfile_key;
3167
3168 /* Minimal symbol not found sentinel.  */
3169 static struct minimal_symbol msym_not_found;
3170
3171 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3172
3173 static int
3174 msym_not_found_p (const struct minimal_symbol *msym)
3175 {
3176   return msym == &msym_not_found;
3177 }
3178
3179 /* Return per-objfile data needed by breakpoint.c.
3180    Allocate the data if necessary.  */
3181
3182 static struct breakpoint_objfile_data *
3183 get_breakpoint_objfile_data (struct objfile *objfile)
3184 {
3185   struct breakpoint_objfile_data *bp_objfile_data;
3186
3187   bp_objfile_data = ((struct breakpoint_objfile_data *)
3188                      objfile_data (objfile, breakpoint_objfile_key));
3189   if (bp_objfile_data == NULL)
3190     {
3191       bp_objfile_data = new breakpoint_objfile_data ();
3192       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3193     }
3194   return bp_objfile_data;
3195 }
3196
3197 static void
3198 free_breakpoint_objfile_data (struct objfile *obj, void *data)
3199 {
3200   struct breakpoint_objfile_data *bp_objfile_data
3201     = (struct breakpoint_objfile_data *) data;
3202
3203   delete bp_objfile_data;
3204 }
3205
3206 static void
3207 create_overlay_event_breakpoint (void)
3208 {
3209   struct objfile *objfile;
3210   const char *const func_name = "_ovly_debug_event";
3211
3212   ALL_OBJFILES (objfile)
3213     {
3214       struct breakpoint *b;
3215       struct breakpoint_objfile_data *bp_objfile_data;
3216       CORE_ADDR addr;
3217       struct explicit_location explicit_loc;
3218
3219       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3220
3221       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3222         continue;
3223
3224       if (bp_objfile_data->overlay_msym.minsym == NULL)
3225         {
3226           struct bound_minimal_symbol m;
3227
3228           m = lookup_minimal_symbol_text (func_name, objfile);
3229           if (m.minsym == NULL)
3230             {
3231               /* Avoid future lookups in this objfile.  */
3232               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3233               continue;
3234             }
3235           bp_objfile_data->overlay_msym = m;
3236         }
3237
3238       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3239       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3240                                       bp_overlay_event,
3241                                       &internal_breakpoint_ops);
3242       initialize_explicit_location (&explicit_loc);
3243       explicit_loc.function_name = ASTRDUP (func_name);
3244       b->location = new_explicit_location (&explicit_loc);
3245
3246       if (overlay_debugging == ovly_auto)
3247         {
3248           b->enable_state = bp_enabled;
3249           overlay_events_enabled = 1;
3250         }
3251       else
3252        {
3253          b->enable_state = bp_disabled;
3254          overlay_events_enabled = 0;
3255        }
3256     }
3257 }
3258
3259 static void
3260 create_longjmp_master_breakpoint (void)
3261 {
3262   struct program_space *pspace;
3263
3264   scoped_restore_current_program_space restore_pspace;
3265
3266   ALL_PSPACES (pspace)
3267   {
3268     struct objfile *objfile;
3269
3270     set_current_program_space (pspace);
3271
3272     ALL_OBJFILES (objfile)
3273     {
3274       int i;
3275       struct gdbarch *gdbarch;
3276       struct breakpoint_objfile_data *bp_objfile_data;
3277
3278       gdbarch = get_objfile_arch (objfile);
3279
3280       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3281
3282       if (!bp_objfile_data->longjmp_searched)
3283         {
3284           std::vector<probe *> ret
3285             = find_probes_in_objfile (objfile, "libc", "longjmp");
3286
3287           if (!ret.empty ())
3288             {
3289               /* We are only interested in checking one element.  */
3290               probe *p = ret[0];
3291
3292               if (!p->can_evaluate_arguments ())
3293                 {
3294                   /* We cannot use the probe interface here, because it does
3295                      not know how to evaluate arguments.  */
3296                   ret.clear ();
3297                 }
3298             }
3299           bp_objfile_data->longjmp_probes = ret;
3300           bp_objfile_data->longjmp_searched = 1;
3301         }
3302
3303       if (!bp_objfile_data->longjmp_probes.empty ())
3304         {
3305           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3306
3307           for (probe *p : bp_objfile_data->longjmp_probes)
3308             {
3309               struct breakpoint *b;
3310
3311               b = create_internal_breakpoint (gdbarch,
3312                                               p->get_relocated_address (objfile),
3313                                               bp_longjmp_master,
3314                                               &internal_breakpoint_ops);
3315               b->location = new_probe_location ("-probe-stap libc:longjmp");
3316               b->enable_state = bp_disabled;
3317             }
3318
3319           continue;
3320         }
3321
3322       if (!gdbarch_get_longjmp_target_p (gdbarch))
3323         continue;
3324
3325       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3326         {
3327           struct breakpoint *b;
3328           const char *func_name;
3329           CORE_ADDR addr;
3330           struct explicit_location explicit_loc;
3331
3332           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3333             continue;
3334
3335           func_name = longjmp_names[i];
3336           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3337             {
3338               struct bound_minimal_symbol m;
3339
3340               m = lookup_minimal_symbol_text (func_name, objfile);
3341               if (m.minsym == NULL)
3342                 {
3343                   /* Prevent future lookups in this objfile.  */
3344                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3345                   continue;
3346                 }
3347               bp_objfile_data->longjmp_msym[i] = m;
3348             }
3349
3350           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3351           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3352                                           &internal_breakpoint_ops);
3353           initialize_explicit_location (&explicit_loc);
3354           explicit_loc.function_name = ASTRDUP (func_name);
3355           b->location = new_explicit_location (&explicit_loc);
3356           b->enable_state = bp_disabled;
3357         }
3358     }
3359   }
3360 }
3361
3362 /* Create a master std::terminate breakpoint.  */
3363 static void
3364 create_std_terminate_master_breakpoint (void)
3365 {
3366   struct program_space *pspace;
3367   const char *const func_name = "std::terminate()";
3368
3369   scoped_restore_current_program_space restore_pspace;
3370
3371   ALL_PSPACES (pspace)
3372   {
3373     struct objfile *objfile;
3374     CORE_ADDR addr;
3375
3376     set_current_program_space (pspace);
3377
3378     ALL_OBJFILES (objfile)
3379     {
3380       struct breakpoint *b;
3381       struct breakpoint_objfile_data *bp_objfile_data;
3382       struct explicit_location explicit_loc;
3383
3384       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3385
3386       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3387         continue;
3388
3389       if (bp_objfile_data->terminate_msym.minsym == NULL)
3390         {
3391           struct bound_minimal_symbol m;
3392
3393           m = lookup_minimal_symbol (func_name, NULL, objfile);
3394           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3395                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3396             {
3397               /* Prevent future lookups in this objfile.  */
3398               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3399               continue;
3400             }
3401           bp_objfile_data->terminate_msym = m;
3402         }
3403
3404       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3405       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3406                                       bp_std_terminate_master,
3407                                       &internal_breakpoint_ops);
3408       initialize_explicit_location (&explicit_loc);
3409       explicit_loc.function_name = ASTRDUP (func_name);
3410       b->location = new_explicit_location (&explicit_loc);
3411       b->enable_state = bp_disabled;
3412     }
3413   }
3414 }
3415
3416 /* Install a master breakpoint on the unwinder's debug hook.  */
3417
3418 static void
3419 create_exception_master_breakpoint (void)
3420 {
3421   struct objfile *objfile;
3422   const char *const func_name = "_Unwind_DebugHook";
3423
3424   ALL_OBJFILES (objfile)
3425     {
3426       struct breakpoint *b;
3427       struct gdbarch *gdbarch;
3428       struct breakpoint_objfile_data *bp_objfile_data;
3429       CORE_ADDR addr;
3430       struct explicit_location explicit_loc;
3431
3432       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3433
3434       /* We prefer the SystemTap probe point if it exists.  */
3435       if (!bp_objfile_data->exception_searched)
3436         {
3437           std::vector<probe *> ret
3438             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3439
3440           if (!ret.empty ())
3441             {
3442               /* We are only interested in checking one element.  */
3443               probe *p = ret[0];
3444
3445               if (!p->can_evaluate_arguments ())
3446                 {
3447                   /* We cannot use the probe interface here, because it does
3448                      not know how to evaluate arguments.  */
3449                   ret.clear ();
3450                 }
3451             }
3452           bp_objfile_data->exception_probes = ret;
3453           bp_objfile_data->exception_searched = 1;
3454         }
3455
3456       if (!bp_objfile_data->exception_probes.empty ())
3457         {
3458           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3459
3460           for (probe *p : bp_objfile_data->exception_probes)
3461             {
3462               struct breakpoint *b;
3463
3464               b = create_internal_breakpoint (gdbarch,
3465                                               p->get_relocated_address (objfile),
3466                                               bp_exception_master,
3467                                               &internal_breakpoint_ops);
3468               b->location = new_probe_location ("-probe-stap libgcc:unwind");
3469               b->enable_state = bp_disabled;
3470             }
3471
3472           continue;
3473         }
3474
3475       /* Otherwise, try the hook function.  */
3476
3477       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3478         continue;
3479
3480       gdbarch = get_objfile_arch (objfile);
3481
3482       if (bp_objfile_data->exception_msym.minsym == NULL)
3483         {
3484           struct bound_minimal_symbol debug_hook;
3485
3486           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3487           if (debug_hook.minsym == NULL)
3488             {
3489               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3490               continue;
3491             }
3492
3493           bp_objfile_data->exception_msym = debug_hook;
3494         }
3495
3496       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3497       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3498                                                  current_top_target ());
3499       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3500                                       &internal_breakpoint_ops);
3501       initialize_explicit_location (&explicit_loc);
3502       explicit_loc.function_name = ASTRDUP (func_name);
3503       b->location = new_explicit_location (&explicit_loc);
3504       b->enable_state = bp_disabled;
3505     }
3506 }
3507
3508 /* Does B have a location spec?  */
3509
3510 static int
3511 breakpoint_event_location_empty_p (const struct breakpoint *b)
3512 {
3513   return b->location != NULL && event_location_empty_p (b->location.get ());
3514 }
3515
3516 void
3517 update_breakpoints_after_exec (void)
3518 {
3519   struct breakpoint *b, *b_tmp;
3520   struct bp_location *bploc, **bplocp_tmp;
3521
3522   /* We're about to delete breakpoints from GDB's lists.  If the
3523      INSERTED flag is true, GDB will try to lift the breakpoints by
3524      writing the breakpoints' "shadow contents" back into memory.  The
3525      "shadow contents" are NOT valid after an exec, so GDB should not
3526      do that.  Instead, the target is responsible from marking
3527      breakpoints out as soon as it detects an exec.  We don't do that
3528      here instead, because there may be other attempts to delete
3529      breakpoints after detecting an exec and before reaching here.  */
3530   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3531     if (bploc->pspace == current_program_space)
3532       gdb_assert (!bploc->inserted);
3533
3534   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3535   {
3536     if (b->pspace != current_program_space)
3537       continue;
3538
3539     /* Solib breakpoints must be explicitly reset after an exec().  */
3540     if (b->type == bp_shlib_event)
3541       {
3542         delete_breakpoint (b);
3543         continue;
3544       }
3545
3546     /* JIT breakpoints must be explicitly reset after an exec().  */
3547     if (b->type == bp_jit_event)
3548       {
3549         delete_breakpoint (b);
3550         continue;
3551       }
3552
3553     /* Thread event breakpoints must be set anew after an exec(),
3554        as must overlay event and longjmp master breakpoints.  */
3555     if (b->type == bp_thread_event || b->type == bp_overlay_event
3556         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3557         || b->type == bp_exception_master)
3558       {
3559         delete_breakpoint (b);
3560         continue;
3561       }
3562
3563     /* Step-resume breakpoints are meaningless after an exec().  */
3564     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3565       {
3566         delete_breakpoint (b);
3567         continue;
3568       }
3569
3570     /* Just like single-step breakpoints.  */
3571     if (b->type == bp_single_step)
3572       {
3573         delete_breakpoint (b);
3574         continue;
3575       }
3576
3577     /* Longjmp and longjmp-resume breakpoints are also meaningless
3578        after an exec.  */
3579     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3580         || b->type == bp_longjmp_call_dummy
3581         || b->type == bp_exception || b->type == bp_exception_resume)
3582       {
3583         delete_breakpoint (b);
3584         continue;
3585       }
3586
3587     if (b->type == bp_catchpoint)
3588       {
3589         /* For now, none of the bp_catchpoint breakpoints need to
3590            do anything at this point.  In the future, if some of
3591            the catchpoints need to something, we will need to add
3592            a new method, and call this method from here.  */
3593         continue;
3594       }
3595
3596     /* bp_finish is a special case.  The only way we ought to be able
3597        to see one of these when an exec() has happened, is if the user
3598        caught a vfork, and then said "finish".  Ordinarily a finish just
3599        carries them to the call-site of the current callee, by setting
3600        a temporary bp there and resuming.  But in this case, the finish
3601        will carry them entirely through the vfork & exec.
3602
3603        We don't want to allow a bp_finish to remain inserted now.  But
3604        we can't safely delete it, 'cause finish_command has a handle to
3605        the bp on a bpstat, and will later want to delete it.  There's a
3606        chance (and I've seen it happen) that if we delete the bp_finish
3607        here, that its storage will get reused by the time finish_command
3608        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3609        We really must allow finish_command to delete a bp_finish.
3610
3611        In the absence of a general solution for the "how do we know
3612        it's safe to delete something others may have handles to?"
3613        problem, what we'll do here is just uninsert the bp_finish, and
3614        let finish_command delete it.
3615
3616        (We know the bp_finish is "doomed" in the sense that it's
3617        momentary, and will be deleted as soon as finish_command sees
3618        the inferior stopped.  So it doesn't matter that the bp's
3619        address is probably bogus in the new a.out, unlike e.g., the
3620        solib breakpoints.)  */
3621
3622     if (b->type == bp_finish)
3623       {
3624         continue;
3625       }
3626
3627     /* Without a symbolic address, we have little hope of the
3628        pre-exec() address meaning the same thing in the post-exec()
3629        a.out.  */
3630     if (breakpoint_event_location_empty_p (b))
3631       {
3632         delete_breakpoint (b);
3633         continue;
3634       }
3635   }
3636 }
3637
3638 int
3639 detach_breakpoints (ptid_t ptid)
3640 {
3641   struct bp_location *bl, **blp_tmp;
3642   int val = 0;
3643   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3644   struct inferior *inf = current_inferior ();
3645
3646   if (ptid.pid () == inferior_ptid.pid ())
3647     error (_("Cannot detach breakpoints of inferior_ptid"));
3648
3649   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3650   inferior_ptid = ptid;
3651   ALL_BP_LOCATIONS (bl, blp_tmp)
3652   {
3653     if (bl->pspace != inf->pspace)
3654       continue;
3655
3656     /* This function must physically remove breakpoints locations
3657        from the specified ptid, without modifying the breakpoint
3658        package's state.  Locations of type bp_loc_other are only
3659        maintained at GDB side.  So, there is no need to remove
3660        these bp_loc_other locations.  Moreover, removing these
3661        would modify the breakpoint package's state.  */
3662     if (bl->loc_type == bp_loc_other)
3663       continue;
3664
3665     if (bl->inserted)
3666       val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3667   }
3668
3669   return val;
3670 }
3671
3672 /* Remove the breakpoint location BL from the current address space.
3673    Note that this is used to detach breakpoints from a child fork.
3674    When we get here, the child isn't in the inferior list, and neither
3675    do we have objects to represent its address space --- we should
3676    *not* look at bl->pspace->aspace here.  */
3677
3678 static int
3679 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3680 {
3681   int val;
3682
3683   /* BL is never in moribund_locations by our callers.  */
3684   gdb_assert (bl->owner != NULL);
3685
3686   /* The type of none suggests that owner is actually deleted.
3687      This should not ever happen.  */
3688   gdb_assert (bl->owner->type != bp_none);
3689
3690   if (bl->loc_type == bp_loc_software_breakpoint
3691       || bl->loc_type == bp_loc_hardware_breakpoint)
3692     {
3693       /* "Normal" instruction breakpoint: either the standard
3694          trap-instruction bp (bp_breakpoint), or a
3695          bp_hardware_breakpoint.  */
3696
3697       /* First check to see if we have to handle an overlay.  */
3698       if (overlay_debugging == ovly_off
3699           || bl->section == NULL
3700           || !(section_is_overlay (bl->section)))
3701         {
3702           /* No overlay handling: just remove the breakpoint.  */
3703
3704           /* If we're trying to uninsert a memory breakpoint that we
3705              know is set in a dynamic object that is marked
3706              shlib_disabled, then either the dynamic object was
3707              removed with "remove-symbol-file" or with
3708              "nosharedlibrary".  In the former case, we don't know
3709              whether another dynamic object might have loaded over the
3710              breakpoint's address -- the user might well let us know
3711              about it next with add-symbol-file (the whole point of
3712              add-symbol-file is letting the user manually maintain a
3713              list of dynamically loaded objects).  If we have the
3714              breakpoint's shadow memory, that is, this is a software
3715              breakpoint managed by GDB, check whether the breakpoint
3716              is still inserted in memory, to avoid overwriting wrong
3717              code with stale saved shadow contents.  Note that HW
3718              breakpoints don't have shadow memory, as they're
3719              implemented using a mechanism that is not dependent on
3720              being able to modify the target's memory, and as such
3721              they should always be removed.  */
3722           if (bl->shlib_disabled
3723               && bl->target_info.shadow_len != 0
3724               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3725             val = 0;
3726           else
3727             val = bl->owner->ops->remove_location (bl, reason);
3728         }
3729       else
3730         {
3731           /* This breakpoint is in an overlay section.
3732              Did we set a breakpoint at the LMA?  */
3733           if (!overlay_events_enabled)
3734               {
3735                 /* Yes -- overlay event support is not active, so we
3736                    should have set a breakpoint at the LMA.  Remove it.  
3737                 */
3738                 /* Ignore any failures: if the LMA is in ROM, we will
3739                    have already warned when we failed to insert it.  */
3740                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3741                   target_remove_hw_breakpoint (bl->gdbarch,
3742                                                &bl->overlay_target_info);
3743                 else
3744                   target_remove_breakpoint (bl->gdbarch,
3745                                             &bl->overlay_target_info,
3746                                             reason);
3747               }
3748           /* Did we set a breakpoint at the VMA? 
3749              If so, we will have marked the breakpoint 'inserted'.  */
3750           if (bl->inserted)
3751             {
3752               /* Yes -- remove it.  Previously we did not bother to
3753                  remove the breakpoint if the section had been
3754                  unmapped, but let's not rely on that being safe.  We
3755                  don't know what the overlay manager might do.  */
3756
3757               /* However, we should remove *software* breakpoints only
3758                  if the section is still mapped, or else we overwrite
3759                  wrong code with the saved shadow contents.  */
3760               if (bl->loc_type == bp_loc_hardware_breakpoint
3761                   || section_is_mapped (bl->section))
3762                 val = bl->owner->ops->remove_location (bl, reason);
3763               else
3764                 val = 0;
3765             }
3766           else
3767             {
3768               /* No -- not inserted, so no need to remove.  No error.  */
3769               val = 0;
3770             }
3771         }
3772
3773       /* In some cases, we might not be able to remove a breakpoint in
3774          a shared library that has already been removed, but we have
3775          not yet processed the shlib unload event.  Similarly for an
3776          unloaded add-symbol-file object - the user might not yet have
3777          had the chance to remove-symbol-file it.  shlib_disabled will
3778          be set if the library/object has already been removed, but
3779          the breakpoint hasn't been uninserted yet, e.g., after
3780          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3781          always-inserted mode.  */
3782       if (val
3783           && (bl->loc_type == bp_loc_software_breakpoint
3784               && (bl->shlib_disabled
3785                   || solib_name_from_address (bl->pspace, bl->address)
3786                   || shared_objfile_contains_address_p (bl->pspace,
3787                                                         bl->address))))
3788         val = 0;
3789
3790       if (val)
3791         return val;
3792       bl->inserted = (reason == DETACH_BREAKPOINT);
3793     }
3794   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3795     {
3796       gdb_assert (bl->owner->ops != NULL
3797                   && bl->owner->ops->remove_location != NULL);
3798
3799       bl->inserted = (reason == DETACH_BREAKPOINT);
3800       bl->owner->ops->remove_location (bl, reason);
3801
3802       /* Failure to remove any of the hardware watchpoints comes here.  */
3803       if (reason == REMOVE_BREAKPOINT && bl->inserted)
3804         warning (_("Could not remove hardware watchpoint %d."),
3805                  bl->owner->number);
3806     }
3807   else if (bl->owner->type == bp_catchpoint
3808            && breakpoint_enabled (bl->owner)
3809            && !bl->duplicate)
3810     {
3811       gdb_assert (bl->owner->ops != NULL
3812                   && bl->owner->ops->remove_location != NULL);
3813
3814       val = bl->owner->ops->remove_location (bl, reason);
3815       if (val)
3816         return val;
3817
3818       bl->inserted = (reason == DETACH_BREAKPOINT);
3819     }
3820
3821   return 0;
3822 }
3823
3824 static int
3825 remove_breakpoint (struct bp_location *bl)
3826 {
3827   /* BL is never in moribund_locations by our callers.  */
3828   gdb_assert (bl->owner != NULL);
3829
3830   /* The type of none suggests that owner is actually deleted.
3831      This should not ever happen.  */
3832   gdb_assert (bl->owner->type != bp_none);
3833
3834   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3835
3836   switch_to_program_space_and_thread (bl->pspace);
3837
3838   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
3839 }
3840
3841 /* Clear the "inserted" flag in all breakpoints.  */
3842
3843 void
3844 mark_breakpoints_out (void)
3845 {
3846   struct bp_location *bl, **blp_tmp;
3847
3848   ALL_BP_LOCATIONS (bl, blp_tmp)
3849     if (bl->pspace == current_program_space)
3850       bl->inserted = 0;
3851 }
3852
3853 /* Clear the "inserted" flag in all breakpoints and delete any
3854    breakpoints which should go away between runs of the program.
3855
3856    Plus other such housekeeping that has to be done for breakpoints
3857    between runs.
3858
3859    Note: this function gets called at the end of a run (by
3860    generic_mourn_inferior) and when a run begins (by
3861    init_wait_for_inferior).  */
3862
3863
3864
3865 void
3866 breakpoint_init_inferior (enum inf_context context)
3867 {
3868   struct breakpoint *b, *b_tmp;
3869   struct bp_location *bl;
3870   int ix;
3871   struct program_space *pspace = current_program_space;
3872
3873   /* If breakpoint locations are shared across processes, then there's
3874      nothing to do.  */
3875   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3876     return;
3877
3878   mark_breakpoints_out ();
3879
3880   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3881   {
3882     if (b->loc && b->loc->pspace != pspace)
3883       continue;
3884
3885     switch (b->type)
3886       {
3887       case bp_call_dummy:
3888       case bp_longjmp_call_dummy:
3889
3890         /* If the call dummy breakpoint is at the entry point it will
3891            cause problems when the inferior is rerun, so we better get
3892            rid of it.  */
3893
3894       case bp_watchpoint_scope:
3895
3896         /* Also get rid of scope breakpoints.  */
3897
3898       case bp_shlib_event:
3899
3900         /* Also remove solib event breakpoints.  Their addresses may
3901            have changed since the last time we ran the program.
3902            Actually we may now be debugging against different target;
3903            and so the solib backend that installed this breakpoint may
3904            not be used in by the target.  E.g.,
3905
3906            (gdb) file prog-linux
3907            (gdb) run               # native linux target
3908            ...
3909            (gdb) kill
3910            (gdb) file prog-win.exe
3911            (gdb) tar rem :9999     # remote Windows gdbserver.
3912         */
3913
3914       case bp_step_resume:
3915
3916         /* Also remove step-resume breakpoints.  */
3917
3918       case bp_single_step:
3919
3920         /* Also remove single-step breakpoints.  */
3921
3922         delete_breakpoint (b);
3923         break;
3924
3925       case bp_watchpoint:
3926       case bp_hardware_watchpoint:
3927       case bp_read_watchpoint:
3928       case bp_access_watchpoint:
3929         {
3930           struct watchpoint *w = (struct watchpoint *) b;
3931
3932           /* Likewise for watchpoints on local expressions.  */
3933           if (w->exp_valid_block != NULL)
3934             delete_breakpoint (b);
3935           else
3936             {
3937               /* Get rid of existing locations, which are no longer
3938                  valid.  New ones will be created in
3939                  update_watchpoint, when the inferior is restarted.
3940                  The next update_global_location_list call will
3941                  garbage collect them.  */
3942               b->loc = NULL;
3943
3944               if (context == inf_starting)
3945                 {
3946                   /* Reset val field to force reread of starting value in
3947                      insert_breakpoints.  */
3948                   w->val.reset (nullptr);
3949                   w->val_valid = 0;
3950                 }
3951             }
3952         }
3953         break;
3954       default:
3955         break;
3956       }
3957   }
3958
3959   /* Get rid of the moribund locations.  */
3960   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3961     decref_bp_location (&bl);
3962   VEC_free (bp_location_p, moribund_locations);
3963 }
3964
3965 /* These functions concern about actual breakpoints inserted in the
3966    target --- to e.g. check if we need to do decr_pc adjustment or if
3967    we need to hop over the bkpt --- so we check for address space
3968    match, not program space.  */
3969
3970 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3971    exists at PC.  It returns ordinary_breakpoint_here if it's an
3972    ordinary breakpoint, or permanent_breakpoint_here if it's a
3973    permanent breakpoint.
3974    - When continuing from a location with an ordinary breakpoint, we
3975      actually single step once before calling insert_breakpoints.
3976    - When continuing from a location with a permanent breakpoint, we
3977      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3978      the target, to advance the PC past the breakpoint.  */
3979
3980 enum breakpoint_here
3981 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
3982 {
3983   struct bp_location *bl, **blp_tmp;
3984   int any_breakpoint_here = 0;
3985
3986   ALL_BP_LOCATIONS (bl, blp_tmp)
3987     {
3988       if (bl->loc_type != bp_loc_software_breakpoint
3989           && bl->loc_type != bp_loc_hardware_breakpoint)
3990         continue;
3991
3992       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3993       if ((breakpoint_enabled (bl->owner)
3994            || bl->permanent)
3995           && breakpoint_location_address_match (bl, aspace, pc))
3996         {
3997           if (overlay_debugging 
3998               && section_is_overlay (bl->section)
3999               && !section_is_mapped (bl->section))
4000             continue;           /* unmapped overlay -- can't be a match */
4001           else if (bl->permanent)
4002             return permanent_breakpoint_here;
4003           else
4004             any_breakpoint_here = 1;
4005         }
4006     }
4007
4008   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4009 }
4010
4011 /* See breakpoint.h.  */
4012
4013 int
4014 breakpoint_in_range_p (const address_space *aspace,
4015                        CORE_ADDR addr, ULONGEST len)
4016 {
4017   struct bp_location *bl, **blp_tmp;
4018
4019   ALL_BP_LOCATIONS (bl, blp_tmp)
4020     {
4021       if (bl->loc_type != bp_loc_software_breakpoint
4022           && bl->loc_type != bp_loc_hardware_breakpoint)
4023         continue;
4024
4025       if ((breakpoint_enabled (bl->owner)
4026            || bl->permanent)
4027           && breakpoint_location_address_range_overlap (bl, aspace,
4028                                                         addr, len))
4029         {
4030           if (overlay_debugging
4031               && section_is_overlay (bl->section)
4032               && !section_is_mapped (bl->section))
4033             {
4034               /* Unmapped overlay -- can't be a match.  */
4035               continue;
4036             }
4037
4038           return 1;
4039         }
4040     }
4041
4042   return 0;
4043 }
4044
4045 /* Return true if there's a moribund breakpoint at PC.  */
4046
4047 int
4048 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4049 {
4050   struct bp_location *loc;
4051   int ix;
4052
4053   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4054     if (breakpoint_location_address_match (loc, aspace, pc))
4055       return 1;
4056
4057   return 0;
4058 }
4059
4060 /* Returns non-zero iff BL is inserted at PC, in address space
4061    ASPACE.  */
4062
4063 static int
4064 bp_location_inserted_here_p (struct bp_location *bl,
4065                              const address_space *aspace, CORE_ADDR pc)
4066 {
4067   if (bl->inserted
4068       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4069                                    aspace, pc))
4070     {
4071       if (overlay_debugging
4072           && section_is_overlay (bl->section)
4073           && !section_is_mapped (bl->section))
4074         return 0;               /* unmapped overlay -- can't be a match */
4075       else
4076         return 1;
4077     }
4078   return 0;
4079 }
4080
4081 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4082
4083 int
4084 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4085 {
4086   struct bp_location **blp, **blp_tmp = NULL;
4087
4088   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4089     {
4090       struct bp_location *bl = *blp;
4091
4092       if (bl->loc_type != bp_loc_software_breakpoint
4093           && bl->loc_type != bp_loc_hardware_breakpoint)
4094         continue;
4095
4096       if (bp_location_inserted_here_p (bl, aspace, pc))
4097         return 1;
4098     }
4099   return 0;
4100 }
4101
4102 /* This function returns non-zero iff there is a software breakpoint
4103    inserted at PC.  */
4104
4105 int
4106 software_breakpoint_inserted_here_p (const address_space *aspace,
4107                                      CORE_ADDR pc)
4108 {
4109   struct bp_location **blp, **blp_tmp = NULL;
4110
4111   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4112     {
4113       struct bp_location *bl = *blp;
4114
4115       if (bl->loc_type != bp_loc_software_breakpoint)
4116         continue;
4117
4118       if (bp_location_inserted_here_p (bl, aspace, pc))
4119         return 1;
4120     }
4121
4122   return 0;
4123 }
4124
4125 /* See breakpoint.h.  */
4126
4127 int
4128 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4129                                      CORE_ADDR pc)
4130 {
4131   struct bp_location **blp, **blp_tmp = NULL;
4132
4133   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4134     {
4135       struct bp_location *bl = *blp;
4136
4137       if (bl->loc_type != bp_loc_hardware_breakpoint)
4138         continue;
4139
4140       if (bp_location_inserted_here_p (bl, aspace, pc))
4141         return 1;
4142     }
4143
4144   return 0;
4145 }
4146
4147 int
4148 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4149                                        CORE_ADDR addr, ULONGEST len)
4150 {
4151   struct breakpoint *bpt;
4152
4153   ALL_BREAKPOINTS (bpt)
4154     {
4155       struct bp_location *loc;
4156
4157       if (bpt->type != bp_hardware_watchpoint
4158           && bpt->type != bp_access_watchpoint)
4159         continue;
4160
4161       if (!breakpoint_enabled (bpt))
4162         continue;
4163
4164       for (loc = bpt->loc; loc; loc = loc->next)
4165         if (loc->pspace->aspace == aspace && loc->inserted)
4166           {
4167             CORE_ADDR l, h;
4168
4169             /* Check for intersection.  */
4170             l = std::max<CORE_ADDR> (loc->address, addr);
4171             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4172             if (l < h)
4173               return 1;
4174           }
4175     }
4176   return 0;
4177 }
4178 \f
4179
4180 /* bpstat stuff.  External routines' interfaces are documented
4181    in breakpoint.h.  */
4182
4183 int
4184 is_catchpoint (struct breakpoint *ep)
4185 {
4186   return (ep->type == bp_catchpoint);
4187 }
4188
4189 /* Frees any storage that is part of a bpstat.  Does not walk the
4190    'next' chain.  */
4191
4192 bpstats::~bpstats ()
4193 {
4194   if (bp_location_at != NULL)
4195     decref_bp_location (&bp_location_at);
4196 }
4197
4198 /* Clear a bpstat so that it says we are not at any breakpoint.
4199    Also free any storage that is part of a bpstat.  */
4200
4201 void
4202 bpstat_clear (bpstat *bsp)
4203 {
4204   bpstat p;
4205   bpstat q;
4206
4207   if (bsp == 0)
4208     return;
4209   p = *bsp;
4210   while (p != NULL)
4211     {
4212       q = p->next;
4213       delete p;
4214       p = q;
4215     }
4216   *bsp = NULL;
4217 }
4218
4219 bpstats::bpstats (const bpstats &other)
4220   : next (NULL),
4221     bp_location_at (other.bp_location_at),
4222     breakpoint_at (other.breakpoint_at),
4223     commands (other.commands),
4224     print (other.print),
4225     stop (other.stop),
4226     print_it (other.print_it)
4227 {
4228   if (other.old_val != NULL)
4229     old_val = release_value (value_copy (other.old_val.get ()));
4230   incref_bp_location (bp_location_at);
4231 }
4232
4233 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4234    is part of the bpstat is copied as well.  */
4235
4236 bpstat
4237 bpstat_copy (bpstat bs)
4238 {
4239   bpstat p = NULL;
4240   bpstat tmp;
4241   bpstat retval = NULL;
4242
4243   if (bs == NULL)
4244     return bs;
4245
4246   for (; bs != NULL; bs = bs->next)
4247     {
4248       tmp = new bpstats (*bs);
4249
4250       if (p == NULL)
4251         /* This is the first thing in the chain.  */
4252         retval = tmp;
4253       else
4254         p->next = tmp;
4255       p = tmp;
4256     }
4257   p->next = NULL;
4258   return retval;
4259 }
4260
4261 /* Find the bpstat associated with this breakpoint.  */
4262
4263 bpstat
4264 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4265 {
4266   if (bsp == NULL)
4267     return NULL;
4268
4269   for (; bsp != NULL; bsp = bsp->next)
4270     {
4271       if (bsp->breakpoint_at == breakpoint)
4272         return bsp;
4273     }
4274   return NULL;
4275 }
4276
4277 /* See breakpoint.h.  */
4278
4279 int
4280 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4281 {
4282   for (; bsp != NULL; bsp = bsp->next)
4283     {
4284       if (bsp->breakpoint_at == NULL)
4285         {
4286           /* A moribund location can never explain a signal other than
4287              GDB_SIGNAL_TRAP.  */
4288           if (sig == GDB_SIGNAL_TRAP)
4289             return 1;
4290         }
4291       else
4292         {
4293           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4294                                                         sig))
4295             return 1;
4296         }
4297     }
4298
4299   return 0;
4300 }
4301
4302 /* Put in *NUM the breakpoint number of the first breakpoint we are
4303    stopped at.  *BSP upon return is a bpstat which points to the
4304    remaining breakpoints stopped at (but which is not guaranteed to be
4305    good for anything but further calls to bpstat_num).
4306
4307    Return 0 if passed a bpstat which does not indicate any breakpoints.
4308    Return -1 if stopped at a breakpoint that has been deleted since
4309    we set it.
4310    Return 1 otherwise.  */
4311
4312 int
4313 bpstat_num (bpstat *bsp, int *num)
4314 {
4315   struct breakpoint *b;
4316
4317   if ((*bsp) == NULL)
4318     return 0;                   /* No more breakpoint values */
4319
4320   /* We assume we'll never have several bpstats that correspond to a
4321      single breakpoint -- otherwise, this function might return the
4322      same number more than once and this will look ugly.  */
4323   b = (*bsp)->breakpoint_at;
4324   *bsp = (*bsp)->next;
4325   if (b == NULL)
4326     return -1;                  /* breakpoint that's been deleted since */
4327
4328   *num = b->number;             /* We have its number */
4329   return 1;
4330 }
4331
4332 /* See breakpoint.h.  */
4333
4334 void
4335 bpstat_clear_actions (void)
4336 {
4337   bpstat bs;
4338
4339   if (inferior_ptid == null_ptid)
4340     return;
4341
4342   thread_info *tp = inferior_thread ();
4343   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4344     {
4345       bs->commands = NULL;
4346       bs->old_val.reset (nullptr);
4347     }
4348 }
4349
4350 /* Called when a command is about to proceed the inferior.  */
4351
4352 static void
4353 breakpoint_about_to_proceed (void)
4354 {
4355   if (inferior_ptid != null_ptid)
4356     {
4357       struct thread_info *tp = inferior_thread ();
4358
4359       /* Allow inferior function calls in breakpoint commands to not
4360          interrupt the command list.  When the call finishes
4361          successfully, the inferior will be standing at the same
4362          breakpoint as if nothing happened.  */
4363       if (tp->control.in_infcall)
4364         return;
4365     }
4366
4367   breakpoint_proceeded = 1;
4368 }
4369
4370 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4371    or its equivalent.  */
4372
4373 static int
4374 command_line_is_silent (struct command_line *cmd)
4375 {
4376   return cmd && (strcmp ("silent", cmd->line) == 0);
4377 }
4378
4379 /* Execute all the commands associated with all the breakpoints at
4380    this location.  Any of these commands could cause the process to
4381    proceed beyond this point, etc.  We look out for such changes by
4382    checking the global "breakpoint_proceeded" after each command.
4383
4384    Returns true if a breakpoint command resumed the inferior.  In that
4385    case, it is the caller's responsibility to recall it again with the
4386    bpstat of the current thread.  */
4387
4388 static int
4389 bpstat_do_actions_1 (bpstat *bsp)
4390 {
4391   bpstat bs;
4392   int again = 0;
4393
4394   /* Avoid endless recursion if a `source' command is contained
4395      in bs->commands.  */
4396   if (executing_breakpoint_commands)
4397     return 0;
4398
4399   scoped_restore save_executing
4400     = make_scoped_restore (&executing_breakpoint_commands, 1);
4401
4402   scoped_restore preventer = prevent_dont_repeat ();
4403
4404   /* This pointer will iterate over the list of bpstat's.  */
4405   bs = *bsp;
4406
4407   breakpoint_proceeded = 0;
4408   for (; bs != NULL; bs = bs->next)
4409     {
4410       struct command_line *cmd = NULL;
4411
4412       /* Take ownership of the BSP's command tree, if it has one.
4413
4414          The command tree could legitimately contain commands like
4415          'step' and 'next', which call clear_proceed_status, which
4416          frees stop_bpstat's command tree.  To make sure this doesn't
4417          free the tree we're executing out from under us, we need to
4418          take ownership of the tree ourselves.  Since a given bpstat's
4419          commands are only executed once, we don't need to copy it; we
4420          can clear the pointer in the bpstat, and make sure we free
4421          the tree when we're done.  */
4422       counted_command_line ccmd = bs->commands;
4423       bs->commands = NULL;
4424       if (ccmd != NULL)
4425         cmd = ccmd.get ();
4426       if (command_line_is_silent (cmd))
4427         {
4428           /* The action has been already done by bpstat_stop_status.  */
4429           cmd = cmd->next;
4430         }
4431
4432       while (cmd != NULL)
4433         {
4434           execute_control_command (cmd);
4435
4436           if (breakpoint_proceeded)
4437             break;
4438           else
4439             cmd = cmd->next;
4440         }
4441
4442       if (breakpoint_proceeded)
4443         {
4444           if (current_ui->async)
4445             /* If we are in async mode, then the target might be still
4446                running, not stopped at any breakpoint, so nothing for
4447                us to do here -- just return to the event loop.  */
4448             ;
4449           else
4450             /* In sync mode, when execute_control_command returns
4451                we're already standing on the next breakpoint.
4452                Breakpoint commands for that stop were not run, since
4453                execute_command does not run breakpoint commands --
4454                only command_line_handler does, but that one is not
4455                involved in execution of breakpoint commands.  So, we
4456                can now execute breakpoint commands.  It should be
4457                noted that making execute_command do bpstat actions is
4458                not an option -- in this case we'll have recursive
4459                invocation of bpstat for each breakpoint with a
4460                command, and can easily blow up GDB stack.  Instead, we
4461                return true, which will trigger the caller to recall us
4462                with the new stop_bpstat.  */
4463             again = 1;
4464           break;
4465         }
4466     }
4467   return again;
4468 }
4469
4470 /* Helper for bpstat_do_actions.  Get the current thread, if there's
4471    one, is alive and has execution.  Return NULL otherwise.  */
4472
4473 static thread_info *
4474 get_bpstat_thread ()
4475 {
4476   if (inferior_ptid == null_ptid || !target_has_execution)
4477     return NULL;
4478
4479   thread_info *tp = inferior_thread ();
4480   if (tp->state == THREAD_EXITED || tp->executing)
4481     return NULL;
4482   return tp;
4483 }
4484
4485 void
4486 bpstat_do_actions (void)
4487 {
4488   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4489   thread_info *tp;
4490
4491   /* Do any commands attached to breakpoint we are stopped at.  */
4492   while ((tp = get_bpstat_thread ()) != NULL)
4493     {
4494       /* Since in sync mode, bpstat_do_actions may resume the
4495          inferior, and only return when it is stopped at the next
4496          breakpoint, we keep doing breakpoint actions until it returns
4497          false to indicate the inferior was not resumed.  */
4498       if (!bpstat_do_actions_1 (&tp->control.stop_bpstat))
4499         break;
4500     }
4501
4502   discard_cleanups (cleanup_if_error);
4503 }
4504
4505 /* Print out the (old or new) value associated with a watchpoint.  */
4506
4507 static void
4508 watchpoint_value_print (struct value *val, struct ui_file *stream)
4509 {
4510   if (val == NULL)
4511     fprintf_unfiltered (stream, _("<unreadable>"));
4512   else
4513     {
4514       struct value_print_options opts;
4515       get_user_print_options (&opts);
4516       value_print (val, stream, &opts);
4517     }
4518 }
4519
4520 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4521    debugging multiple threads.  */
4522
4523 void
4524 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4525 {
4526   if (uiout->is_mi_like_p ())
4527     return;
4528
4529   uiout->text ("\n");
4530
4531   if (show_thread_that_caused_stop ())
4532     {
4533       const char *name;
4534       struct thread_info *thr = inferior_thread ();
4535
4536       uiout->text ("Thread ");
4537       uiout->field_fmt ("thread-id", "%s", print_thread_id (thr));
4538
4539       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4540       if (name != NULL)
4541         {
4542           uiout->text (" \"");
4543           uiout->field_fmt ("name", "%s", name);
4544           uiout->text ("\"");
4545         }
4546
4547       uiout->text (" hit ");
4548     }
4549 }
4550
4551 /* Generic routine for printing messages indicating why we
4552    stopped.  The behavior of this function depends on the value
4553    'print_it' in the bpstat structure.  Under some circumstances we
4554    may decide not to print anything here and delegate the task to
4555    normal_stop().  */
4556
4557 static enum print_stop_action
4558 print_bp_stop_message (bpstat bs)
4559 {
4560   switch (bs->print_it)
4561     {
4562     case print_it_noop:
4563       /* Nothing should be printed for this bpstat entry.  */
4564       return PRINT_UNKNOWN;
4565       break;
4566
4567     case print_it_done:
4568       /* We still want to print the frame, but we already printed the
4569          relevant messages.  */
4570       return PRINT_SRC_AND_LOC;
4571       break;
4572
4573     case print_it_normal:
4574       {
4575         struct breakpoint *b = bs->breakpoint_at;
4576
4577         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4578            which has since been deleted.  */
4579         if (b == NULL)
4580           return PRINT_UNKNOWN;
4581
4582         /* Normal case.  Call the breakpoint's print_it method.  */
4583         return b->ops->print_it (bs);
4584       }
4585       break;
4586
4587     default:
4588       internal_error (__FILE__, __LINE__,
4589                       _("print_bp_stop_message: unrecognized enum value"));
4590       break;
4591     }
4592 }
4593
4594 /* A helper function that prints a shared library stopped event.  */
4595
4596 static void
4597 print_solib_event (int is_catchpoint)
4598 {
4599   bool any_deleted = !current_program_space->deleted_solibs.empty ();
4600   bool any_added = !current_program_space->added_solibs.empty ();
4601
4602   if (!is_catchpoint)
4603     {
4604       if (any_added || any_deleted)
4605         current_uiout->text (_("Stopped due to shared library event:\n"));
4606       else
4607         current_uiout->text (_("Stopped due to shared library event (no "
4608                                "libraries added or removed)\n"));
4609     }
4610
4611   if (current_uiout->is_mi_like_p ())
4612     current_uiout->field_string ("reason",
4613                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4614
4615   if (any_deleted)
4616     {
4617       current_uiout->text (_("  Inferior unloaded "));
4618       ui_out_emit_list list_emitter (current_uiout, "removed");
4619       for (int ix = 0; ix < current_program_space->deleted_solibs.size (); ix++)
4620         {
4621           const std::string &name = current_program_space->deleted_solibs[ix];
4622
4623           if (ix > 0)
4624             current_uiout->text ("    ");
4625           current_uiout->field_string ("library", name);
4626           current_uiout->text ("\n");
4627         }
4628     }
4629
4630   if (any_added)
4631     {
4632       current_uiout->text (_("  Inferior loaded "));
4633       ui_out_emit_list list_emitter (current_uiout, "added");
4634       bool first = true;
4635       for (so_list *iter : current_program_space->added_solibs)
4636         {
4637           if (!first)
4638             current_uiout->text ("    ");
4639           first = false;
4640           current_uiout->field_string ("library", iter->so_name);
4641           current_uiout->text ("\n");
4642         }
4643     }
4644 }
4645
4646 /* Print a message indicating what happened.  This is called from
4647    normal_stop().  The input to this routine is the head of the bpstat
4648    list - a list of the eventpoints that caused this stop.  KIND is
4649    the target_waitkind for the stopping event.  This
4650    routine calls the generic print routine for printing a message
4651    about reasons for stopping.  This will print (for example) the
4652    "Breakpoint n," part of the output.  The return value of this
4653    routine is one of:
4654
4655    PRINT_UNKNOWN: Means we printed nothing.
4656    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4657    code to print the location.  An example is 
4658    "Breakpoint 1, " which should be followed by
4659    the location.
4660    PRINT_SRC_ONLY: Means we printed something, but there is no need
4661    to also print the location part of the message.
4662    An example is the catch/throw messages, which
4663    don't require a location appended to the end.
4664    PRINT_NOTHING: We have done some printing and we don't need any 
4665    further info to be printed.  */
4666
4667 enum print_stop_action
4668 bpstat_print (bpstat bs, int kind)
4669 {
4670   enum print_stop_action val;
4671
4672   /* Maybe another breakpoint in the chain caused us to stop.
4673      (Currently all watchpoints go on the bpstat whether hit or not.
4674      That probably could (should) be changed, provided care is taken
4675      with respect to bpstat_explains_signal).  */
4676   for (; bs; bs = bs->next)
4677     {
4678       val = print_bp_stop_message (bs);
4679       if (val == PRINT_SRC_ONLY 
4680           || val == PRINT_SRC_AND_LOC 
4681           || val == PRINT_NOTHING)
4682         return val;
4683     }
4684
4685   /* If we had hit a shared library event breakpoint,
4686      print_bp_stop_message would print out this message.  If we hit an
4687      OS-level shared library event, do the same thing.  */
4688   if (kind == TARGET_WAITKIND_LOADED)
4689     {
4690       print_solib_event (0);
4691       return PRINT_NOTHING;
4692     }
4693
4694   /* We reached the end of the chain, or we got a null BS to start
4695      with and nothing was printed.  */
4696   return PRINT_UNKNOWN;
4697 }
4698
4699 /* Evaluate the boolean expression EXP and return the result.  */
4700
4701 static bool
4702 breakpoint_cond_eval (expression *exp)
4703 {
4704   struct value *mark = value_mark ();
4705   bool res = value_true (evaluate_expression (exp));
4706
4707   value_free_to_mark (mark);
4708   return res;
4709 }
4710
4711 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4712
4713 bpstats::bpstats (struct bp_location *bl, bpstat **bs_link_pointer)
4714   : next (NULL),
4715     bp_location_at (bl),
4716     breakpoint_at (bl->owner),
4717     commands (NULL),
4718     print (0),
4719     stop (0),
4720     print_it (print_it_normal)
4721 {
4722   incref_bp_location (bl);
4723   **bs_link_pointer = this;
4724   *bs_link_pointer = &next;
4725 }
4726
4727 bpstats::bpstats ()
4728   : next (NULL),
4729     bp_location_at (NULL),
4730     breakpoint_at (NULL),
4731     commands (NULL),
4732     print (0),
4733     stop (0),
4734     print_it (print_it_normal)
4735 {
4736 }
4737 \f
4738 /* The target has stopped with waitstatus WS.  Check if any hardware
4739    watchpoints have triggered, according to the target.  */
4740
4741 int
4742 watchpoints_triggered (struct target_waitstatus *ws)
4743 {
4744   bool stopped_by_watchpoint = target_stopped_by_watchpoint ();
4745   CORE_ADDR addr;
4746   struct breakpoint *b;
4747
4748   if (!stopped_by_watchpoint)
4749     {
4750       /* We were not stopped by a watchpoint.  Mark all watchpoints
4751          as not triggered.  */
4752       ALL_BREAKPOINTS (b)
4753         if (is_hardware_watchpoint (b))
4754           {
4755             struct watchpoint *w = (struct watchpoint *) b;
4756
4757             w->watchpoint_triggered = watch_triggered_no;
4758           }
4759
4760       return 0;
4761     }
4762
4763   if (!target_stopped_data_address (current_top_target (), &addr))
4764     {
4765       /* We were stopped by a watchpoint, but we don't know where.
4766          Mark all watchpoints as unknown.  */
4767       ALL_BREAKPOINTS (b)
4768         if (is_hardware_watchpoint (b))
4769           {
4770             struct watchpoint *w = (struct watchpoint *) b;
4771
4772             w->watchpoint_triggered = watch_triggered_unknown;
4773           }
4774
4775       return 1;
4776     }
4777
4778   /* The target could report the data address.  Mark watchpoints
4779      affected by this data address as triggered, and all others as not
4780      triggered.  */
4781
4782   ALL_BREAKPOINTS (b)
4783     if (is_hardware_watchpoint (b))
4784       {
4785         struct watchpoint *w = (struct watchpoint *) b;
4786         struct bp_location *loc;
4787
4788         w->watchpoint_triggered = watch_triggered_no;
4789         for (loc = b->loc; loc; loc = loc->next)
4790           {
4791             if (is_masked_watchpoint (b))
4792               {
4793                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4794                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4795
4796                 if (newaddr == start)
4797                   {
4798                     w->watchpoint_triggered = watch_triggered_yes;
4799                     break;
4800                   }
4801               }
4802             /* Exact match not required.  Within range is sufficient.  */
4803             else if (target_watchpoint_addr_within_range (current_top_target (),
4804                                                          addr, loc->address,
4805                                                          loc->length))
4806               {
4807                 w->watchpoint_triggered = watch_triggered_yes;
4808                 break;
4809               }
4810           }
4811       }
4812
4813   return 1;
4814 }
4815
4816 /* Possible return values for watchpoint_check.  */
4817 enum wp_check_result
4818   {
4819     /* The watchpoint has been deleted.  */
4820     WP_DELETED = 1,
4821
4822     /* The value has changed.  */
4823     WP_VALUE_CHANGED = 2,
4824
4825     /* The value has not changed.  */
4826     WP_VALUE_NOT_CHANGED = 3,
4827
4828     /* Ignore this watchpoint, no matter if the value changed or not.  */
4829     WP_IGNORE = 4,
4830   };
4831
4832 #define BP_TEMPFLAG 1
4833 #define BP_HARDWAREFLAG 2
4834
4835 /* Evaluate watchpoint condition expression and check if its value
4836    changed.  */
4837
4838 static wp_check_result
4839 watchpoint_check (bpstat bs)
4840 {
4841   struct watchpoint *b;
4842   struct frame_info *fr;
4843   int within_current_scope;
4844
4845   /* BS is built from an existing struct breakpoint.  */
4846   gdb_assert (bs->breakpoint_at != NULL);
4847   b = (struct watchpoint *) bs->breakpoint_at;
4848
4849   /* If this is a local watchpoint, we only want to check if the
4850      watchpoint frame is in scope if the current thread is the thread
4851      that was used to create the watchpoint.  */
4852   if (!watchpoint_in_thread_scope (b))
4853     return WP_IGNORE;
4854
4855   if (b->exp_valid_block == NULL)
4856     within_current_scope = 1;
4857   else
4858     {
4859       struct frame_info *frame = get_current_frame ();
4860       struct gdbarch *frame_arch = get_frame_arch (frame);
4861       CORE_ADDR frame_pc = get_frame_pc (frame);
4862
4863       /* stack_frame_destroyed_p() returns a non-zero value if we're
4864          still in the function but the stack frame has already been
4865          invalidated.  Since we can't rely on the values of local
4866          variables after the stack has been destroyed, we are treating
4867          the watchpoint in that state as `not changed' without further
4868          checking.  Don't mark watchpoints as changed if the current
4869          frame is in an epilogue - even if they are in some other
4870          frame, our view of the stack is likely to be wrong and
4871          frame_find_by_id could error out.  */
4872       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
4873         return WP_IGNORE;
4874
4875       fr = frame_find_by_id (b->watchpoint_frame);
4876       within_current_scope = (fr != NULL);
4877
4878       /* If we've gotten confused in the unwinder, we might have
4879          returned a frame that can't describe this variable.  */
4880       if (within_current_scope)
4881         {
4882           struct symbol *function;
4883
4884           function = get_frame_function (fr);
4885           if (function == NULL
4886               || !contained_in (b->exp_valid_block,
4887                                 SYMBOL_BLOCK_VALUE (function)))
4888             within_current_scope = 0;
4889         }
4890
4891       if (within_current_scope)
4892         /* If we end up stopping, the current frame will get selected
4893            in normal_stop.  So this call to select_frame won't affect
4894            the user.  */
4895         select_frame (fr);
4896     }
4897
4898   if (within_current_scope)
4899     {
4900       /* We use value_{,free_to_}mark because it could be a *long*
4901          time before we return to the command level and call
4902          free_all_values.  We can't call free_all_values because we
4903          might be in the middle of evaluating a function call.  */
4904
4905       int pc = 0;
4906       struct value *mark;
4907       struct value *new_val;
4908
4909       if (is_masked_watchpoint (b))
4910         /* Since we don't know the exact trigger address (from
4911            stopped_data_address), just tell the user we've triggered
4912            a mask watchpoint.  */
4913         return WP_VALUE_CHANGED;
4914
4915       mark = value_mark ();
4916       fetch_subexp_value (b->exp.get (), &pc, &new_val, NULL, NULL, 0);
4917
4918       if (b->val_bitsize != 0)
4919         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
4920
4921       /* We use value_equal_contents instead of value_equal because
4922          the latter coerces an array to a pointer, thus comparing just
4923          the address of the array instead of its contents.  This is
4924          not what we want.  */
4925       if ((b->val != NULL) != (new_val != NULL)
4926           || (b->val != NULL && !value_equal_contents (b->val.get (),
4927                                                        new_val)))
4928         {
4929           bs->old_val = b->val;
4930           b->val = release_value (new_val);
4931           b->val_valid = 1;
4932           if (new_val != NULL)
4933             value_free_to_mark (mark);
4934           return WP_VALUE_CHANGED;
4935         }
4936       else
4937         {
4938           /* Nothing changed.  */
4939           value_free_to_mark (mark);
4940           return WP_VALUE_NOT_CHANGED;
4941         }
4942     }
4943   else
4944     {
4945       /* This seems like the only logical thing to do because
4946          if we temporarily ignored the watchpoint, then when
4947          we reenter the block in which it is valid it contains
4948          garbage (in the case of a function, it may have two
4949          garbage values, one before and one after the prologue).
4950          So we can't even detect the first assignment to it and
4951          watch after that (since the garbage may or may not equal
4952          the first value assigned).  */
4953       /* We print all the stop information in
4954          breakpoint_ops->print_it, but in this case, by the time we
4955          call breakpoint_ops->print_it this bp will be deleted
4956          already.  So we have no choice but print the information
4957          here.  */
4958
4959       SWITCH_THRU_ALL_UIS ()
4960         {
4961           struct ui_out *uiout = current_uiout;
4962
4963           if (uiout->is_mi_like_p ())
4964             uiout->field_string
4965               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4966           uiout->text ("\nWatchpoint ");
4967           uiout->field_int ("wpnum", b->number);
4968           uiout->text (" deleted because the program has left the block in\n"
4969                        "which its expression is valid.\n");
4970         }
4971
4972       /* Make sure the watchpoint's commands aren't executed.  */
4973       b->commands = NULL;
4974       watchpoint_del_at_next_stop (b);
4975
4976       return WP_DELETED;
4977     }
4978 }
4979
4980 /* Return true if it looks like target has stopped due to hitting
4981    breakpoint location BL.  This function does not check if we should
4982    stop, only if BL explains the stop.  */
4983
4984 static int
4985 bpstat_check_location (const struct bp_location *bl,
4986                        const address_space *aspace, CORE_ADDR bp_addr,
4987                        const struct target_waitstatus *ws)
4988 {
4989   struct breakpoint *b = bl->owner;
4990
4991   /* BL is from an existing breakpoint.  */
4992   gdb_assert (b != NULL);
4993
4994   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4995 }
4996
4997 /* Determine if the watched values have actually changed, and we
4998    should stop.  If not, set BS->stop to 0.  */
4999
5000 static void
5001 bpstat_check_watchpoint (bpstat bs)
5002 {
5003   const struct bp_location *bl;
5004   struct watchpoint *b;
5005
5006   /* BS is built for existing struct breakpoint.  */
5007   bl = bs->bp_location_at;
5008   gdb_assert (bl != NULL);
5009   b = (struct watchpoint *) bs->breakpoint_at;
5010   gdb_assert (b != NULL);
5011
5012     {
5013       int must_check_value = 0;
5014       
5015       if (b->type == bp_watchpoint)
5016         /* For a software watchpoint, we must always check the
5017            watched value.  */
5018         must_check_value = 1;
5019       else if (b->watchpoint_triggered == watch_triggered_yes)
5020         /* We have a hardware watchpoint (read, write, or access)
5021            and the target earlier reported an address watched by
5022            this watchpoint.  */
5023         must_check_value = 1;
5024       else if (b->watchpoint_triggered == watch_triggered_unknown
5025                && b->type == bp_hardware_watchpoint)
5026         /* We were stopped by a hardware watchpoint, but the target could
5027            not report the data address.  We must check the watchpoint's
5028            value.  Access and read watchpoints are out of luck; without
5029            a data address, we can't figure it out.  */
5030         must_check_value = 1;
5031
5032       if (must_check_value)
5033         {
5034           wp_check_result e;
5035
5036           TRY
5037             {
5038               e = watchpoint_check (bs);
5039             }
5040           CATCH (ex, RETURN_MASK_ALL)
5041             {
5042               exception_fprintf (gdb_stderr, ex,
5043                                  "Error evaluating expression "
5044                                  "for watchpoint %d\n",
5045                                  b->number);
5046
5047               SWITCH_THRU_ALL_UIS ()
5048                 {
5049                   printf_filtered (_("Watchpoint %d deleted.\n"),
5050                                    b->number);
5051                 }
5052               watchpoint_del_at_next_stop (b);
5053               e = WP_DELETED;
5054             }
5055           END_CATCH
5056
5057           switch (e)
5058             {
5059             case WP_DELETED:
5060               /* We've already printed what needs to be printed.  */
5061               bs->print_it = print_it_done;
5062               /* Stop.  */
5063               break;
5064             case WP_IGNORE:
5065               bs->print_it = print_it_noop;
5066               bs->stop = 0;
5067               break;
5068             case WP_VALUE_CHANGED:
5069               if (b->type == bp_read_watchpoint)
5070                 {
5071                   /* There are two cases to consider here:
5072
5073                      1. We're watching the triggered memory for reads.
5074                      In that case, trust the target, and always report
5075                      the watchpoint hit to the user.  Even though
5076                      reads don't cause value changes, the value may
5077                      have changed since the last time it was read, and
5078                      since we're not trapping writes, we will not see
5079                      those, and as such we should ignore our notion of
5080                      old value.
5081
5082                      2. We're watching the triggered memory for both
5083                      reads and writes.  There are two ways this may
5084                      happen:
5085
5086                      2.1. This is a target that can't break on data
5087                      reads only, but can break on accesses (reads or
5088                      writes), such as e.g., x86.  We detect this case
5089                      at the time we try to insert read watchpoints.
5090
5091                      2.2. Otherwise, the target supports read
5092                      watchpoints, but, the user set an access or write
5093                      watchpoint watching the same memory as this read
5094                      watchpoint.
5095
5096                      If we're watching memory writes as well as reads,
5097                      ignore watchpoint hits when we find that the
5098                      value hasn't changed, as reads don't cause
5099                      changes.  This still gives false positives when
5100                      the program writes the same value to memory as
5101                      what there was already in memory (we will confuse
5102                      it for a read), but it's much better than
5103                      nothing.  */
5104
5105                   int other_write_watchpoint = 0;
5106
5107                   if (bl->watchpoint_type == hw_read)
5108                     {
5109                       struct breakpoint *other_b;
5110
5111                       ALL_BREAKPOINTS (other_b)
5112                         if (other_b->type == bp_hardware_watchpoint
5113                             || other_b->type == bp_access_watchpoint)
5114                           {
5115                             struct watchpoint *other_w =
5116                               (struct watchpoint *) other_b;
5117
5118                             if (other_w->watchpoint_triggered
5119                                 == watch_triggered_yes)
5120                               {
5121                                 other_write_watchpoint = 1;
5122                                 break;
5123                               }
5124                           }
5125                     }
5126
5127                   if (other_write_watchpoint
5128                       || bl->watchpoint_type == hw_access)
5129                     {
5130                       /* We're watching the same memory for writes,
5131                          and the value changed since the last time we
5132                          updated it, so this trap must be for a write.
5133                          Ignore it.  */
5134                       bs->print_it = print_it_noop;
5135                       bs->stop = 0;
5136                     }
5137                 }
5138               break;
5139             case WP_VALUE_NOT_CHANGED:
5140               if (b->type == bp_hardware_watchpoint
5141                   || b->type == bp_watchpoint)
5142                 {
5143                   /* Don't stop: write watchpoints shouldn't fire if
5144                      the value hasn't changed.  */
5145                   bs->print_it = print_it_noop;
5146                   bs->stop = 0;
5147                 }
5148               /* Stop.  */
5149               break;
5150             default:
5151               /* Can't happen.  */
5152               break;
5153             }
5154         }
5155       else      /* must_check_value == 0 */
5156         {
5157           /* This is a case where some watchpoint(s) triggered, but
5158              not at the address of this watchpoint, or else no
5159              watchpoint triggered after all.  So don't print
5160              anything for this watchpoint.  */
5161           bs->print_it = print_it_noop;
5162           bs->stop = 0;
5163         }
5164     }
5165 }
5166
5167 /* For breakpoints that are currently marked as telling gdb to stop,
5168    check conditions (condition proper, frame, thread and ignore count)
5169    of breakpoint referred to by BS.  If we should not stop for this
5170    breakpoint, set BS->stop to 0.  */
5171
5172 static void
5173 bpstat_check_breakpoint_conditions (bpstat bs, thread_info *thread)
5174 {
5175   const struct bp_location *bl;
5176   struct breakpoint *b;
5177   /* Assume stop.  */
5178   bool condition_result = true;
5179   struct expression *cond;
5180
5181   gdb_assert (bs->stop);
5182
5183   /* BS is built for existing struct breakpoint.  */
5184   bl = bs->bp_location_at;
5185   gdb_assert (bl != NULL);
5186   b = bs->breakpoint_at;
5187   gdb_assert (b != NULL);
5188
5189   /* Even if the target evaluated the condition on its end and notified GDB, we
5190      need to do so again since GDB does not know if we stopped due to a
5191      breakpoint or a single step breakpoint.  */
5192
5193   if (frame_id_p (b->frame_id)
5194       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5195     {
5196       bs->stop = 0;
5197       return;
5198     }
5199
5200   /* If this is a thread/task-specific breakpoint, don't waste cpu
5201      evaluating the condition if this isn't the specified
5202      thread/task.  */
5203   if ((b->thread != -1 && b->thread != thread->global_num)
5204       || (b->task != 0 && b->task != ada_get_task_number (thread)))
5205     {
5206       bs->stop = 0;
5207       return;
5208     }
5209
5210   /* Evaluate extension language breakpoints that have a "stop" method
5211      implemented.  */
5212   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5213
5214   if (is_watchpoint (b))
5215     {
5216       struct watchpoint *w = (struct watchpoint *) b;
5217
5218       cond = w->cond_exp.get ();
5219     }
5220   else
5221     cond = bl->cond.get ();
5222
5223   if (cond && b->disposition != disp_del_at_next_stop)
5224     {
5225       int within_current_scope = 1;
5226       struct watchpoint * w;
5227
5228       /* We use value_mark and value_free_to_mark because it could
5229          be a long time before we return to the command level and
5230          call free_all_values.  We can't call free_all_values
5231          because we might be in the middle of evaluating a
5232          function call.  */
5233       struct value *mark = value_mark ();
5234
5235       if (is_watchpoint (b))
5236         w = (struct watchpoint *) b;
5237       else
5238         w = NULL;
5239
5240       /* Need to select the frame, with all that implies so that
5241          the conditions will have the right context.  Because we
5242          use the frame, we will not see an inlined function's
5243          variables when we arrive at a breakpoint at the start
5244          of the inlined function; the current frame will be the
5245          call site.  */
5246       if (w == NULL || w->cond_exp_valid_block == NULL)
5247         select_frame (get_current_frame ());
5248       else
5249         {
5250           struct frame_info *frame;
5251
5252           /* For local watchpoint expressions, which particular
5253              instance of a local is being watched matters, so we
5254              keep track of the frame to evaluate the expression
5255              in.  To evaluate the condition however, it doesn't
5256              really matter which instantiation of the function
5257              where the condition makes sense triggers the
5258              watchpoint.  This allows an expression like "watch
5259              global if q > 10" set in `func', catch writes to
5260              global on all threads that call `func', or catch
5261              writes on all recursive calls of `func' by a single
5262              thread.  We simply always evaluate the condition in
5263              the innermost frame that's executing where it makes
5264              sense to evaluate the condition.  It seems
5265              intuitive.  */
5266           frame = block_innermost_frame (w->cond_exp_valid_block);
5267           if (frame != NULL)
5268             select_frame (frame);
5269           else
5270             within_current_scope = 0;
5271         }
5272       if (within_current_scope)
5273         {
5274           TRY
5275             {
5276               condition_result = breakpoint_cond_eval (cond);
5277             }
5278           CATCH (ex, RETURN_MASK_ALL)
5279             {
5280               exception_fprintf (gdb_stderr, ex,
5281                                  "Error in testing breakpoint condition:\n");
5282             }
5283           END_CATCH
5284         }
5285       else
5286         {
5287           warning (_("Watchpoint condition cannot be tested "
5288                      "in the current scope"));
5289           /* If we failed to set the right context for this
5290              watchpoint, unconditionally report it.  */
5291         }
5292       /* FIXME-someday, should give breakpoint #.  */
5293       value_free_to_mark (mark);
5294     }
5295
5296   if (cond && !condition_result)
5297     {
5298       bs->stop = 0;
5299     }
5300   else if (b->ignore_count > 0)
5301     {
5302       b->ignore_count--;
5303       bs->stop = 0;
5304       /* Increase the hit count even though we don't stop.  */
5305       ++(b->hit_count);
5306       gdb::observers::breakpoint_modified.notify (b);
5307     }   
5308 }
5309
5310 /* Returns true if we need to track moribund locations of LOC's type
5311    on the current target.  */
5312
5313 static int
5314 need_moribund_for_location_type (struct bp_location *loc)
5315 {
5316   return ((loc->loc_type == bp_loc_software_breakpoint
5317            && !target_supports_stopped_by_sw_breakpoint ())
5318           || (loc->loc_type == bp_loc_hardware_breakpoint
5319               && !target_supports_stopped_by_hw_breakpoint ()));
5320 }
5321
5322 /* See breakpoint.h.  */
5323
5324 bpstat
5325 build_bpstat_chain (const address_space *aspace, CORE_ADDR bp_addr,
5326                     const struct target_waitstatus *ws)
5327 {
5328   struct breakpoint *b;
5329   bpstat bs_head = NULL, *bs_link = &bs_head;
5330
5331   ALL_BREAKPOINTS (b)
5332     {
5333       if (!breakpoint_enabled (b))
5334         continue;
5335
5336       for (bp_location *bl = b->loc; bl != NULL; bl = bl->next)
5337         {
5338           /* For hardware watchpoints, we look only at the first
5339              location.  The watchpoint_check function will work on the
5340              entire expression, not the individual locations.  For
5341              read watchpoints, the watchpoints_triggered function has
5342              checked all locations already.  */
5343           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5344             break;
5345
5346           if (!bl->enabled || bl->shlib_disabled)
5347             continue;
5348
5349           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5350             continue;
5351
5352           /* Come here if it's a watchpoint, or if the break address
5353              matches.  */
5354
5355           bpstat bs = new bpstats (bl, &bs_link);       /* Alloc a bpstat to
5356                                                            explain stop.  */
5357
5358           /* Assume we stop.  Should we find a watchpoint that is not
5359              actually triggered, or if the condition of the breakpoint
5360              evaluates as false, we'll reset 'stop' to 0.  */
5361           bs->stop = 1;
5362           bs->print = 1;
5363
5364           /* If this is a scope breakpoint, mark the associated
5365              watchpoint as triggered so that we will handle the
5366              out-of-scope event.  We'll get to the watchpoint next
5367              iteration.  */
5368           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5369             {
5370               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5371
5372               w->watchpoint_triggered = watch_triggered_yes;
5373             }
5374         }
5375     }
5376
5377   /* Check if a moribund breakpoint explains the stop.  */
5378   if (!target_supports_stopped_by_sw_breakpoint ()
5379       || !target_supports_stopped_by_hw_breakpoint ())
5380     {
5381       bp_location *loc;
5382
5383       for (int ix = 0;
5384            VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5385         {
5386           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5387               && need_moribund_for_location_type (loc))
5388             {
5389               bpstat bs = new bpstats (loc, &bs_link);
5390               /* For hits of moribund locations, we should just proceed.  */
5391               bs->stop = 0;
5392               bs->print = 0;
5393               bs->print_it = print_it_noop;
5394             }
5395         }
5396     }
5397
5398   return bs_head;
5399 }
5400
5401 /* See breakpoint.h.  */
5402
5403 bpstat
5404 bpstat_stop_status (const address_space *aspace,
5405                     CORE_ADDR bp_addr, thread_info *thread,
5406                     const struct target_waitstatus *ws,
5407                     bpstat stop_chain)
5408 {
5409   struct breakpoint *b = NULL;
5410   /* First item of allocated bpstat's.  */
5411   bpstat bs_head = stop_chain;
5412   bpstat bs;
5413   int need_remove_insert;
5414   int removed_any;
5415
5416   /* First, build the bpstat chain with locations that explain a
5417      target stop, while being careful to not set the target running,
5418      as that may invalidate locations (in particular watchpoint
5419      locations are recreated).  Resuming will happen here with
5420      breakpoint conditions or watchpoint expressions that include
5421      inferior function calls.  */
5422   if (bs_head == NULL)
5423     bs_head = build_bpstat_chain (aspace, bp_addr, ws);
5424
5425   /* A bit of special processing for shlib breakpoints.  We need to
5426      process solib loading here, so that the lists of loaded and
5427      unloaded libraries are correct before we handle "catch load" and
5428      "catch unload".  */
5429   for (bs = bs_head; bs != NULL; bs = bs->next)
5430     {
5431       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5432         {
5433           handle_solib_event ();
5434           break;
5435         }
5436     }
5437
5438   /* Now go through the locations that caused the target to stop, and
5439      check whether we're interested in reporting this stop to higher
5440      layers, or whether we should resume the target transparently.  */
5441
5442   removed_any = 0;
5443
5444   for (bs = bs_head; bs != NULL; bs = bs->next)
5445     {
5446       if (!bs->stop)
5447         continue;
5448
5449       b = bs->breakpoint_at;
5450       b->ops->check_status (bs);
5451       if (bs->stop)
5452         {
5453           bpstat_check_breakpoint_conditions (bs, thread);
5454
5455           if (bs->stop)
5456             {
5457               ++(b->hit_count);
5458               gdb::observers::breakpoint_modified.notify (b);
5459
5460               /* We will stop here.  */
5461               if (b->disposition == disp_disable)
5462                 {
5463                   --(b->enable_count);
5464                   if (b->enable_count <= 0)
5465                     b->enable_state = bp_disabled;
5466                   removed_any = 1;
5467                 }
5468               if (b->silent)
5469                 bs->print = 0;
5470               bs->commands = b->commands;
5471               if (command_line_is_silent (bs->commands
5472                                           ? bs->commands.get () : NULL))
5473                 bs->print = 0;
5474
5475               b->ops->after_condition_true (bs);
5476             }
5477
5478         }
5479
5480       /* Print nothing for this entry if we don't stop or don't
5481          print.  */
5482       if (!bs->stop || !bs->print)
5483         bs->print_it = print_it_noop;
5484     }
5485
5486   /* If we aren't stopping, the value of some hardware watchpoint may
5487      not have changed, but the intermediate memory locations we are
5488      watching may have.  Don't bother if we're stopping; this will get
5489      done later.  */
5490   need_remove_insert = 0;
5491   if (! bpstat_causes_stop (bs_head))
5492     for (bs = bs_head; bs != NULL; bs = bs->next)
5493       if (!bs->stop
5494           && bs->breakpoint_at
5495           && is_hardware_watchpoint (bs->breakpoint_at))
5496         {
5497           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5498
5499           update_watchpoint (w, 0 /* don't reparse.  */);
5500           need_remove_insert = 1;
5501         }
5502
5503   if (need_remove_insert)
5504     update_global_location_list (UGLL_MAY_INSERT);
5505   else if (removed_any)
5506     update_global_location_list (UGLL_DONT_INSERT);
5507
5508   return bs_head;
5509 }
5510
5511 static void
5512 handle_jit_event (void)
5513 {
5514   struct frame_info *frame;
5515   struct gdbarch *gdbarch;
5516
5517   if (debug_infrun)
5518     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5519
5520   /* Switch terminal for any messages produced by
5521      breakpoint_re_set.  */
5522   target_terminal::ours_for_output ();
5523
5524   frame = get_current_frame ();
5525   gdbarch = get_frame_arch (frame);
5526
5527   jit_event_handler (gdbarch);
5528
5529   target_terminal::inferior ();
5530 }
5531
5532 /* Prepare WHAT final decision for infrun.  */
5533
5534 /* Decide what infrun needs to do with this bpstat.  */
5535
5536 struct bpstat_what
5537 bpstat_what (bpstat bs_head)
5538 {
5539   struct bpstat_what retval;
5540   bpstat bs;
5541
5542   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5543   retval.call_dummy = STOP_NONE;
5544   retval.is_longjmp = 0;
5545
5546   for (bs = bs_head; bs != NULL; bs = bs->next)
5547     {
5548       /* Extract this BS's action.  After processing each BS, we check
5549          if its action overrides all we've seem so far.  */
5550       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5551       enum bptype bptype;
5552
5553       if (bs->breakpoint_at == NULL)
5554         {
5555           /* I suspect this can happen if it was a momentary
5556              breakpoint which has since been deleted.  */
5557           bptype = bp_none;
5558         }
5559       else
5560         bptype = bs->breakpoint_at->type;
5561
5562       switch (bptype)
5563         {
5564         case bp_none:
5565           break;
5566         case bp_breakpoint:
5567         case bp_hardware_breakpoint:
5568         case bp_single_step:
5569         case bp_until:
5570         case bp_finish:
5571         case bp_shlib_event:
5572           if (bs->stop)
5573             {
5574               if (bs->print)
5575                 this_action = BPSTAT_WHAT_STOP_NOISY;
5576               else
5577                 this_action = BPSTAT_WHAT_STOP_SILENT;
5578             }
5579           else
5580             this_action = BPSTAT_WHAT_SINGLE;
5581           break;
5582         case bp_watchpoint:
5583         case bp_hardware_watchpoint:
5584         case bp_read_watchpoint:
5585         case bp_access_watchpoint:
5586           if (bs->stop)
5587             {
5588               if (bs->print)
5589                 this_action = BPSTAT_WHAT_STOP_NOISY;
5590               else
5591                 this_action = BPSTAT_WHAT_STOP_SILENT;
5592             }
5593           else
5594             {
5595               /* There was a watchpoint, but we're not stopping.
5596                  This requires no further action.  */
5597             }
5598           break;
5599         case bp_longjmp:
5600         case bp_longjmp_call_dummy:
5601         case bp_exception:
5602           if (bs->stop)
5603             {
5604               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5605               retval.is_longjmp = bptype != bp_exception;
5606             }
5607           else
5608             this_action = BPSTAT_WHAT_SINGLE;
5609           break;
5610         case bp_longjmp_resume:
5611         case bp_exception_resume:
5612           if (bs->stop)
5613             {
5614               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5615               retval.is_longjmp = bptype == bp_longjmp_resume;
5616             }
5617           else
5618             this_action = BPSTAT_WHAT_SINGLE;
5619           break;
5620         case bp_step_resume:
5621           if (bs->stop)
5622             this_action = BPSTAT_WHAT_STEP_RESUME;
5623           else
5624             {
5625               /* It is for the wrong frame.  */
5626               this_action = BPSTAT_WHAT_SINGLE;
5627             }
5628           break;
5629         case bp_hp_step_resume:
5630           if (bs->stop)
5631             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5632           else
5633             {
5634               /* It is for the wrong frame.  */
5635               this_action = BPSTAT_WHAT_SINGLE;
5636             }
5637           break;
5638         case bp_watchpoint_scope:
5639         case bp_thread_event:
5640         case bp_overlay_event:
5641         case bp_longjmp_master:
5642         case bp_std_terminate_master:
5643         case bp_exception_master:
5644           this_action = BPSTAT_WHAT_SINGLE;
5645           break;
5646         case bp_catchpoint:
5647           if (bs->stop)
5648             {
5649               if (bs->print)
5650                 this_action = BPSTAT_WHAT_STOP_NOISY;
5651               else
5652                 this_action = BPSTAT_WHAT_STOP_SILENT;
5653             }
5654           else
5655             {
5656               /* There was a catchpoint, but we're not stopping.
5657                  This requires no further action.  */
5658             }
5659           break;
5660         case bp_jit_event:
5661           this_action = BPSTAT_WHAT_SINGLE;
5662           break;
5663         case bp_call_dummy:
5664           /* Make sure the action is stop (silent or noisy),
5665              so infrun.c pops the dummy frame.  */
5666           retval.call_dummy = STOP_STACK_DUMMY;
5667           this_action = BPSTAT_WHAT_STOP_SILENT;
5668           break;
5669         case bp_std_terminate:
5670           /* Make sure the action is stop (silent or noisy),
5671              so infrun.c pops the dummy frame.  */
5672           retval.call_dummy = STOP_STD_TERMINATE;
5673           this_action = BPSTAT_WHAT_STOP_SILENT;
5674           break;
5675         case bp_tracepoint:
5676         case bp_fast_tracepoint:
5677         case bp_static_tracepoint:
5678           /* Tracepoint hits should not be reported back to GDB, and
5679              if one got through somehow, it should have been filtered
5680              out already.  */
5681           internal_error (__FILE__, __LINE__,
5682                           _("bpstat_what: tracepoint encountered"));
5683           break;
5684         case bp_gnu_ifunc_resolver:
5685           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5686           this_action = BPSTAT_WHAT_SINGLE;
5687           break;
5688         case bp_gnu_ifunc_resolver_return:
5689           /* The breakpoint will be removed, execution will restart from the
5690              PC of the former breakpoint.  */
5691           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5692           break;
5693
5694         case bp_dprintf:
5695           if (bs->stop)
5696             this_action = BPSTAT_WHAT_STOP_SILENT;
5697           else
5698             this_action = BPSTAT_WHAT_SINGLE;
5699           break;
5700
5701         default:
5702           internal_error (__FILE__, __LINE__,
5703                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5704         }
5705
5706       retval.main_action = std::max (retval.main_action, this_action);
5707     }
5708
5709   return retval;
5710 }
5711
5712 void
5713 bpstat_run_callbacks (bpstat bs_head)
5714 {
5715   bpstat bs;
5716
5717   for (bs = bs_head; bs != NULL; bs = bs->next)
5718     {
5719       struct breakpoint *b = bs->breakpoint_at;
5720
5721       if (b == NULL)
5722         continue;
5723       switch (b->type)
5724         {
5725         case bp_jit_event:
5726           handle_jit_event ();
5727           break;
5728         case bp_gnu_ifunc_resolver:
5729           gnu_ifunc_resolver_stop (b);
5730           break;
5731         case bp_gnu_ifunc_resolver_return:
5732           gnu_ifunc_resolver_return_stop (b);
5733           break;
5734         }
5735     }
5736 }
5737
5738 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5739    without hardware support).  This isn't related to a specific bpstat,
5740    just to things like whether watchpoints are set.  */
5741
5742 int
5743 bpstat_should_step (void)
5744 {
5745   struct breakpoint *b;
5746
5747   ALL_BREAKPOINTS (b)
5748     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5749       return 1;
5750   return 0;
5751 }
5752
5753 int
5754 bpstat_causes_stop (bpstat bs)
5755 {
5756   for (; bs != NULL; bs = bs->next)
5757     if (bs->stop)
5758       return 1;
5759
5760   return 0;
5761 }
5762
5763 \f
5764
5765 /* Compute a string of spaces suitable to indent the next line
5766    so it starts at the position corresponding to the table column
5767    named COL_NAME in the currently active table of UIOUT.  */
5768
5769 static char *
5770 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5771 {
5772   static char wrap_indent[80];
5773   int i, total_width, width, align;
5774   const char *text;
5775
5776   total_width = 0;
5777   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
5778     {
5779       if (strcmp (text, col_name) == 0)
5780         {
5781           gdb_assert (total_width < sizeof wrap_indent);
5782           memset (wrap_indent, ' ', total_width);
5783           wrap_indent[total_width] = 0;
5784
5785           return wrap_indent;
5786         }
5787
5788       total_width += width + 1;
5789     }
5790
5791   return NULL;
5792 }
5793
5794 /* Determine if the locations of this breakpoint will have their conditions
5795    evaluated by the target, host or a mix of both.  Returns the following:
5796
5797     "host": Host evals condition.
5798     "host or target": Host or Target evals condition.
5799     "target": Target evals condition.
5800 */
5801
5802 static const char *
5803 bp_condition_evaluator (struct breakpoint *b)
5804 {
5805   struct bp_location *bl;
5806   char host_evals = 0;
5807   char target_evals = 0;
5808
5809   if (!b)
5810     return NULL;
5811
5812   if (!is_breakpoint (b))
5813     return NULL;
5814
5815   if (gdb_evaluates_breakpoint_condition_p ()
5816       || !target_supports_evaluation_of_breakpoint_conditions ())
5817     return condition_evaluation_host;
5818
5819   for (bl = b->loc; bl; bl = bl->next)
5820     {
5821       if (bl->cond_bytecode)
5822         target_evals++;
5823       else
5824         host_evals++;
5825     }
5826
5827   if (host_evals && target_evals)
5828     return condition_evaluation_both;
5829   else if (target_evals)
5830     return condition_evaluation_target;
5831   else
5832     return condition_evaluation_host;
5833 }
5834
5835 /* Determine the breakpoint location's condition evaluator.  This is
5836    similar to bp_condition_evaluator, but for locations.  */
5837
5838 static const char *
5839 bp_location_condition_evaluator (struct bp_location *bl)
5840 {
5841   if (bl && !is_breakpoint (bl->owner))
5842     return NULL;
5843
5844   if (gdb_evaluates_breakpoint_condition_p ()
5845       || !target_supports_evaluation_of_breakpoint_conditions ())
5846     return condition_evaluation_host;
5847
5848   if (bl && bl->cond_bytecode)
5849     return condition_evaluation_target;
5850   else
5851     return condition_evaluation_host;
5852 }
5853
5854 /* Print the LOC location out of the list of B->LOC locations.  */
5855
5856 static void
5857 print_breakpoint_location (struct breakpoint *b,
5858                            struct bp_location *loc)
5859 {
5860   struct ui_out *uiout = current_uiout;
5861
5862   scoped_restore_current_program_space restore_pspace;
5863
5864   if (loc != NULL && loc->shlib_disabled)
5865     loc = NULL;
5866
5867   if (loc != NULL)
5868     set_current_program_space (loc->pspace);
5869
5870   if (b->display_canonical)
5871     uiout->field_string ("what", event_location_to_string (b->location.get ()));
5872   else if (loc && loc->symtab)
5873     {
5874       const struct symbol *sym = loc->symbol;
5875
5876       if (sym)
5877         {
5878           uiout->text ("in ");
5879           uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
5880           uiout->text (" ");
5881           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
5882           uiout->text ("at ");
5883         }
5884       uiout->field_string ("file",
5885                            symtab_to_filename_for_display (loc->symtab));
5886       uiout->text (":");
5887
5888       if (uiout->is_mi_like_p ())
5889         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
5890       
5891       uiout->field_int ("line", loc->line_number);
5892     }
5893   else if (loc)
5894     {
5895       string_file stb;
5896
5897       print_address_symbolic (loc->gdbarch, loc->address, &stb,
5898                               demangle, "");
5899       uiout->field_stream ("at", stb);
5900     }
5901   else
5902     {
5903       uiout->field_string ("pending",
5904                            event_location_to_string (b->location.get ()));
5905       /* If extra_string is available, it could be holding a condition
5906          or dprintf arguments.  In either case, make sure it is printed,
5907          too, but only for non-MI streams.  */
5908       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
5909         {
5910           if (b->type == bp_dprintf)
5911             uiout->text (",");
5912           else
5913             uiout->text (" ");
5914           uiout->text (b->extra_string);
5915         }
5916     }
5917
5918   if (loc && is_breakpoint (b)
5919       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5920       && bp_condition_evaluator (b) == condition_evaluation_both)
5921     {
5922       uiout->text (" (");
5923       uiout->field_string ("evaluated-by",
5924                            bp_location_condition_evaluator (loc));
5925       uiout->text (")");
5926     }
5927 }
5928
5929 static const char *
5930 bptype_string (enum bptype type)
5931 {
5932   struct ep_type_description
5933     {
5934       enum bptype type;
5935       const char *description;
5936     };
5937   static struct ep_type_description bptypes[] =
5938   {
5939     {bp_none, "?deleted?"},
5940     {bp_breakpoint, "breakpoint"},
5941     {bp_hardware_breakpoint, "hw breakpoint"},
5942     {bp_single_step, "sw single-step"},
5943     {bp_until, "until"},
5944     {bp_finish, "finish"},
5945     {bp_watchpoint, "watchpoint"},
5946     {bp_hardware_watchpoint, "hw watchpoint"},
5947     {bp_read_watchpoint, "read watchpoint"},
5948     {bp_access_watchpoint, "acc watchpoint"},
5949     {bp_longjmp, "longjmp"},
5950     {bp_longjmp_resume, "longjmp resume"},
5951     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5952     {bp_exception, "exception"},
5953     {bp_exception_resume, "exception resume"},
5954     {bp_step_resume, "step resume"},
5955     {bp_hp_step_resume, "high-priority step resume"},
5956     {bp_watchpoint_scope, "watchpoint scope"},
5957     {bp_call_dummy, "call dummy"},
5958     {bp_std_terminate, "std::terminate"},
5959     {bp_shlib_event, "shlib events"},
5960     {bp_thread_event, "thread events"},
5961     {bp_overlay_event, "overlay events"},
5962     {bp_longjmp_master, "longjmp master"},
5963     {bp_std_terminate_master, "std::terminate master"},
5964     {bp_exception_master, "exception master"},
5965     {bp_catchpoint, "catchpoint"},
5966     {bp_tracepoint, "tracepoint"},
5967     {bp_fast_tracepoint, "fast tracepoint"},
5968     {bp_static_tracepoint, "static tracepoint"},
5969     {bp_dprintf, "dprintf"},
5970     {bp_jit_event, "jit events"},
5971     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5972     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5973   };
5974
5975   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5976       || ((int) type != bptypes[(int) type].type))
5977     internal_error (__FILE__, __LINE__,
5978                     _("bptypes table does not describe type #%d."),
5979                     (int) type);
5980
5981   return bptypes[(int) type].description;
5982 }
5983
5984 /* For MI, output a field named 'thread-groups' with a list as the value.
5985    For CLI, prefix the list with the string 'inf'. */
5986
5987 static void
5988 output_thread_groups (struct ui_out *uiout,
5989                       const char *field_name,
5990                       const std::vector<int> &inf_nums,
5991                       int mi_only)
5992 {
5993   int is_mi = uiout->is_mi_like_p ();
5994
5995   /* For backward compatibility, don't display inferiors in CLI unless
5996      there are several.  Always display them for MI. */
5997   if (!is_mi && mi_only)
5998     return;
5999
6000   ui_out_emit_list list_emitter (uiout, field_name);
6001
6002   for (size_t i = 0; i < inf_nums.size (); i++)
6003     {
6004       if (is_mi)
6005         {
6006           char mi_group[10];
6007
6008           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf_nums[i]);
6009           uiout->field_string (NULL, mi_group);
6010         }
6011       else
6012         {
6013           if (i == 0)
6014             uiout->text (" inf ");
6015           else
6016             uiout->text (", ");
6017         
6018           uiout->text (plongest (inf_nums[i]));
6019         }
6020     }
6021 }
6022
6023 /* Print B to gdb_stdout.  */
6024
6025 static void
6026 print_one_breakpoint_location (struct breakpoint *b,
6027                                struct bp_location *loc,
6028                                int loc_number,
6029                                struct bp_location **last_loc,
6030                                int allflag)
6031 {
6032   struct command_line *l;
6033   static char bpenables[] = "nynny";
6034
6035   struct ui_out *uiout = current_uiout;
6036   int header_of_multiple = 0;
6037   int part_of_multiple = (loc != NULL);
6038   struct value_print_options opts;
6039
6040   get_user_print_options (&opts);
6041
6042   gdb_assert (!loc || loc_number != 0);
6043   /* See comment in print_one_breakpoint concerning treatment of
6044      breakpoints with single disabled location.  */
6045   if (loc == NULL 
6046       && (b->loc != NULL 
6047           && (b->loc->next != NULL || !b->loc->enabled)))
6048     header_of_multiple = 1;
6049   if (loc == NULL)
6050     loc = b->loc;
6051
6052   annotate_record ();
6053
6054   /* 1 */
6055   annotate_field (0);
6056   if (part_of_multiple)
6057     {
6058       char *formatted;
6059       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6060       uiout->field_string ("number", formatted);
6061       xfree (formatted);
6062     }
6063   else
6064     {
6065       uiout->field_int ("number", b->number);
6066     }
6067
6068   /* 2 */
6069   annotate_field (1);
6070   if (part_of_multiple)
6071     uiout->field_skip ("type");
6072   else
6073     uiout->field_string ("type", bptype_string (b->type));
6074
6075   /* 3 */
6076   annotate_field (2);
6077   if (part_of_multiple)
6078     uiout->field_skip ("disp");
6079   else
6080     uiout->field_string ("disp", bpdisp_text (b->disposition));
6081
6082
6083   /* 4 */
6084   annotate_field (3);
6085   if (part_of_multiple)
6086     uiout->field_string ("enabled", loc->enabled ? "y" : "n");
6087   else
6088     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6089   uiout->spaces (2);
6090
6091   
6092   /* 5 and 6 */
6093   if (b->ops != NULL && b->ops->print_one != NULL)
6094     {
6095       /* Although the print_one can possibly print all locations,
6096          calling it here is not likely to get any nice result.  So,
6097          make sure there's just one location.  */
6098       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6099       b->ops->print_one (b, last_loc);
6100     }
6101   else
6102     switch (b->type)
6103       {
6104       case bp_none:
6105         internal_error (__FILE__, __LINE__,
6106                         _("print_one_breakpoint: bp_none encountered\n"));
6107         break;
6108
6109       case bp_watchpoint:
6110       case bp_hardware_watchpoint:
6111       case bp_read_watchpoint:
6112       case bp_access_watchpoint:
6113         {
6114           struct watchpoint *w = (struct watchpoint *) b;
6115
6116           /* Field 4, the address, is omitted (which makes the columns
6117              not line up too nicely with the headers, but the effect
6118              is relatively readable).  */
6119           if (opts.addressprint)
6120             uiout->field_skip ("addr");
6121           annotate_field (5);
6122           uiout->field_string ("what", w->exp_string);
6123         }
6124         break;
6125
6126       case bp_breakpoint:
6127       case bp_hardware_breakpoint:
6128       case bp_single_step:
6129       case bp_until:
6130       case bp_finish:
6131       case bp_longjmp:
6132       case bp_longjmp_resume:
6133       case bp_longjmp_call_dummy:
6134       case bp_exception:
6135       case bp_exception_resume:
6136       case bp_step_resume:
6137       case bp_hp_step_resume:
6138       case bp_watchpoint_scope:
6139       case bp_call_dummy:
6140       case bp_std_terminate:
6141       case bp_shlib_event:
6142       case bp_thread_event:
6143       case bp_overlay_event:
6144       case bp_longjmp_master:
6145       case bp_std_terminate_master:
6146       case bp_exception_master:
6147       case bp_tracepoint:
6148       case bp_fast_tracepoint:
6149       case bp_static_tracepoint:
6150       case bp_dprintf:
6151       case bp_jit_event:
6152       case bp_gnu_ifunc_resolver:
6153       case bp_gnu_ifunc_resolver_return:
6154         if (opts.addressprint)
6155           {
6156             annotate_field (4);
6157             if (header_of_multiple)
6158               uiout->field_string ("addr", "<MULTIPLE>");
6159             else if (b->loc == NULL || loc->shlib_disabled)
6160               uiout->field_string ("addr", "<PENDING>");
6161             else
6162               uiout->field_core_addr ("addr",
6163                                       loc->gdbarch, loc->address);
6164           }
6165         annotate_field (5);
6166         if (!header_of_multiple)
6167           print_breakpoint_location (b, loc);
6168         if (b->loc)
6169           *last_loc = b->loc;
6170         break;
6171       }
6172
6173
6174   if (loc != NULL && !header_of_multiple)
6175     {
6176       struct inferior *inf;
6177       std::vector<int> inf_nums;
6178       int mi_only = 1;
6179
6180       ALL_INFERIORS (inf)
6181         {
6182           if (inf->pspace == loc->pspace)
6183             inf_nums.push_back (inf->num);
6184         }
6185
6186         /* For backward compatibility, don't display inferiors in CLI unless
6187            there are several.  Always display for MI. */
6188         if (allflag
6189             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6190                 && (number_of_program_spaces () > 1
6191                     || number_of_inferiors () > 1)
6192                 /* LOC is for existing B, it cannot be in
6193                    moribund_locations and thus having NULL OWNER.  */
6194                 && loc->owner->type != bp_catchpoint))
6195         mi_only = 0;
6196       output_thread_groups (uiout, "thread-groups", inf_nums, mi_only);
6197     }
6198
6199   if (!part_of_multiple)
6200     {
6201       if (b->thread != -1)
6202         {
6203           /* FIXME: This seems to be redundant and lost here; see the
6204              "stop only in" line a little further down.  */
6205           uiout->text (" thread ");
6206           uiout->field_int ("thread", b->thread);
6207         }
6208       else if (b->task != 0)
6209         {
6210           uiout->text (" task ");
6211           uiout->field_int ("task", b->task);
6212         }
6213     }
6214
6215   uiout->text ("\n");
6216
6217   if (!part_of_multiple)
6218     b->ops->print_one_detail (b, uiout);
6219
6220   if (part_of_multiple && frame_id_p (b->frame_id))
6221     {
6222       annotate_field (6);
6223       uiout->text ("\tstop only in stack frame at ");
6224       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6225          the frame ID.  */
6226       uiout->field_core_addr ("frame",
6227                               b->gdbarch, b->frame_id.stack_addr);
6228       uiout->text ("\n");
6229     }
6230   
6231   if (!part_of_multiple && b->cond_string)
6232     {
6233       annotate_field (7);
6234       if (is_tracepoint (b))
6235         uiout->text ("\ttrace only if ");
6236       else
6237         uiout->text ("\tstop only if ");
6238       uiout->field_string ("cond", b->cond_string);
6239
6240       /* Print whether the target is doing the breakpoint's condition
6241          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6242       if (is_breakpoint (b)
6243           && breakpoint_condition_evaluation_mode ()
6244           == condition_evaluation_target)
6245         {
6246           uiout->text (" (");
6247           uiout->field_string ("evaluated-by",
6248                                bp_condition_evaluator (b));
6249           uiout->text (" evals)");
6250         }
6251       uiout->text ("\n");
6252     }
6253
6254   if (!part_of_multiple && b->thread != -1)
6255     {
6256       /* FIXME should make an annotation for this.  */
6257       uiout->text ("\tstop only in thread ");
6258       if (uiout->is_mi_like_p ())
6259         uiout->field_int ("thread", b->thread);
6260       else
6261         {
6262           struct thread_info *thr = find_thread_global_id (b->thread);
6263
6264           uiout->field_string ("thread", print_thread_id (thr));
6265         }
6266       uiout->text ("\n");
6267     }
6268   
6269   if (!part_of_multiple)
6270     {
6271       if (b->hit_count)
6272         {
6273           /* FIXME should make an annotation for this.  */
6274           if (is_catchpoint (b))
6275             uiout->text ("\tcatchpoint");
6276           else if (is_tracepoint (b))
6277             uiout->text ("\ttracepoint");
6278           else
6279             uiout->text ("\tbreakpoint");
6280           uiout->text (" already hit ");
6281           uiout->field_int ("times", b->hit_count);
6282           if (b->hit_count == 1)
6283             uiout->text (" time\n");
6284           else
6285             uiout->text (" times\n");
6286         }
6287       else
6288         {
6289           /* Output the count also if it is zero, but only if this is mi.  */
6290           if (uiout->is_mi_like_p ())
6291             uiout->field_int ("times", b->hit_count);
6292         }
6293     }
6294
6295   if (!part_of_multiple && b->ignore_count)
6296     {
6297       annotate_field (8);
6298       uiout->text ("\tignore next ");
6299       uiout->field_int ("ignore", b->ignore_count);
6300       uiout->text (" hits\n");
6301     }
6302
6303   /* Note that an enable count of 1 corresponds to "enable once"
6304      behavior, which is reported by the combination of enablement and
6305      disposition, so we don't need to mention it here.  */
6306   if (!part_of_multiple && b->enable_count > 1)
6307     {
6308       annotate_field (8);
6309       uiout->text ("\tdisable after ");
6310       /* Tweak the wording to clarify that ignore and enable counts
6311          are distinct, and have additive effect.  */
6312       if (b->ignore_count)
6313         uiout->text ("additional ");
6314       else
6315         uiout->text ("next ");
6316       uiout->field_int ("enable", b->enable_count);
6317       uiout->text (" hits\n");
6318     }
6319
6320   if (!part_of_multiple && is_tracepoint (b))
6321     {
6322       struct tracepoint *tp = (struct tracepoint *) b;
6323
6324       if (tp->traceframe_usage)
6325         {
6326           uiout->text ("\ttrace buffer usage ");
6327           uiout->field_int ("traceframe-usage", tp->traceframe_usage);
6328           uiout->text (" bytes\n");
6329         }
6330     }
6331
6332   l = b->commands ? b->commands.get () : NULL;
6333   if (!part_of_multiple && l)
6334     {
6335       annotate_field (9);
6336       ui_out_emit_tuple tuple_emitter (uiout, "script");
6337       print_command_lines (uiout, l, 4);
6338     }
6339
6340   if (is_tracepoint (b))
6341     {
6342       struct tracepoint *t = (struct tracepoint *) b;
6343
6344       if (!part_of_multiple && t->pass_count)
6345         {
6346           annotate_field (10);
6347           uiout->text ("\tpass count ");
6348           uiout->field_int ("pass", t->pass_count);
6349           uiout->text (" \n");
6350         }
6351
6352       /* Don't display it when tracepoint or tracepoint location is
6353          pending.   */
6354       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6355         {
6356           annotate_field (11);
6357
6358           if (uiout->is_mi_like_p ())
6359             uiout->field_string ("installed",
6360                                  loc->inserted ? "y" : "n");
6361           else
6362             {
6363               if (loc->inserted)
6364                 uiout->text ("\t");
6365               else
6366                 uiout->text ("\tnot ");
6367               uiout->text ("installed on target\n");
6368             }
6369         }
6370     }
6371
6372   if (uiout->is_mi_like_p () && !part_of_multiple)
6373     {
6374       if (is_watchpoint (b))
6375         {
6376           struct watchpoint *w = (struct watchpoint *) b;
6377
6378           uiout->field_string ("original-location", w->exp_string);
6379         }
6380       else if (b->location != NULL
6381                && event_location_to_string (b->location.get ()) != NULL)
6382         uiout->field_string ("original-location",
6383                              event_location_to_string (b->location.get ()));
6384     }
6385 }
6386
6387 static void
6388 print_one_breakpoint (struct breakpoint *b,
6389                       struct bp_location **last_loc, 
6390                       int allflag)
6391 {
6392   struct ui_out *uiout = current_uiout;
6393
6394   {
6395     ui_out_emit_tuple tuple_emitter (uiout, "bkpt");
6396
6397     print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6398   }
6399
6400   /* If this breakpoint has custom print function,
6401      it's already printed.  Otherwise, print individual
6402      locations, if any.  */
6403   if (b->ops == NULL || b->ops->print_one == NULL)
6404     {
6405       /* If breakpoint has a single location that is disabled, we
6406          print it as if it had several locations, since otherwise it's
6407          hard to represent "breakpoint enabled, location disabled"
6408          situation.
6409
6410          Note that while hardware watchpoints have several locations
6411          internally, that's not a property exposed to user.  */
6412       if (b->loc 
6413           && !is_hardware_watchpoint (b)
6414           && (b->loc->next || !b->loc->enabled))
6415         {
6416           struct bp_location *loc;
6417           int n = 1;
6418
6419           for (loc = b->loc; loc; loc = loc->next, ++n)
6420             {
6421               ui_out_emit_tuple tuple_emitter (uiout, NULL);
6422               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6423             }
6424         }
6425     }
6426 }
6427
6428 static int
6429 breakpoint_address_bits (struct breakpoint *b)
6430 {
6431   int print_address_bits = 0;
6432   struct bp_location *loc;
6433
6434   /* Software watchpoints that aren't watching memory don't have an
6435      address to print.  */
6436   if (is_no_memory_software_watchpoint (b))
6437     return 0;
6438
6439   for (loc = b->loc; loc; loc = loc->next)
6440     {
6441       int addr_bit;
6442
6443       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6444       if (addr_bit > print_address_bits)
6445         print_address_bits = addr_bit;
6446     }
6447
6448   return print_address_bits;
6449 }
6450
6451 /* See breakpoint.h.  */
6452
6453 void
6454 print_breakpoint (breakpoint *b)
6455 {
6456   struct bp_location *dummy_loc = NULL;
6457   print_one_breakpoint (b, &dummy_loc, 0);
6458 }
6459
6460 /* Return true if this breakpoint was set by the user, false if it is
6461    internal or momentary.  */
6462
6463 int
6464 user_breakpoint_p (struct breakpoint *b)
6465 {
6466   return b->number > 0;
6467 }
6468
6469 /* See breakpoint.h.  */
6470
6471 int
6472 pending_breakpoint_p (struct breakpoint *b)
6473 {
6474   return b->loc == NULL;
6475 }
6476
6477 /* Print information on user settable breakpoint (watchpoint, etc)
6478    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6479    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6480    FILTER is non-NULL, call it on each breakpoint and only include the
6481    ones for which it returns non-zero.  Return the total number of
6482    breakpoints listed.  */
6483
6484 static int
6485 breakpoint_1 (const char *args, int allflag, 
6486               int (*filter) (const struct breakpoint *))
6487 {
6488   struct breakpoint *b;
6489   struct bp_location *last_loc = NULL;
6490   int nr_printable_breakpoints;
6491   struct value_print_options opts;
6492   int print_address_bits = 0;
6493   int print_type_col_width = 14;
6494   struct ui_out *uiout = current_uiout;
6495
6496   get_user_print_options (&opts);
6497
6498   /* Compute the number of rows in the table, as well as the size
6499      required for address fields.  */
6500   nr_printable_breakpoints = 0;
6501   ALL_BREAKPOINTS (b)
6502     {
6503       /* If we have a filter, only list the breakpoints it accepts.  */
6504       if (filter && !filter (b))
6505         continue;
6506
6507       /* If we have an "args" string, it is a list of breakpoints to 
6508          accept.  Skip the others.  */
6509       if (args != NULL && *args != '\0')
6510         {
6511           if (allflag && parse_and_eval_long (args) != b->number)
6512             continue;
6513           if (!allflag && !number_is_in_list (args, b->number))
6514             continue;
6515         }
6516
6517       if (allflag || user_breakpoint_p (b))
6518         {
6519           int addr_bit, type_len;
6520
6521           addr_bit = breakpoint_address_bits (b);
6522           if (addr_bit > print_address_bits)
6523             print_address_bits = addr_bit;
6524
6525           type_len = strlen (bptype_string (b->type));
6526           if (type_len > print_type_col_width)
6527             print_type_col_width = type_len;
6528
6529           nr_printable_breakpoints++;
6530         }
6531     }
6532
6533   {
6534     ui_out_emit_table table_emitter (uiout,
6535                                      opts.addressprint ? 6 : 5,
6536                                      nr_printable_breakpoints,
6537                                      "BreakpointTable");
6538
6539     if (nr_printable_breakpoints > 0)
6540       annotate_breakpoints_headers ();
6541     if (nr_printable_breakpoints > 0)
6542       annotate_field (0);
6543     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6544     if (nr_printable_breakpoints > 0)
6545       annotate_field (1);
6546     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6547     if (nr_printable_breakpoints > 0)
6548       annotate_field (2);
6549     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6550     if (nr_printable_breakpoints > 0)
6551       annotate_field (3);
6552     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6553     if (opts.addressprint)
6554       {
6555         if (nr_printable_breakpoints > 0)
6556           annotate_field (4);
6557         if (print_address_bits <= 32)
6558           uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6559         else
6560           uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6561       }
6562     if (nr_printable_breakpoints > 0)
6563       annotate_field (5);
6564     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6565     uiout->table_body ();
6566     if (nr_printable_breakpoints > 0)
6567       annotate_breakpoints_table ();
6568
6569     ALL_BREAKPOINTS (b)
6570       {
6571         QUIT;
6572         /* If we have a filter, only list the breakpoints it accepts.  */
6573         if (filter && !filter (b))
6574           continue;
6575
6576         /* If we have an "args" string, it is a list of breakpoints to 
6577            accept.  Skip the others.  */
6578
6579         if (args != NULL && *args != '\0')
6580           {
6581             if (allflag)        /* maintenance info breakpoint */
6582               {
6583                 if (parse_and_eval_long (args) != b->number)
6584                   continue;
6585               }
6586             else                /* all others */
6587               {
6588                 if (!number_is_in_list (args, b->number))
6589                   continue;
6590               }
6591           }
6592         /* We only print out user settable breakpoints unless the
6593            allflag is set.  */
6594         if (allflag || user_breakpoint_p (b))
6595           print_one_breakpoint (b, &last_loc, allflag);
6596       }
6597   }
6598
6599   if (nr_printable_breakpoints == 0)
6600     {
6601       /* If there's a filter, let the caller decide how to report
6602          empty list.  */
6603       if (!filter)
6604         {
6605           if (args == NULL || *args == '\0')
6606             uiout->message ("No breakpoints or watchpoints.\n");
6607           else
6608             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6609                             args);
6610         }
6611     }
6612   else
6613     {
6614       if (last_loc && !server_command)
6615         set_next_address (last_loc->gdbarch, last_loc->address);
6616     }
6617
6618   /* FIXME?  Should this be moved up so that it is only called when
6619      there have been breakpoints? */
6620   annotate_breakpoints_table_end ();
6621
6622   return nr_printable_breakpoints;
6623 }
6624
6625 /* Display the value of default-collect in a way that is generally
6626    compatible with the breakpoint list.  */
6627
6628 static void
6629 default_collect_info (void)
6630 {
6631   struct ui_out *uiout = current_uiout;
6632
6633   /* If it has no value (which is frequently the case), say nothing; a
6634      message like "No default-collect." gets in user's face when it's
6635      not wanted.  */
6636   if (!*default_collect)
6637     return;
6638
6639   /* The following phrase lines up nicely with per-tracepoint collect
6640      actions.  */
6641   uiout->text ("default collect ");
6642   uiout->field_string ("default-collect", default_collect);
6643   uiout->text (" \n");
6644 }
6645   
6646 static void
6647 info_breakpoints_command (const char *args, int from_tty)
6648 {
6649   breakpoint_1 (args, 0, NULL);
6650
6651   default_collect_info ();
6652 }
6653
6654 static void
6655 info_watchpoints_command (const char *args, int from_tty)
6656 {
6657   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6658   struct ui_out *uiout = current_uiout;
6659
6660   if (num_printed == 0)
6661     {
6662       if (args == NULL || *args == '\0')
6663         uiout->message ("No watchpoints.\n");
6664       else
6665         uiout->message ("No watchpoint matching '%s'.\n", args);
6666     }
6667 }
6668
6669 static void
6670 maintenance_info_breakpoints (const char *args, int from_tty)
6671 {
6672   breakpoint_1 (args, 1, NULL);
6673
6674   default_collect_info ();
6675 }
6676
6677 static int
6678 breakpoint_has_pc (struct breakpoint *b,
6679                    struct program_space *pspace,
6680                    CORE_ADDR pc, struct obj_section *section)
6681 {
6682   struct bp_location *bl = b->loc;
6683
6684   for (; bl; bl = bl->next)
6685     {
6686       if (bl->pspace == pspace
6687           && bl->address == pc
6688           && (!overlay_debugging || bl->section == section))
6689         return 1;         
6690     }
6691   return 0;
6692 }
6693
6694 /* Print a message describing any user-breakpoints set at PC.  This
6695    concerns with logical breakpoints, so we match program spaces, not
6696    address spaces.  */
6697
6698 static void
6699 describe_other_breakpoints (struct gdbarch *gdbarch,
6700                             struct program_space *pspace, CORE_ADDR pc,
6701                             struct obj_section *section, int thread)
6702 {
6703   int others = 0;
6704   struct breakpoint *b;
6705
6706   ALL_BREAKPOINTS (b)
6707     others += (user_breakpoint_p (b)
6708                && breakpoint_has_pc (b, pspace, pc, section));
6709   if (others > 0)
6710     {
6711       if (others == 1)
6712         printf_filtered (_("Note: breakpoint "));
6713       else /* if (others == ???) */
6714         printf_filtered (_("Note: breakpoints "));
6715       ALL_BREAKPOINTS (b)
6716         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6717           {
6718             others--;
6719             printf_filtered ("%d", b->number);
6720             if (b->thread == -1 && thread != -1)
6721               printf_filtered (" (all threads)");
6722             else if (b->thread != -1)
6723               printf_filtered (" (thread %d)", b->thread);
6724             printf_filtered ("%s%s ",
6725                              ((b->enable_state == bp_disabled
6726                                || b->enable_state == bp_call_disabled)
6727                               ? " (disabled)"
6728                               : ""),
6729                              (others > 1) ? "," 
6730                              : ((others == 1) ? " and" : ""));
6731           }
6732       printf_filtered (_("also set at pc "));
6733       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6734       printf_filtered (".\n");
6735     }
6736 }
6737 \f
6738
6739 /* Return true iff it is meaningful to use the address member of
6740    BPT locations.  For some breakpoint types, the locations' address members
6741    are irrelevant and it makes no sense to attempt to compare them to other
6742    addresses (or use them for any other purpose either).
6743
6744    More specifically, each of the following breakpoint types will
6745    always have a zero valued location address and we don't want to mark
6746    breakpoints of any of these types to be a duplicate of an actual
6747    breakpoint location at address zero:
6748
6749       bp_watchpoint
6750       bp_catchpoint
6751
6752 */
6753
6754 static int
6755 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6756 {
6757   enum bptype type = bpt->type;
6758
6759   return (type != bp_watchpoint && type != bp_catchpoint);
6760 }
6761
6762 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6763    true if LOC1 and LOC2 represent the same watchpoint location.  */
6764
6765 static int
6766 watchpoint_locations_match (struct bp_location *loc1, 
6767                             struct bp_location *loc2)
6768 {
6769   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6770   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6771
6772   /* Both of them must exist.  */
6773   gdb_assert (w1 != NULL);
6774   gdb_assert (w2 != NULL);
6775
6776   /* If the target can evaluate the condition expression in hardware,
6777      then we we need to insert both watchpoints even if they are at
6778      the same place.  Otherwise the watchpoint will only trigger when
6779      the condition of whichever watchpoint was inserted evaluates to
6780      true, not giving a chance for GDB to check the condition of the
6781      other watchpoint.  */
6782   if ((w1->cond_exp
6783        && target_can_accel_watchpoint_condition (loc1->address, 
6784                                                  loc1->length,
6785                                                  loc1->watchpoint_type,
6786                                                  w1->cond_exp.get ()))
6787       || (w2->cond_exp
6788           && target_can_accel_watchpoint_condition (loc2->address, 
6789                                                     loc2->length,
6790                                                     loc2->watchpoint_type,
6791                                                     w2->cond_exp.get ())))
6792     return 0;
6793
6794   /* Note that this checks the owner's type, not the location's.  In
6795      case the target does not support read watchpoints, but does
6796      support access watchpoints, we'll have bp_read_watchpoint
6797      watchpoints with hw_access locations.  Those should be considered
6798      duplicates of hw_read locations.  The hw_read locations will
6799      become hw_access locations later.  */
6800   return (loc1->owner->type == loc2->owner->type
6801           && loc1->pspace->aspace == loc2->pspace->aspace
6802           && loc1->address == loc2->address
6803           && loc1->length == loc2->length);
6804 }
6805
6806 /* See breakpoint.h.  */
6807
6808 int
6809 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
6810                           const address_space *aspace2, CORE_ADDR addr2)
6811 {
6812   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6813            || aspace1 == aspace2)
6814           && addr1 == addr2);
6815 }
6816
6817 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6818    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6819    matches ASPACE2.  On targets that have global breakpoints, the address
6820    space doesn't really matter.  */
6821
6822 static int
6823 breakpoint_address_match_range (const address_space *aspace1,
6824                                 CORE_ADDR addr1,
6825                                 int len1, const address_space *aspace2,
6826                                 CORE_ADDR addr2)
6827 {
6828   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6829            || aspace1 == aspace2)
6830           && addr2 >= addr1 && addr2 < addr1 + len1);
6831 }
6832
6833 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6834    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6835    matches the breakpoint's address space.  On targets that have global
6836    breakpoints, the address space doesn't really matter.  */
6837
6838 static int
6839 breakpoint_location_address_match (struct bp_location *bl,
6840                                    const address_space *aspace,
6841                                    CORE_ADDR addr)
6842 {
6843   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6844                                     aspace, addr)
6845           || (bl->length
6846               && breakpoint_address_match_range (bl->pspace->aspace,
6847                                                  bl->address, bl->length,
6848                                                  aspace, addr)));
6849 }
6850
6851 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
6852    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
6853    match happens only if ASPACE matches the breakpoint's address
6854    space.  On targets that have global breakpoints, the address space
6855    doesn't really matter.  */
6856
6857 static int
6858 breakpoint_location_address_range_overlap (struct bp_location *bl,
6859                                            const address_space *aspace,
6860                                            CORE_ADDR addr, int len)
6861 {
6862   if (gdbarch_has_global_breakpoints (target_gdbarch ())
6863       || bl->pspace->aspace == aspace)
6864     {
6865       int bl_len = bl->length != 0 ? bl->length : 1;
6866
6867       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
6868         return 1;
6869     }
6870   return 0;
6871 }
6872
6873 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6874    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6875    true, otherwise returns false.  */
6876
6877 static int
6878 tracepoint_locations_match (struct bp_location *loc1,
6879                             struct bp_location *loc2)
6880 {
6881   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6882     /* Since tracepoint locations are never duplicated with others', tracepoint
6883        locations at the same address of different tracepoints are regarded as
6884        different locations.  */
6885     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6886   else
6887     return 0;
6888 }
6889
6890 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6891    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6892    represent the same location.  */
6893
6894 static int
6895 breakpoint_locations_match (struct bp_location *loc1, 
6896                             struct bp_location *loc2)
6897 {
6898   int hw_point1, hw_point2;
6899
6900   /* Both of them must not be in moribund_locations.  */
6901   gdb_assert (loc1->owner != NULL);
6902   gdb_assert (loc2->owner != NULL);
6903
6904   hw_point1 = is_hardware_watchpoint (loc1->owner);
6905   hw_point2 = is_hardware_watchpoint (loc2->owner);
6906
6907   if (hw_point1 != hw_point2)
6908     return 0;
6909   else if (hw_point1)
6910     return watchpoint_locations_match (loc1, loc2);
6911   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6912     return tracepoint_locations_match (loc1, loc2);
6913   else
6914     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6915     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6916                                      loc2->pspace->aspace, loc2->address)
6917             && loc1->length == loc2->length);
6918 }
6919
6920 static void
6921 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6922                                int bnum, int have_bnum)
6923 {
6924   /* The longest string possibly returned by hex_string_custom
6925      is 50 chars.  These must be at least that big for safety.  */
6926   char astr1[64];
6927   char astr2[64];
6928
6929   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6930   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6931   if (have_bnum)
6932     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6933              bnum, astr1, astr2);
6934   else
6935     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6936 }
6937
6938 /* Adjust a breakpoint's address to account for architectural
6939    constraints on breakpoint placement.  Return the adjusted address.
6940    Note: Very few targets require this kind of adjustment.  For most
6941    targets, this function is simply the identity function.  */
6942
6943 static CORE_ADDR
6944 adjust_breakpoint_address (struct gdbarch *gdbarch,
6945                            CORE_ADDR bpaddr, enum bptype bptype)
6946 {
6947   if (bptype == bp_watchpoint
6948       || bptype == bp_hardware_watchpoint
6949       || bptype == bp_read_watchpoint
6950       || bptype == bp_access_watchpoint
6951       || bptype == bp_catchpoint)
6952     {
6953       /* Watchpoints and the various bp_catch_* eventpoints should not
6954          have their addresses modified.  */
6955       return bpaddr;
6956     }
6957   else if (bptype == bp_single_step)
6958     {
6959       /* Single-step breakpoints should not have their addresses
6960          modified.  If there's any architectural constrain that
6961          applies to this address, then it should have already been
6962          taken into account when the breakpoint was created in the
6963          first place.  If we didn't do this, stepping through e.g.,
6964          Thumb-2 IT blocks would break.  */
6965       return bpaddr;
6966     }
6967   else
6968     {
6969       CORE_ADDR adjusted_bpaddr = bpaddr;
6970
6971       if (gdbarch_adjust_breakpoint_address_p (gdbarch))
6972         {
6973           /* Some targets have architectural constraints on the placement
6974              of breakpoint instructions.  Obtain the adjusted address.  */
6975           adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6976         }
6977
6978       adjusted_bpaddr = address_significant (gdbarch, adjusted_bpaddr);
6979
6980       /* An adjusted breakpoint address can significantly alter
6981          a user's expectations.  Print a warning if an adjustment
6982          is required.  */
6983       if (adjusted_bpaddr != bpaddr)
6984         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6985
6986       return adjusted_bpaddr;
6987     }
6988 }
6989
6990 bp_location::bp_location (const bp_location_ops *ops, breakpoint *owner)
6991 {
6992   bp_location *loc = this;
6993
6994   gdb_assert (ops != NULL);
6995
6996   loc->ops = ops;
6997   loc->owner = owner;
6998   loc->cond_bytecode = NULL;
6999   loc->shlib_disabled = 0;
7000   loc->enabled = 1;
7001
7002   switch (owner->type)
7003     {
7004     case bp_breakpoint:
7005     case bp_single_step:
7006     case bp_until:
7007     case bp_finish:
7008     case bp_longjmp:
7009     case bp_longjmp_resume:
7010     case bp_longjmp_call_dummy:
7011     case bp_exception:
7012     case bp_exception_resume:
7013     case bp_step_resume:
7014     case bp_hp_step_resume:
7015     case bp_watchpoint_scope:
7016     case bp_call_dummy:
7017     case bp_std_terminate:
7018     case bp_shlib_event:
7019     case bp_thread_event:
7020     case bp_overlay_event:
7021     case bp_jit_event:
7022     case bp_longjmp_master:
7023     case bp_std_terminate_master:
7024     case bp_exception_master:
7025     case bp_gnu_ifunc_resolver:
7026     case bp_gnu_ifunc_resolver_return:
7027     case bp_dprintf:
7028       loc->loc_type = bp_loc_software_breakpoint;
7029       mark_breakpoint_location_modified (loc);
7030       break;
7031     case bp_hardware_breakpoint:
7032       loc->loc_type = bp_loc_hardware_breakpoint;
7033       mark_breakpoint_location_modified (loc);
7034       break;
7035     case bp_hardware_watchpoint:
7036     case bp_read_watchpoint:
7037     case bp_access_watchpoint:
7038       loc->loc_type = bp_loc_hardware_watchpoint;
7039       break;
7040     case bp_watchpoint:
7041     case bp_catchpoint:
7042     case bp_tracepoint:
7043     case bp_fast_tracepoint:
7044     case bp_static_tracepoint:
7045       loc->loc_type = bp_loc_other;
7046       break;
7047     default:
7048       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7049     }
7050
7051   loc->refc = 1;
7052 }
7053
7054 /* Allocate a struct bp_location.  */
7055
7056 static struct bp_location *
7057 allocate_bp_location (struct breakpoint *bpt)
7058 {
7059   return bpt->ops->allocate_location (bpt);
7060 }
7061
7062 static void
7063 free_bp_location (struct bp_location *loc)
7064 {
7065   loc->ops->dtor (loc);
7066   delete loc;
7067 }
7068
7069 /* Increment reference count.  */
7070
7071 static void
7072 incref_bp_location (struct bp_location *bl)
7073 {
7074   ++bl->refc;
7075 }
7076
7077 /* Decrement reference count.  If the reference count reaches 0,
7078    destroy the bp_location.  Sets *BLP to NULL.  */
7079
7080 static void
7081 decref_bp_location (struct bp_location **blp)
7082 {
7083   gdb_assert ((*blp)->refc > 0);
7084
7085   if (--(*blp)->refc == 0)
7086     free_bp_location (*blp);
7087   *blp = NULL;
7088 }
7089
7090 /* Add breakpoint B at the end of the global breakpoint chain.  */
7091
7092 static breakpoint *
7093 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7094 {
7095   struct breakpoint *b1;
7096   struct breakpoint *result = b.get ();
7097
7098   /* Add this breakpoint to the end of the chain so that a list of
7099      breakpoints will come out in order of increasing numbers.  */
7100
7101   b1 = breakpoint_chain;
7102   if (b1 == 0)
7103     breakpoint_chain = b.release ();
7104   else
7105     {
7106       while (b1->next)
7107         b1 = b1->next;
7108       b1->next = b.release ();
7109     }
7110
7111   return result;
7112 }
7113
7114 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7115
7116 static void
7117 init_raw_breakpoint_without_location (struct breakpoint *b,
7118                                       struct gdbarch *gdbarch,
7119                                       enum bptype bptype,
7120                                       const struct breakpoint_ops *ops)
7121 {
7122   gdb_assert (ops != NULL);
7123
7124   b->ops = ops;
7125   b->type = bptype;
7126   b->gdbarch = gdbarch;
7127   b->language = current_language->la_language;
7128   b->input_radix = input_radix;
7129   b->related_breakpoint = b;
7130 }
7131
7132 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7133    that has type BPTYPE and has no locations as yet.  */
7134
7135 static struct breakpoint *
7136 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7137                                      enum bptype bptype,
7138                                      const struct breakpoint_ops *ops)
7139 {
7140   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7141
7142   init_raw_breakpoint_without_location (b.get (), gdbarch, bptype, ops);
7143   return add_to_breakpoint_chain (std::move (b));
7144 }
7145
7146 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7147    resolutions should be made as the user specified the location explicitly
7148    enough.  */
7149
7150 static void
7151 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7152 {
7153   gdb_assert (loc->owner != NULL);
7154
7155   if (loc->owner->type == bp_breakpoint
7156       || loc->owner->type == bp_hardware_breakpoint
7157       || is_tracepoint (loc->owner))
7158     {
7159       const char *function_name;
7160
7161       if (loc->msymbol != NULL
7162           && (MSYMBOL_TYPE (loc->msymbol) == mst_text_gnu_ifunc
7163               || MSYMBOL_TYPE (loc->msymbol) == mst_data_gnu_ifunc)
7164           && !explicit_loc)
7165         {
7166           struct breakpoint *b = loc->owner;
7167
7168           function_name = MSYMBOL_LINKAGE_NAME (loc->msymbol);
7169
7170           if (b->type == bp_breakpoint && b->loc == loc
7171               && loc->next == NULL && b->related_breakpoint == b)
7172             {
7173               /* Create only the whole new breakpoint of this type but do not
7174                  mess more complicated breakpoints with multiple locations.  */
7175               b->type = bp_gnu_ifunc_resolver;
7176               /* Remember the resolver's address for use by the return
7177                  breakpoint.  */
7178               loc->related_address = loc->address;
7179             }
7180         }
7181       else
7182         find_pc_partial_function (loc->address, &function_name, NULL, NULL);
7183
7184       if (function_name)
7185         loc->function_name = xstrdup (function_name);
7186     }
7187 }
7188
7189 /* Attempt to determine architecture of location identified by SAL.  */
7190 struct gdbarch *
7191 get_sal_arch (struct symtab_and_line sal)
7192 {
7193   if (sal.section)
7194     return get_objfile_arch (sal.section->objfile);
7195   if (sal.symtab)
7196     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7197
7198   return NULL;
7199 }
7200
7201 /* Low level routine for partially initializing a breakpoint of type
7202    BPTYPE.  The newly created breakpoint's address, section, source
7203    file name, and line number are provided by SAL.
7204
7205    It is expected that the caller will complete the initialization of
7206    the newly created breakpoint struct as well as output any status
7207    information regarding the creation of a new breakpoint.  */
7208
7209 static void
7210 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7211                      struct symtab_and_line sal, enum bptype bptype,
7212                      const struct breakpoint_ops *ops)
7213 {
7214   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7215
7216   add_location_to_breakpoint (b, &sal);
7217
7218   if (bptype != bp_catchpoint)
7219     gdb_assert (sal.pspace != NULL);
7220
7221   /* Store the program space that was used to set the breakpoint,
7222      except for ordinary breakpoints, which are independent of the
7223      program space.  */
7224   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7225     b->pspace = sal.pspace;
7226 }
7227
7228 /* set_raw_breakpoint is a low level routine for allocating and
7229    partially initializing a breakpoint of type BPTYPE.  The newly
7230    created breakpoint's address, section, source file name, and line
7231    number are provided by SAL.  The newly created and partially
7232    initialized breakpoint is added to the breakpoint chain and
7233    is also returned as the value of this function.
7234
7235    It is expected that the caller will complete the initialization of
7236    the newly created breakpoint struct as well as output any status
7237    information regarding the creation of a new breakpoint.  In
7238    particular, set_raw_breakpoint does NOT set the breakpoint
7239    number!  Care should be taken to not allow an error to occur
7240    prior to completing the initialization of the breakpoint.  If this
7241    should happen, a bogus breakpoint will be left on the chain.  */
7242
7243 struct breakpoint *
7244 set_raw_breakpoint (struct gdbarch *gdbarch,
7245                     struct symtab_and_line sal, enum bptype bptype,
7246                     const struct breakpoint_ops *ops)
7247 {
7248   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7249
7250   init_raw_breakpoint (b.get (), gdbarch, sal, bptype, ops);
7251   return add_to_breakpoint_chain (std::move (b));
7252 }
7253
7254 /* Call this routine when stepping and nexting to enable a breakpoint
7255    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7256    initiated the operation.  */
7257
7258 void
7259 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7260 {
7261   struct breakpoint *b, *b_tmp;
7262   int thread = tp->global_num;
7263
7264   /* To avoid having to rescan all objfile symbols at every step,
7265      we maintain a list of continually-inserted but always disabled
7266      longjmp "master" breakpoints.  Here, we simply create momentary
7267      clones of those and enable them for the requested thread.  */
7268   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7269     if (b->pspace == current_program_space
7270         && (b->type == bp_longjmp_master
7271             || b->type == bp_exception_master))
7272       {
7273         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7274         struct breakpoint *clone;
7275
7276         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7277            after their removal.  */
7278         clone = momentary_breakpoint_from_master (b, type,
7279                                                   &momentary_breakpoint_ops, 1);
7280         clone->thread = thread;
7281       }
7282
7283   tp->initiating_frame = frame;
7284 }
7285
7286 /* Delete all longjmp breakpoints from THREAD.  */
7287 void
7288 delete_longjmp_breakpoint (int thread)
7289 {
7290   struct breakpoint *b, *b_tmp;
7291
7292   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7293     if (b->type == bp_longjmp || b->type == bp_exception)
7294       {
7295         if (b->thread == thread)
7296           delete_breakpoint (b);
7297       }
7298 }
7299
7300 void
7301 delete_longjmp_breakpoint_at_next_stop (int thread)
7302 {
7303   struct breakpoint *b, *b_tmp;
7304
7305   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7306     if (b->type == bp_longjmp || b->type == bp_exception)
7307       {
7308         if (b->thread == thread)
7309           b->disposition = disp_del_at_next_stop;
7310       }
7311 }
7312
7313 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7314    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7315    pointer to any of them.  Return NULL if this system cannot place longjmp
7316    breakpoints.  */
7317
7318 struct breakpoint *
7319 set_longjmp_breakpoint_for_call_dummy (void)
7320 {
7321   struct breakpoint *b, *retval = NULL;
7322
7323   ALL_BREAKPOINTS (b)
7324     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7325       {
7326         struct breakpoint *new_b;
7327
7328         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7329                                                   &momentary_breakpoint_ops,
7330                                                   1);
7331         new_b->thread = inferior_thread ()->global_num;
7332
7333         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7334
7335         gdb_assert (new_b->related_breakpoint == new_b);
7336         if (retval == NULL)
7337           retval = new_b;
7338         new_b->related_breakpoint = retval;
7339         while (retval->related_breakpoint != new_b->related_breakpoint)
7340           retval = retval->related_breakpoint;
7341         retval->related_breakpoint = new_b;
7342       }
7343
7344   return retval;
7345 }
7346
7347 /* Verify all existing dummy frames and their associated breakpoints for
7348    TP.  Remove those which can no longer be found in the current frame
7349    stack.
7350
7351    You should call this function only at places where it is safe to currently
7352    unwind the whole stack.  Failed stack unwind would discard live dummy
7353    frames.  */
7354
7355 void
7356 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7357 {
7358   struct breakpoint *b, *b_tmp;
7359
7360   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7361     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7362       {
7363         struct breakpoint *dummy_b = b->related_breakpoint;
7364
7365         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7366           dummy_b = dummy_b->related_breakpoint;
7367         if (dummy_b->type != bp_call_dummy
7368             || frame_find_by_id (dummy_b->frame_id) != NULL)
7369           continue;
7370         
7371         dummy_frame_discard (dummy_b->frame_id, tp);
7372
7373         while (b->related_breakpoint != b)
7374           {
7375             if (b_tmp == b->related_breakpoint)
7376               b_tmp = b->related_breakpoint->next;
7377             delete_breakpoint (b->related_breakpoint);
7378           }
7379         delete_breakpoint (b);
7380       }
7381 }
7382
7383 void
7384 enable_overlay_breakpoints (void)
7385 {
7386   struct breakpoint *b;
7387
7388   ALL_BREAKPOINTS (b)
7389     if (b->type == bp_overlay_event)
7390     {
7391       b->enable_state = bp_enabled;
7392       update_global_location_list (UGLL_MAY_INSERT);
7393       overlay_events_enabled = 1;
7394     }
7395 }
7396
7397 void
7398 disable_overlay_breakpoints (void)
7399 {
7400   struct breakpoint *b;
7401
7402   ALL_BREAKPOINTS (b)
7403     if (b->type == bp_overlay_event)
7404     {
7405       b->enable_state = bp_disabled;
7406       update_global_location_list (UGLL_DONT_INSERT);
7407       overlay_events_enabled = 0;
7408     }
7409 }
7410
7411 /* Set an active std::terminate breakpoint for each std::terminate
7412    master breakpoint.  */
7413 void
7414 set_std_terminate_breakpoint (void)
7415 {
7416   struct breakpoint *b, *b_tmp;
7417
7418   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7419     if (b->pspace == current_program_space
7420         && b->type == bp_std_terminate_master)
7421       {
7422         momentary_breakpoint_from_master (b, bp_std_terminate,
7423                                           &momentary_breakpoint_ops, 1);
7424       }
7425 }
7426
7427 /* Delete all the std::terminate breakpoints.  */
7428 void
7429 delete_std_terminate_breakpoint (void)
7430 {
7431   struct breakpoint *b, *b_tmp;
7432
7433   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7434     if (b->type == bp_std_terminate)
7435       delete_breakpoint (b);
7436 }
7437
7438 struct breakpoint *
7439 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7440 {
7441   struct breakpoint *b;
7442
7443   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7444                                   &internal_breakpoint_ops);
7445
7446   b->enable_state = bp_enabled;
7447   /* location has to be used or breakpoint_re_set will delete me.  */
7448   b->location = new_address_location (b->loc->address, NULL, 0);
7449
7450   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7451
7452   return b;
7453 }
7454
7455 struct lang_and_radix
7456   {
7457     enum language lang;
7458     int radix;
7459   };
7460
7461 /* Create a breakpoint for JIT code registration and unregistration.  */
7462
7463 struct breakpoint *
7464 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7465 {
7466   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7467                                      &internal_breakpoint_ops);
7468 }
7469
7470 /* Remove JIT code registration and unregistration breakpoint(s).  */
7471
7472 void
7473 remove_jit_event_breakpoints (void)
7474 {
7475   struct breakpoint *b, *b_tmp;
7476
7477   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7478     if (b->type == bp_jit_event
7479         && b->loc->pspace == current_program_space)
7480       delete_breakpoint (b);
7481 }
7482
7483 void
7484 remove_solib_event_breakpoints (void)
7485 {
7486   struct breakpoint *b, *b_tmp;
7487
7488   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7489     if (b->type == bp_shlib_event
7490         && b->loc->pspace == current_program_space)
7491       delete_breakpoint (b);
7492 }
7493
7494 /* See breakpoint.h.  */
7495
7496 void
7497 remove_solib_event_breakpoints_at_next_stop (void)
7498 {
7499   struct breakpoint *b, *b_tmp;
7500
7501   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7502     if (b->type == bp_shlib_event
7503         && b->loc->pspace == current_program_space)
7504       b->disposition = disp_del_at_next_stop;
7505 }
7506
7507 /* Helper for create_solib_event_breakpoint /
7508    create_and_insert_solib_event_breakpoint.  Allows specifying which
7509    INSERT_MODE to pass through to update_global_location_list.  */
7510
7511 static struct breakpoint *
7512 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7513                                  enum ugll_insert_mode insert_mode)
7514 {
7515   struct breakpoint *b;
7516
7517   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7518                                   &internal_breakpoint_ops);
7519   update_global_location_list_nothrow (insert_mode);
7520   return b;
7521 }
7522
7523 struct breakpoint *
7524 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7525 {
7526   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7527 }
7528
7529 /* See breakpoint.h.  */
7530
7531 struct breakpoint *
7532 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7533 {
7534   struct breakpoint *b;
7535
7536   /* Explicitly tell update_global_location_list to insert
7537      locations.  */
7538   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7539   if (!b->loc->inserted)
7540     {
7541       delete_breakpoint (b);
7542       return NULL;
7543     }
7544   return b;
7545 }
7546
7547 /* Disable any breakpoints that are on code in shared libraries.  Only
7548    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7549
7550 void
7551 disable_breakpoints_in_shlibs (void)
7552 {
7553   struct bp_location *loc, **locp_tmp;
7554
7555   ALL_BP_LOCATIONS (loc, locp_tmp)
7556   {
7557     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7558     struct breakpoint *b = loc->owner;
7559
7560     /* We apply the check to all breakpoints, including disabled for
7561        those with loc->duplicate set.  This is so that when breakpoint
7562        becomes enabled, or the duplicate is removed, gdb will try to
7563        insert all breakpoints.  If we don't set shlib_disabled here,
7564        we'll try to insert those breakpoints and fail.  */
7565     if (((b->type == bp_breakpoint)
7566          || (b->type == bp_jit_event)
7567          || (b->type == bp_hardware_breakpoint)
7568          || (is_tracepoint (b)))
7569         && loc->pspace == current_program_space
7570         && !loc->shlib_disabled
7571         && solib_name_from_address (loc->pspace, loc->address)
7572         )
7573       {
7574         loc->shlib_disabled = 1;
7575       }
7576   }
7577 }
7578
7579 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7580    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7581    disabled ones can just stay disabled.  */
7582
7583 static void
7584 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7585 {
7586   struct bp_location *loc, **locp_tmp;
7587   int disabled_shlib_breaks = 0;
7588
7589   ALL_BP_LOCATIONS (loc, locp_tmp)
7590   {
7591     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7592     struct breakpoint *b = loc->owner;
7593
7594     if (solib->pspace == loc->pspace
7595         && !loc->shlib_disabled
7596         && (((b->type == bp_breakpoint
7597               || b->type == bp_jit_event
7598               || b->type == bp_hardware_breakpoint)
7599              && (loc->loc_type == bp_loc_hardware_breakpoint
7600                  || loc->loc_type == bp_loc_software_breakpoint))
7601             || is_tracepoint (b))
7602         && solib_contains_address_p (solib, loc->address))
7603       {
7604         loc->shlib_disabled = 1;
7605         /* At this point, we cannot rely on remove_breakpoint
7606            succeeding so we must mark the breakpoint as not inserted
7607            to prevent future errors occurring in remove_breakpoints.  */
7608         loc->inserted = 0;
7609
7610         /* This may cause duplicate notifications for the same breakpoint.  */
7611         gdb::observers::breakpoint_modified.notify (b);
7612
7613         if (!disabled_shlib_breaks)
7614           {
7615             target_terminal::ours_for_output ();
7616             warning (_("Temporarily disabling breakpoints "
7617                        "for unloaded shared library \"%s\""),
7618                      solib->so_name);
7619           }
7620         disabled_shlib_breaks = 1;
7621       }
7622   }
7623 }
7624
7625 /* Disable any breakpoints and tracepoints in OBJFILE upon
7626    notification of free_objfile.  Only apply to enabled breakpoints,
7627    disabled ones can just stay disabled.  */
7628
7629 static void
7630 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7631 {
7632   struct breakpoint *b;
7633
7634   if (objfile == NULL)
7635     return;
7636
7637   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7638      managed by the user with add-symbol-file/remove-symbol-file.
7639      Similarly to how breakpoints in shared libraries are handled in
7640      response to "nosharedlibrary", mark breakpoints in such modules
7641      shlib_disabled so they end up uninserted on the next global
7642      location list update.  Shared libraries not loaded by the user
7643      aren't handled here -- they're already handled in
7644      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7645      solib_unloaded observer.  We skip objfiles that are not
7646      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7647      main objfile).  */
7648   if ((objfile->flags & OBJF_SHARED) == 0
7649       || (objfile->flags & OBJF_USERLOADED) == 0)
7650     return;
7651
7652   ALL_BREAKPOINTS (b)
7653     {
7654       struct bp_location *loc;
7655       int bp_modified = 0;
7656
7657       if (!is_breakpoint (b) && !is_tracepoint (b))
7658         continue;
7659
7660       for (loc = b->loc; loc != NULL; loc = loc->next)
7661         {
7662           CORE_ADDR loc_addr = loc->address;
7663
7664           if (loc->loc_type != bp_loc_hardware_breakpoint
7665               && loc->loc_type != bp_loc_software_breakpoint)
7666             continue;
7667
7668           if (loc->shlib_disabled != 0)
7669             continue;
7670
7671           if (objfile->pspace != loc->pspace)
7672             continue;
7673
7674           if (loc->loc_type != bp_loc_hardware_breakpoint
7675               && loc->loc_type != bp_loc_software_breakpoint)
7676             continue;
7677
7678           if (is_addr_in_objfile (loc_addr, objfile))
7679             {
7680               loc->shlib_disabled = 1;
7681               /* At this point, we don't know whether the object was
7682                  unmapped from the inferior or not, so leave the
7683                  inserted flag alone.  We'll handle failure to
7684                  uninsert quietly, in case the object was indeed
7685                  unmapped.  */
7686
7687               mark_breakpoint_location_modified (loc);
7688
7689               bp_modified = 1;
7690             }
7691         }
7692
7693       if (bp_modified)
7694         gdb::observers::breakpoint_modified.notify (b);
7695     }
7696 }
7697
7698 /* FORK & VFORK catchpoints.  */
7699
7700 /* An instance of this type is used to represent a fork or vfork
7701    catchpoint.  A breakpoint is really of this type iff its ops pointer points
7702    to CATCH_FORK_BREAKPOINT_OPS.  */
7703
7704 struct fork_catchpoint : public breakpoint
7705 {
7706   /* Process id of a child process whose forking triggered this
7707      catchpoint.  This field is only valid immediately after this
7708      catchpoint has triggered.  */
7709   ptid_t forked_inferior_pid;
7710 };
7711
7712 /* Implement the "insert" breakpoint_ops method for fork
7713    catchpoints.  */
7714
7715 static int
7716 insert_catch_fork (struct bp_location *bl)
7717 {
7718   return target_insert_fork_catchpoint (inferior_ptid.pid ());
7719 }
7720
7721 /* Implement the "remove" breakpoint_ops method for fork
7722    catchpoints.  */
7723
7724 static int
7725 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
7726 {
7727   return target_remove_fork_catchpoint (inferior_ptid.pid ());
7728 }
7729
7730 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7731    catchpoints.  */
7732
7733 static int
7734 breakpoint_hit_catch_fork (const struct bp_location *bl,
7735                            const address_space *aspace, CORE_ADDR bp_addr,
7736                            const struct target_waitstatus *ws)
7737 {
7738   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7739
7740   if (ws->kind != TARGET_WAITKIND_FORKED)
7741     return 0;
7742
7743   c->forked_inferior_pid = ws->value.related_pid;
7744   return 1;
7745 }
7746
7747 /* Implement the "print_it" breakpoint_ops method for fork
7748    catchpoints.  */
7749
7750 static enum print_stop_action
7751 print_it_catch_fork (bpstat bs)
7752 {
7753   struct ui_out *uiout = current_uiout;
7754   struct breakpoint *b = bs->breakpoint_at;
7755   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7756
7757   annotate_catchpoint (b->number);
7758   maybe_print_thread_hit_breakpoint (uiout);
7759   if (b->disposition == disp_del)
7760     uiout->text ("Temporary catchpoint ");
7761   else
7762     uiout->text ("Catchpoint ");
7763   if (uiout->is_mi_like_p ())
7764     {
7765       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
7766       uiout->field_string ("disp", bpdisp_text (b->disposition));
7767     }
7768   uiout->field_int ("bkptno", b->number);
7769   uiout->text (" (forked process ");
7770   uiout->field_int ("newpid", c->forked_inferior_pid.pid ());
7771   uiout->text ("), ");
7772   return PRINT_SRC_AND_LOC;
7773 }
7774
7775 /* Implement the "print_one" breakpoint_ops method for fork
7776    catchpoints.  */
7777
7778 static void
7779 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7780 {
7781   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7782   struct value_print_options opts;
7783   struct ui_out *uiout = current_uiout;
7784
7785   get_user_print_options (&opts);
7786
7787   /* Field 4, the address, is omitted (which makes the columns not
7788      line up too nicely with the headers, but the effect is relatively
7789      readable).  */
7790   if (opts.addressprint)
7791     uiout->field_skip ("addr");
7792   annotate_field (5);
7793   uiout->text ("fork");
7794   if (c->forked_inferior_pid != null_ptid)
7795     {
7796       uiout->text (", process ");
7797       uiout->field_int ("what", c->forked_inferior_pid.pid ());
7798       uiout->spaces (1);
7799     }
7800
7801   if (uiout->is_mi_like_p ())
7802     uiout->field_string ("catch-type", "fork");
7803 }
7804
7805 /* Implement the "print_mention" breakpoint_ops method for fork
7806    catchpoints.  */
7807
7808 static void
7809 print_mention_catch_fork (struct breakpoint *b)
7810 {
7811   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7812 }
7813
7814 /* Implement the "print_recreate" breakpoint_ops method for fork
7815    catchpoints.  */
7816
7817 static void
7818 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7819 {
7820   fprintf_unfiltered (fp, "catch fork");
7821   print_recreate_thread (b, fp);
7822 }
7823
7824 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7825
7826 static struct breakpoint_ops catch_fork_breakpoint_ops;
7827
7828 /* Implement the "insert" breakpoint_ops method for vfork
7829    catchpoints.  */
7830
7831 static int
7832 insert_catch_vfork (struct bp_location *bl)
7833 {
7834   return target_insert_vfork_catchpoint (inferior_ptid.pid ());
7835 }
7836
7837 /* Implement the "remove" breakpoint_ops method for vfork
7838    catchpoints.  */
7839
7840 static int
7841 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
7842 {
7843   return target_remove_vfork_catchpoint (inferior_ptid.pid ());
7844 }
7845
7846 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7847    catchpoints.  */
7848
7849 static int
7850 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7851                             const address_space *aspace, CORE_ADDR bp_addr,
7852                             const struct target_waitstatus *ws)
7853 {
7854   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7855
7856   if (ws->kind != TARGET_WAITKIND_VFORKED)
7857     return 0;
7858
7859   c->forked_inferior_pid = ws->value.related_pid;
7860   return 1;
7861 }
7862
7863 /* Implement the "print_it" breakpoint_ops method for vfork
7864    catchpoints.  */
7865
7866 static enum print_stop_action
7867 print_it_catch_vfork (bpstat bs)
7868 {
7869   struct ui_out *uiout = current_uiout;
7870   struct breakpoint *b = bs->breakpoint_at;
7871   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7872
7873   annotate_catchpoint (b->number);
7874   maybe_print_thread_hit_breakpoint (uiout);
7875   if (b->disposition == disp_del)
7876     uiout->text ("Temporary catchpoint ");
7877   else
7878     uiout->text ("Catchpoint ");
7879   if (uiout->is_mi_like_p ())
7880     {
7881       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
7882       uiout->field_string ("disp", bpdisp_text (b->disposition));
7883     }
7884   uiout->field_int ("bkptno", b->number);
7885   uiout->text (" (vforked process ");
7886   uiout->field_int ("newpid", c->forked_inferior_pid.pid ());
7887   uiout->text ("), ");
7888   return PRINT_SRC_AND_LOC;
7889 }
7890
7891 /* Implement the "print_one" breakpoint_ops method for vfork
7892    catchpoints.  */
7893
7894 static void
7895 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7896 {
7897   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7898   struct value_print_options opts;
7899   struct ui_out *uiout = current_uiout;
7900
7901   get_user_print_options (&opts);
7902   /* Field 4, the address, is omitted (which makes the columns not
7903      line up too nicely with the headers, but the effect is relatively
7904      readable).  */
7905   if (opts.addressprint)
7906     uiout->field_skip ("addr");
7907   annotate_field (5);
7908   uiout->text ("vfork");
7909   if (c->forked_inferior_pid != null_ptid)
7910     {
7911       uiout->text (", process ");
7912       uiout->field_int ("what", c->forked_inferior_pid.pid ());
7913       uiout->spaces (1);
7914     }
7915
7916   if (uiout->is_mi_like_p ())
7917     uiout->field_string ("catch-type", "vfork");
7918 }
7919
7920 /* Implement the "print_mention" breakpoint_ops method for vfork
7921    catchpoints.  */
7922
7923 static void
7924 print_mention_catch_vfork (struct breakpoint *b)
7925 {
7926   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7927 }
7928
7929 /* Implement the "print_recreate" breakpoint_ops method for vfork
7930    catchpoints.  */
7931
7932 static void
7933 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7934 {
7935   fprintf_unfiltered (fp, "catch vfork");
7936   print_recreate_thread (b, fp);
7937 }
7938
7939 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7940
7941 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7942
7943 /* An instance of this type is used to represent an solib catchpoint.
7944    A breakpoint is really of this type iff its ops pointer points to
7945    CATCH_SOLIB_BREAKPOINT_OPS.  */
7946
7947 struct solib_catchpoint : public breakpoint
7948 {
7949   ~solib_catchpoint () override;
7950
7951   /* True for "catch load", false for "catch unload".  */
7952   unsigned char is_load;
7953
7954   /* Regular expression to match, if any.  COMPILED is only valid when
7955      REGEX is non-NULL.  */
7956   char *regex;
7957   std::unique_ptr<compiled_regex> compiled;
7958 };
7959
7960 solib_catchpoint::~solib_catchpoint ()
7961 {
7962   xfree (this->regex);
7963 }
7964
7965 static int
7966 insert_catch_solib (struct bp_location *ignore)
7967 {
7968   return 0;
7969 }
7970
7971 static int
7972 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
7973 {
7974   return 0;
7975 }
7976
7977 static int
7978 breakpoint_hit_catch_solib (const struct bp_location *bl,
7979                             const address_space *aspace,
7980                             CORE_ADDR bp_addr,
7981                             const struct target_waitstatus *ws)
7982 {
7983   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7984   struct breakpoint *other;
7985
7986   if (ws->kind == TARGET_WAITKIND_LOADED)
7987     return 1;
7988
7989   ALL_BREAKPOINTS (other)
7990   {
7991     struct bp_location *other_bl;
7992
7993     if (other == bl->owner)
7994       continue;
7995
7996     if (other->type != bp_shlib_event)
7997       continue;
7998
7999     if (self->pspace != NULL && other->pspace != self->pspace)
8000       continue;
8001
8002     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8003       {
8004         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8005           return 1;
8006       }
8007   }
8008
8009   return 0;
8010 }
8011
8012 static void
8013 check_status_catch_solib (struct bpstats *bs)
8014 {
8015   struct solib_catchpoint *self
8016     = (struct solib_catchpoint *) bs->breakpoint_at;
8017
8018   if (self->is_load)
8019     {
8020       for (so_list *iter : current_program_space->added_solibs)
8021         {
8022           if (!self->regex
8023               || self->compiled->exec (iter->so_name, 0, NULL, 0) == 0)
8024             return;
8025         }
8026     }
8027   else
8028     {
8029       for (const std::string &iter : current_program_space->deleted_solibs)
8030         {
8031           if (!self->regex
8032               || self->compiled->exec (iter.c_str (), 0, NULL, 0) == 0)
8033             return;
8034         }
8035     }
8036
8037   bs->stop = 0;
8038   bs->print_it = print_it_noop;
8039 }
8040
8041 static enum print_stop_action
8042 print_it_catch_solib (bpstat bs)
8043 {
8044   struct breakpoint *b = bs->breakpoint_at;
8045   struct ui_out *uiout = current_uiout;
8046
8047   annotate_catchpoint (b->number);
8048   maybe_print_thread_hit_breakpoint (uiout);
8049   if (b->disposition == disp_del)
8050     uiout->text ("Temporary catchpoint ");
8051   else
8052     uiout->text ("Catchpoint ");
8053   uiout->field_int ("bkptno", b->number);
8054   uiout->text ("\n");
8055   if (uiout->is_mi_like_p ())
8056     uiout->field_string ("disp", bpdisp_text (b->disposition));
8057   print_solib_event (1);
8058   return PRINT_SRC_AND_LOC;
8059 }
8060
8061 static void
8062 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8063 {
8064   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8065   struct value_print_options opts;
8066   struct ui_out *uiout = current_uiout;
8067   char *msg;
8068
8069   get_user_print_options (&opts);
8070   /* Field 4, the address, is omitted (which makes the columns not
8071      line up too nicely with the headers, but the effect is relatively
8072      readable).  */
8073   if (opts.addressprint)
8074     {
8075       annotate_field (4);
8076       uiout->field_skip ("addr");
8077     }
8078
8079   annotate_field (5);
8080   if (self->is_load)
8081     {
8082       if (self->regex)
8083         msg = xstrprintf (_("load of library matching %s"), self->regex);
8084       else
8085         msg = xstrdup (_("load of library"));
8086     }
8087   else
8088     {
8089       if (self->regex)
8090         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8091       else
8092         msg = xstrdup (_("unload of library"));
8093     }
8094   uiout->field_string ("what", msg);
8095   xfree (msg);
8096
8097   if (uiout->is_mi_like_p ())
8098     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8099 }
8100
8101 static void
8102 print_mention_catch_solib (struct breakpoint *b)
8103 {
8104   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8105
8106   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8107                    self->is_load ? "load" : "unload");
8108 }
8109
8110 static void
8111 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8112 {
8113   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8114
8115   fprintf_unfiltered (fp, "%s %s",
8116                       b->disposition == disp_del ? "tcatch" : "catch",
8117                       self->is_load ? "load" : "unload");
8118   if (self->regex)
8119     fprintf_unfiltered (fp, " %s", self->regex);
8120   fprintf_unfiltered (fp, "\n");
8121 }
8122
8123 static struct breakpoint_ops catch_solib_breakpoint_ops;
8124
8125 /* Shared helper function (MI and CLI) for creating and installing
8126    a shared object event catchpoint.  If IS_LOAD is non-zero then
8127    the events to be caught are load events, otherwise they are
8128    unload events.  If IS_TEMP is non-zero the catchpoint is a
8129    temporary one.  If ENABLED is non-zero the catchpoint is
8130    created in an enabled state.  */
8131
8132 void
8133 add_solib_catchpoint (const char *arg, int is_load, int is_temp, int enabled)
8134 {
8135   struct gdbarch *gdbarch = get_current_arch ();
8136
8137   if (!arg)
8138     arg = "";
8139   arg = skip_spaces (arg);
8140
8141   std::unique_ptr<solib_catchpoint> c (new solib_catchpoint ());
8142
8143   if (*arg != '\0')
8144     {
8145       c->compiled.reset (new compiled_regex (arg, REG_NOSUB,
8146                                              _("Invalid regexp")));
8147       c->regex = xstrdup (arg);
8148     }
8149
8150   c->is_load = is_load;
8151   init_catchpoint (c.get (), gdbarch, is_temp, NULL,
8152                    &catch_solib_breakpoint_ops);
8153
8154   c->enable_state = enabled ? bp_enabled : bp_disabled;
8155
8156   install_breakpoint (0, std::move (c), 1);
8157 }
8158
8159 /* A helper function that does all the work for "catch load" and
8160    "catch unload".  */
8161
8162 static void
8163 catch_load_or_unload (const char *arg, int from_tty, int is_load,
8164                       struct cmd_list_element *command)
8165 {
8166   int tempflag;
8167   const int enabled = 1;
8168
8169   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8170
8171   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8172 }
8173
8174 static void
8175 catch_load_command_1 (const char *arg, int from_tty,
8176                       struct cmd_list_element *command)
8177 {
8178   catch_load_or_unload (arg, from_tty, 1, command);
8179 }
8180
8181 static void
8182 catch_unload_command_1 (const char *arg, int from_tty,
8183                         struct cmd_list_element *command)
8184 {
8185   catch_load_or_unload (arg, from_tty, 0, command);
8186 }
8187
8188 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8189    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8190    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8191    the breakpoint_ops structure associated to the catchpoint.  */
8192
8193 void
8194 init_catchpoint (struct breakpoint *b,
8195                  struct gdbarch *gdbarch, int tempflag,
8196                  const char *cond_string,
8197                  const struct breakpoint_ops *ops)
8198 {
8199   symtab_and_line sal;
8200   sal.pspace = current_program_space;
8201
8202   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8203
8204   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8205   b->disposition = tempflag ? disp_del : disp_donttouch;
8206 }
8207
8208 void
8209 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8210 {
8211   breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8212   set_breakpoint_number (internal, b);
8213   if (is_tracepoint (b))
8214     set_tracepoint_count (breakpoint_count);
8215   if (!internal)
8216     mention (b);
8217   gdb::observers::breakpoint_created.notify (b);
8218
8219   if (update_gll)
8220     update_global_location_list (UGLL_MAY_INSERT);
8221 }
8222
8223 static void
8224 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8225                                     int tempflag, const char *cond_string,
8226                                     const struct breakpoint_ops *ops)
8227 {
8228   std::unique_ptr<fork_catchpoint> c (new fork_catchpoint ());
8229
8230   init_catchpoint (c.get (), gdbarch, tempflag, cond_string, ops);
8231
8232   c->forked_inferior_pid = null_ptid;
8233
8234   install_breakpoint (0, std::move (c), 1);
8235 }
8236
8237 /* Exec catchpoints.  */
8238
8239 /* An instance of this type is used to represent an exec catchpoint.
8240    A breakpoint is really of this type iff its ops pointer points to
8241    CATCH_EXEC_BREAKPOINT_OPS.  */
8242
8243 struct exec_catchpoint : public breakpoint
8244 {
8245   ~exec_catchpoint () override;
8246
8247   /* Filename of a program whose exec triggered this catchpoint.
8248      This field is only valid immediately after this catchpoint has
8249      triggered.  */
8250   char *exec_pathname;
8251 };
8252
8253 /* Exec catchpoint destructor.  */
8254
8255 exec_catchpoint::~exec_catchpoint ()
8256 {
8257   xfree (this->exec_pathname);
8258 }
8259
8260 static int
8261 insert_catch_exec (struct bp_location *bl)
8262 {
8263   return target_insert_exec_catchpoint (inferior_ptid.pid ());
8264 }
8265
8266 static int
8267 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8268 {
8269   return target_remove_exec_catchpoint (inferior_ptid.pid ());
8270 }
8271
8272 static int
8273 breakpoint_hit_catch_exec (const struct bp_location *bl,
8274                            const address_space *aspace, CORE_ADDR bp_addr,
8275                            const struct target_waitstatus *ws)
8276 {
8277   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8278
8279   if (ws->kind != TARGET_WAITKIND_EXECD)
8280     return 0;
8281
8282   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8283   return 1;
8284 }
8285
8286 static enum print_stop_action
8287 print_it_catch_exec (bpstat bs)
8288 {
8289   struct ui_out *uiout = current_uiout;
8290   struct breakpoint *b = bs->breakpoint_at;
8291   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8292
8293   annotate_catchpoint (b->number);
8294   maybe_print_thread_hit_breakpoint (uiout);
8295   if (b->disposition == disp_del)
8296     uiout->text ("Temporary catchpoint ");
8297   else
8298     uiout->text ("Catchpoint ");
8299   if (uiout->is_mi_like_p ())
8300     {
8301       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8302       uiout->field_string ("disp", bpdisp_text (b->disposition));
8303     }
8304   uiout->field_int ("bkptno", b->number);
8305   uiout->text (" (exec'd ");
8306   uiout->field_string ("new-exec", c->exec_pathname);
8307   uiout->text ("), ");
8308
8309   return PRINT_SRC_AND_LOC;
8310 }
8311
8312 static void
8313 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8314 {
8315   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8316   struct value_print_options opts;
8317   struct ui_out *uiout = current_uiout;
8318
8319   get_user_print_options (&opts);
8320
8321   /* Field 4, the address, is omitted (which makes the columns
8322      not line up too nicely with the headers, but the effect
8323      is relatively readable).  */
8324   if (opts.addressprint)
8325     uiout->field_skip ("addr");
8326   annotate_field (5);
8327   uiout->text ("exec");
8328   if (c->exec_pathname != NULL)
8329     {
8330       uiout->text (", program \"");
8331       uiout->field_string ("what", c->exec_pathname);
8332       uiout->text ("\" ");
8333     }
8334
8335   if (uiout->is_mi_like_p ())
8336     uiout->field_string ("catch-type", "exec");
8337 }
8338
8339 static void
8340 print_mention_catch_exec (struct breakpoint *b)
8341 {
8342   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8343 }
8344
8345 /* Implement the "print_recreate" breakpoint_ops method for exec
8346    catchpoints.  */
8347
8348 static void
8349 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8350 {
8351   fprintf_unfiltered (fp, "catch exec");
8352   print_recreate_thread (b, fp);
8353 }
8354
8355 static struct breakpoint_ops catch_exec_breakpoint_ops;
8356
8357 static int
8358 hw_breakpoint_used_count (void)
8359 {
8360   int i = 0;
8361   struct breakpoint *b;
8362   struct bp_location *bl;
8363
8364   ALL_BREAKPOINTS (b)
8365   {
8366     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8367       for (bl = b->loc; bl; bl = bl->next)
8368         {
8369           /* Special types of hardware breakpoints may use more than
8370              one register.  */
8371           i += b->ops->resources_needed (bl);
8372         }
8373   }
8374
8375   return i;
8376 }
8377
8378 /* Returns the resources B would use if it were a hardware
8379    watchpoint.  */
8380
8381 static int
8382 hw_watchpoint_use_count (struct breakpoint *b)
8383 {
8384   int i = 0;
8385   struct bp_location *bl;
8386
8387   if (!breakpoint_enabled (b))
8388     return 0;
8389
8390   for (bl = b->loc; bl; bl = bl->next)
8391     {
8392       /* Special types of hardware watchpoints may use more than
8393          one register.  */
8394       i += b->ops->resources_needed (bl);
8395     }
8396
8397   return i;
8398 }
8399
8400 /* Returns the sum the used resources of all hardware watchpoints of
8401    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8402    the sum of the used resources of all hardware watchpoints of other
8403    types _not_ TYPE.  */
8404
8405 static int
8406 hw_watchpoint_used_count_others (struct breakpoint *except,
8407                                  enum bptype type, int *other_type_used)
8408 {
8409   int i = 0;
8410   struct breakpoint *b;
8411
8412   *other_type_used = 0;
8413   ALL_BREAKPOINTS (b)
8414     {
8415       if (b == except)
8416         continue;
8417       if (!breakpoint_enabled (b))
8418         continue;
8419
8420       if (b->type == type)
8421         i += hw_watchpoint_use_count (b);
8422       else if (is_hardware_watchpoint (b))
8423         *other_type_used = 1;
8424     }
8425
8426   return i;
8427 }
8428
8429 void
8430 disable_watchpoints_before_interactive_call_start (void)
8431 {
8432   struct breakpoint *b;
8433
8434   ALL_BREAKPOINTS (b)
8435   {
8436     if (is_watchpoint (b) && breakpoint_enabled (b))
8437       {
8438         b->enable_state = bp_call_disabled;
8439         update_global_location_list (UGLL_DONT_INSERT);
8440       }
8441   }
8442 }
8443
8444 void
8445 enable_watchpoints_after_interactive_call_stop (void)
8446 {
8447   struct breakpoint *b;
8448
8449   ALL_BREAKPOINTS (b)
8450   {
8451     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8452       {
8453         b->enable_state = bp_enabled;
8454         update_global_location_list (UGLL_MAY_INSERT);
8455       }
8456   }
8457 }
8458
8459 void
8460 disable_breakpoints_before_startup (void)
8461 {
8462   current_program_space->executing_startup = 1;
8463   update_global_location_list (UGLL_DONT_INSERT);
8464 }
8465
8466 void
8467 enable_breakpoints_after_startup (void)
8468 {
8469   current_program_space->executing_startup = 0;
8470   breakpoint_re_set ();
8471 }
8472
8473 /* Create a new single-step breakpoint for thread THREAD, with no
8474    locations.  */
8475
8476 static struct breakpoint *
8477 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8478 {
8479   std::unique_ptr<breakpoint> b (new breakpoint ());
8480
8481   init_raw_breakpoint_without_location (b.get (), gdbarch, bp_single_step,
8482                                         &momentary_breakpoint_ops);
8483
8484   b->disposition = disp_donttouch;
8485   b->frame_id = null_frame_id;
8486
8487   b->thread = thread;
8488   gdb_assert (b->thread != 0);
8489
8490   return add_to_breakpoint_chain (std::move (b));
8491 }
8492
8493 /* Set a momentary breakpoint of type TYPE at address specified by
8494    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8495    frame.  */
8496
8497 breakpoint_up
8498 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8499                           struct frame_id frame_id, enum bptype type)
8500 {
8501   struct breakpoint *b;
8502
8503   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8504      tail-called one.  */
8505   gdb_assert (!frame_id_artificial_p (frame_id));
8506
8507   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8508   b->enable_state = bp_enabled;
8509   b->disposition = disp_donttouch;
8510   b->frame_id = frame_id;
8511
8512   b->thread = inferior_thread ()->global_num;
8513
8514   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8515
8516   return breakpoint_up (b);
8517 }
8518
8519 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8520    The new breakpoint will have type TYPE, use OPS as its
8521    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8522
8523 static struct breakpoint *
8524 momentary_breakpoint_from_master (struct breakpoint *orig,
8525                                   enum bptype type,
8526                                   const struct breakpoint_ops *ops,
8527                                   int loc_enabled)
8528 {
8529   struct breakpoint *copy;
8530
8531   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8532   copy->loc = allocate_bp_location (copy);
8533   set_breakpoint_location_function (copy->loc, 1);
8534
8535   copy->loc->gdbarch = orig->loc->gdbarch;
8536   copy->loc->requested_address = orig->loc->requested_address;
8537   copy->loc->address = orig->loc->address;
8538   copy->loc->section = orig->loc->section;
8539   copy->loc->pspace = orig->loc->pspace;
8540   copy->loc->probe = orig->loc->probe;
8541   copy->loc->line_number = orig->loc->line_number;
8542   copy->loc->symtab = orig->loc->symtab;
8543   copy->loc->enabled = loc_enabled;
8544   copy->frame_id = orig->frame_id;
8545   copy->thread = orig->thread;
8546   copy->pspace = orig->pspace;
8547
8548   copy->enable_state = bp_enabled;
8549   copy->disposition = disp_donttouch;
8550   copy->number = internal_breakpoint_number--;
8551
8552   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8553   return copy;
8554 }
8555
8556 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8557    ORIG is NULL.  */
8558
8559 struct breakpoint *
8560 clone_momentary_breakpoint (struct breakpoint *orig)
8561 {
8562   /* If there's nothing to clone, then return nothing.  */
8563   if (orig == NULL)
8564     return NULL;
8565
8566   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8567 }
8568
8569 breakpoint_up
8570 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8571                                 enum bptype type)
8572 {
8573   struct symtab_and_line sal;
8574
8575   sal = find_pc_line (pc, 0);
8576   sal.pc = pc;
8577   sal.section = find_pc_overlay (pc);
8578   sal.explicit_pc = 1;
8579
8580   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8581 }
8582 \f
8583
8584 /* Tell the user we have just set a breakpoint B.  */
8585
8586 static void
8587 mention (struct breakpoint *b)
8588 {
8589   b->ops->print_mention (b);
8590   current_uiout->text ("\n");
8591 }
8592 \f
8593
8594 static int bp_loc_is_permanent (struct bp_location *loc);
8595
8596 static struct bp_location *
8597 add_location_to_breakpoint (struct breakpoint *b,
8598                             const struct symtab_and_line *sal)
8599 {
8600   struct bp_location *loc, **tmp;
8601   CORE_ADDR adjusted_address;
8602   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8603
8604   if (loc_gdbarch == NULL)
8605     loc_gdbarch = b->gdbarch;
8606
8607   /* Adjust the breakpoint's address prior to allocating a location.
8608      Once we call allocate_bp_location(), that mostly uninitialized
8609      location will be placed on the location chain.  Adjustment of the
8610      breakpoint may cause target_read_memory() to be called and we do
8611      not want its scan of the location chain to find a breakpoint and
8612      location that's only been partially initialized.  */
8613   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8614                                                 sal->pc, b->type);
8615
8616   /* Sort the locations by their ADDRESS.  */
8617   loc = allocate_bp_location (b);
8618   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8619        tmp = &((*tmp)->next))
8620     ;
8621   loc->next = *tmp;
8622   *tmp = loc;
8623
8624   loc->requested_address = sal->pc;
8625   loc->address = adjusted_address;
8626   loc->pspace = sal->pspace;
8627   loc->probe.prob = sal->prob;
8628   loc->probe.objfile = sal->objfile;
8629   gdb_assert (loc->pspace != NULL);
8630   loc->section = sal->section;
8631   loc->gdbarch = loc_gdbarch;
8632   loc->line_number = sal->line;
8633   loc->symtab = sal->symtab;
8634   loc->symbol = sal->symbol;
8635   loc->msymbol = sal->msymbol;
8636   loc->objfile = sal->objfile;
8637
8638   set_breakpoint_location_function (loc,
8639                                     sal->explicit_pc || sal->explicit_line);
8640
8641   /* While by definition, permanent breakpoints are already present in the
8642      code, we don't mark the location as inserted.  Normally one would expect
8643      that GDB could rely on that breakpoint instruction to stop the program,
8644      thus removing the need to insert its own breakpoint, except that executing
8645      the breakpoint instruction can kill the target instead of reporting a
8646      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8647      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8648      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8649      breakpoint be inserted normally results in QEMU knowing about the GDB
8650      breakpoint, and thus trap before the breakpoint instruction is executed.
8651      (If GDB later needs to continue execution past the permanent breakpoint,
8652      it manually increments the PC, thus avoiding executing the breakpoint
8653      instruction.)  */
8654   if (bp_loc_is_permanent (loc))
8655     loc->permanent = 1;
8656
8657   return loc;
8658 }
8659 \f
8660
8661 /* See breakpoint.h.  */
8662
8663 int
8664 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
8665 {
8666   int len;
8667   CORE_ADDR addr;
8668   const gdb_byte *bpoint;
8669   gdb_byte *target_mem;
8670
8671   addr = address;
8672   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
8673
8674   /* Software breakpoints unsupported?  */
8675   if (bpoint == NULL)
8676     return 0;
8677
8678   target_mem = (gdb_byte *) alloca (len);
8679
8680   /* Enable the automatic memory restoration from breakpoints while
8681      we read the memory.  Otherwise we could say about our temporary
8682      breakpoints they are permanent.  */
8683   scoped_restore restore_memory
8684     = make_scoped_restore_show_memory_breakpoints (0);
8685
8686   if (target_read_memory (address, target_mem, len) == 0
8687       && memcmp (target_mem, bpoint, len) == 0)
8688     return 1;
8689
8690   return 0;
8691 }
8692
8693 /* Return 1 if LOC is pointing to a permanent breakpoint,
8694    return 0 otherwise.  */
8695
8696 static int
8697 bp_loc_is_permanent (struct bp_location *loc)
8698 {
8699   gdb_assert (loc != NULL);
8700
8701   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
8702      attempt to read from the addresses the locations of these breakpoint types
8703      point to.  program_breakpoint_here_p, below, will attempt to read
8704      memory.  */
8705   if (!breakpoint_address_is_meaningful (loc->owner))
8706     return 0;
8707
8708   scoped_restore_current_pspace_and_thread restore_pspace_thread;
8709   switch_to_program_space_and_thread (loc->pspace);
8710   return program_breakpoint_here_p (loc->gdbarch, loc->address);
8711 }
8712
8713 /* Build a command list for the dprintf corresponding to the current
8714    settings of the dprintf style options.  */
8715
8716 static void
8717 update_dprintf_command_list (struct breakpoint *b)
8718 {
8719   char *dprintf_args = b->extra_string;
8720   char *printf_line = NULL;
8721
8722   if (!dprintf_args)
8723     return;
8724
8725   dprintf_args = skip_spaces (dprintf_args);
8726
8727   /* Allow a comma, as it may have terminated a location, but don't
8728      insist on it.  */
8729   if (*dprintf_args == ',')
8730     ++dprintf_args;
8731   dprintf_args = skip_spaces (dprintf_args);
8732
8733   if (*dprintf_args != '"')
8734     error (_("Bad format string, missing '\"'."));
8735
8736   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8737     printf_line = xstrprintf ("printf %s", dprintf_args);
8738   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8739     {
8740       if (!dprintf_function)
8741         error (_("No function supplied for dprintf call"));
8742
8743       if (dprintf_channel && strlen (dprintf_channel) > 0)
8744         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8745                                   dprintf_function,
8746                                   dprintf_channel,
8747                                   dprintf_args);
8748       else
8749         printf_line = xstrprintf ("call (void) %s (%s)",
8750                                   dprintf_function,
8751                                   dprintf_args);
8752     }
8753   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8754     {
8755       if (target_can_run_breakpoint_commands ())
8756         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8757       else
8758         {
8759           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8760           printf_line = xstrprintf ("printf %s", dprintf_args);
8761         }
8762     }
8763   else
8764     internal_error (__FILE__, __LINE__,
8765                     _("Invalid dprintf style."));
8766
8767   gdb_assert (printf_line != NULL);
8768
8769   /* Manufacture a printf sequence.  */
8770   struct command_line *printf_cmd_line
8771     = new struct command_line (simple_control, printf_line);
8772   breakpoint_set_commands (b, counted_command_line (printf_cmd_line,
8773                                                     command_lines_deleter ()));
8774 }
8775
8776 /* Update all dprintf commands, making their command lists reflect
8777    current style settings.  */
8778
8779 static void
8780 update_dprintf_commands (const char *args, int from_tty,
8781                          struct cmd_list_element *c)
8782 {
8783   struct breakpoint *b;
8784
8785   ALL_BREAKPOINTS (b)
8786     {
8787       if (b->type == bp_dprintf)
8788         update_dprintf_command_list (b);
8789     }
8790 }
8791
8792 /* Create a breakpoint with SAL as location.  Use LOCATION
8793    as a description of the location, and COND_STRING
8794    as condition expression.  If LOCATION is NULL then create an
8795    "address location" from the address in the SAL.  */
8796
8797 static void
8798 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8799                      gdb::array_view<const symtab_and_line> sals,
8800                      event_location_up &&location,
8801                      gdb::unique_xmalloc_ptr<char> filter,
8802                      gdb::unique_xmalloc_ptr<char> cond_string,
8803                      gdb::unique_xmalloc_ptr<char> extra_string,
8804                      enum bptype type, enum bpdisp disposition,
8805                      int thread, int task, int ignore_count,
8806                      const struct breakpoint_ops *ops, int from_tty,
8807                      int enabled, int internal, unsigned flags,
8808                      int display_canonical)
8809 {
8810   int i;
8811
8812   if (type == bp_hardware_breakpoint)
8813     {
8814       int target_resources_ok;
8815
8816       i = hw_breakpoint_used_count ();
8817       target_resources_ok =
8818         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8819                                             i + 1, 0);
8820       if (target_resources_ok == 0)
8821         error (_("No hardware breakpoint support in the target."));
8822       else if (target_resources_ok < 0)
8823         error (_("Hardware breakpoints used exceeds limit."));
8824     }
8825
8826   gdb_assert (!sals.empty ());
8827
8828   for (const auto &sal : sals)
8829     {
8830       struct bp_location *loc;
8831
8832       if (from_tty)
8833         {
8834           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8835           if (!loc_gdbarch)
8836             loc_gdbarch = gdbarch;
8837
8838           describe_other_breakpoints (loc_gdbarch,
8839                                       sal.pspace, sal.pc, sal.section, thread);
8840         }
8841
8842       if (&sal == &sals[0])
8843         {
8844           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8845           b->thread = thread;
8846           b->task = task;
8847
8848           b->cond_string = cond_string.release ();
8849           b->extra_string = extra_string.release ();
8850           b->ignore_count = ignore_count;
8851           b->enable_state = enabled ? bp_enabled : bp_disabled;
8852           b->disposition = disposition;
8853
8854           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8855             b->loc->inserted = 1;
8856
8857           if (type == bp_static_tracepoint)
8858             {
8859               struct tracepoint *t = (struct tracepoint *) b;
8860               struct static_tracepoint_marker marker;
8861
8862               if (strace_marker_p (b))
8863                 {
8864                   /* We already know the marker exists, otherwise, we
8865                      wouldn't see a sal for it.  */
8866                   const char *p
8867                     = &event_location_to_string (b->location.get ())[3];
8868                   const char *endp;
8869
8870                   p = skip_spaces (p);
8871
8872                   endp = skip_to_space (p);
8873
8874                   t->static_trace_marker_id.assign (p, endp - p);
8875
8876                   printf_filtered (_("Probed static tracepoint "
8877                                      "marker \"%s\"\n"),
8878                                    t->static_trace_marker_id.c_str ());
8879                 }
8880               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8881                 {
8882                   t->static_trace_marker_id = std::move (marker.str_id);
8883
8884                   printf_filtered (_("Probed static tracepoint "
8885                                      "marker \"%s\"\n"),
8886                                    t->static_trace_marker_id.c_str ());
8887                 }
8888               else
8889                 warning (_("Couldn't determine the static "
8890                            "tracepoint marker to probe"));
8891             }
8892
8893           loc = b->loc;
8894         }
8895       else
8896         {
8897           loc = add_location_to_breakpoint (b, &sal);
8898           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8899             loc->inserted = 1;
8900         }
8901
8902       if (b->cond_string)
8903         {
8904           const char *arg = b->cond_string;
8905
8906           loc->cond = parse_exp_1 (&arg, loc->address,
8907                                    block_for_pc (loc->address), 0);
8908           if (*arg)
8909               error (_("Garbage '%s' follows condition"), arg);
8910         }
8911
8912       /* Dynamic printf requires and uses additional arguments on the
8913          command line, otherwise it's an error.  */
8914       if (type == bp_dprintf)
8915         {
8916           if (b->extra_string)
8917             update_dprintf_command_list (b);
8918           else
8919             error (_("Format string required"));
8920         }
8921       else if (b->extra_string)
8922         error (_("Garbage '%s' at end of command"), b->extra_string);
8923     }
8924
8925   b->display_canonical = display_canonical;
8926   if (location != NULL)
8927     b->location = std::move (location);
8928   else
8929     b->location = new_address_location (b->loc->address, NULL, 0);
8930   b->filter = filter.release ();
8931 }
8932
8933 static void
8934 create_breakpoint_sal (struct gdbarch *gdbarch,
8935                        gdb::array_view<const symtab_and_line> sals,
8936                        event_location_up &&location,
8937                        gdb::unique_xmalloc_ptr<char> filter,
8938                        gdb::unique_xmalloc_ptr<char> cond_string,
8939                        gdb::unique_xmalloc_ptr<char> extra_string,
8940                        enum bptype type, enum bpdisp disposition,
8941                        int thread, int task, int ignore_count,
8942                        const struct breakpoint_ops *ops, int from_tty,
8943                        int enabled, int internal, unsigned flags,
8944                        int display_canonical)
8945 {
8946   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (type);
8947
8948   init_breakpoint_sal (b.get (), gdbarch,
8949                        sals, std::move (location),
8950                        std::move (filter),
8951                        std::move (cond_string),
8952                        std::move (extra_string),
8953                        type, disposition,
8954                        thread, task, ignore_count,
8955                        ops, from_tty,
8956                        enabled, internal, flags,
8957                        display_canonical);
8958
8959   install_breakpoint (internal, std::move (b), 0);
8960 }
8961
8962 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
8963    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8964    value.  COND_STRING, if not NULL, specified the condition to be
8965    used for all breakpoints.  Essentially the only case where
8966    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8967    function.  In that case, it's still not possible to specify
8968    separate conditions for different overloaded functions, so
8969    we take just a single condition string.
8970    
8971    NOTE: If the function succeeds, the caller is expected to cleanup
8972    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8973    array contents).  If the function fails (error() is called), the
8974    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8975    COND and SALS arrays and each of those arrays contents.  */
8976
8977 static void
8978 create_breakpoints_sal (struct gdbarch *gdbarch,
8979                         struct linespec_result *canonical,
8980                         gdb::unique_xmalloc_ptr<char> cond_string,
8981                         gdb::unique_xmalloc_ptr<char> extra_string,
8982                         enum bptype type, enum bpdisp disposition,
8983                         int thread, int task, int ignore_count,
8984                         const struct breakpoint_ops *ops, int from_tty,
8985                         int enabled, int internal, unsigned flags)
8986 {
8987   if (canonical->pre_expanded)
8988     gdb_assert (canonical->lsals.size () == 1);
8989
8990   for (const auto &lsal : canonical->lsals)
8991     {
8992       /* Note that 'location' can be NULL in the case of a plain
8993          'break', without arguments.  */
8994       event_location_up location
8995         = (canonical->location != NULL
8996            ? copy_event_location (canonical->location.get ()) : NULL);
8997       gdb::unique_xmalloc_ptr<char> filter_string
8998         (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
8999
9000       create_breakpoint_sal (gdbarch, lsal.sals,
9001                              std::move (location),
9002                              std::move (filter_string),
9003                              std::move (cond_string),
9004                              std::move (extra_string),
9005                              type, disposition,
9006                              thread, task, ignore_count, ops,
9007                              from_tty, enabled, internal, flags,
9008                              canonical->special_display);
9009     }
9010 }
9011
9012 /* Parse LOCATION which is assumed to be a SAL specification possibly
9013    followed by conditionals.  On return, SALS contains an array of SAL
9014    addresses found.  LOCATION points to the end of the SAL (for
9015    linespec locations).
9016
9017    The array and the line spec strings are allocated on the heap, it is
9018    the caller's responsibility to free them.  */
9019
9020 static void
9021 parse_breakpoint_sals (const struct event_location *location,
9022                        struct linespec_result *canonical)
9023 {
9024   struct symtab_and_line cursal;
9025
9026   if (event_location_type (location) == LINESPEC_LOCATION)
9027     {
9028       const char *spec = get_linespec_location (location)->spec_string;
9029
9030       if (spec == NULL)
9031         {
9032           /* The last displayed codepoint, if it's valid, is our default
9033              breakpoint address.  */
9034           if (last_displayed_sal_is_valid ())
9035             {
9036               /* Set sal's pspace, pc, symtab, and line to the values
9037                  corresponding to the last call to print_frame_info.
9038                  Be sure to reinitialize LINE with NOTCURRENT == 0
9039                  as the breakpoint line number is inappropriate otherwise.
9040                  find_pc_line would adjust PC, re-set it back.  */
9041               symtab_and_line sal = get_last_displayed_sal ();
9042               CORE_ADDR pc = sal.pc;
9043
9044               sal = find_pc_line (pc, 0);
9045
9046               /* "break" without arguments is equivalent to "break *PC"
9047                  where PC is the last displayed codepoint's address.  So
9048                  make sure to set sal.explicit_pc to prevent GDB from
9049                  trying to expand the list of sals to include all other
9050                  instances with the same symtab and line.  */
9051               sal.pc = pc;
9052               sal.explicit_pc = 1;
9053
9054               struct linespec_sals lsal;
9055               lsal.sals = {sal};
9056               lsal.canonical = NULL;
9057
9058               canonical->lsals.push_back (std::move (lsal));
9059               return;
9060             }
9061           else
9062             error (_("No default breakpoint address now."));
9063         }
9064     }
9065
9066   /* Force almost all breakpoints to be in terms of the
9067      current_source_symtab (which is decode_line_1's default).
9068      This should produce the results we want almost all of the
9069      time while leaving default_breakpoint_* alone.
9070
9071      ObjC: However, don't match an Objective-C method name which
9072      may have a '+' or '-' succeeded by a '['.  */
9073   cursal = get_current_source_symtab_and_line ();
9074   if (last_displayed_sal_is_valid ())
9075     {
9076       const char *spec = NULL;
9077
9078       if (event_location_type (location) == LINESPEC_LOCATION)
9079         spec = get_linespec_location (location)->spec_string;
9080
9081       if (!cursal.symtab
9082           || (spec != NULL
9083               && strchr ("+-", spec[0]) != NULL
9084               && spec[1] != '['))
9085         {
9086           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9087                             get_last_displayed_symtab (),
9088                             get_last_displayed_line (),
9089                             canonical, NULL, NULL);
9090           return;
9091         }
9092     }
9093
9094   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9095                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9096 }
9097
9098
9099 /* Convert each SAL into a real PC.  Verify that the PC can be
9100    inserted as a breakpoint.  If it can't throw an error.  */
9101
9102 static void
9103 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
9104 {    
9105   for (auto &sal : sals)
9106     resolve_sal_pc (&sal);
9107 }
9108
9109 /* Fast tracepoints may have restrictions on valid locations.  For
9110    instance, a fast tracepoint using a jump instead of a trap will
9111    likely have to overwrite more bytes than a trap would, and so can
9112    only be placed where the instruction is longer than the jump, or a
9113    multi-instruction sequence does not have a jump into the middle of
9114    it, etc.  */
9115
9116 static void
9117 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9118                             gdb::array_view<const symtab_and_line> sals)
9119 {
9120   for (const auto &sal : sals)
9121     {
9122       struct gdbarch *sarch;
9123
9124       sarch = get_sal_arch (sal);
9125       /* We fall back to GDBARCH if there is no architecture
9126          associated with SAL.  */
9127       if (sarch == NULL)
9128         sarch = gdbarch;
9129       std::string msg;
9130       if (!gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg))
9131         error (_("May not have a fast tracepoint at %s%s"),
9132                paddress (sarch, sal.pc), msg.c_str ());
9133     }
9134 }
9135
9136 /* Given TOK, a string specification of condition and thread, as
9137    accepted by the 'break' command, extract the condition
9138    string and thread number and set *COND_STRING and *THREAD.
9139    PC identifies the context at which the condition should be parsed.
9140    If no condition is found, *COND_STRING is set to NULL.
9141    If no thread is found, *THREAD is set to -1.  */
9142
9143 static void
9144 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9145                            char **cond_string, int *thread, int *task,
9146                            char **rest)
9147 {
9148   *cond_string = NULL;
9149   *thread = -1;
9150   *task = 0;
9151   *rest = NULL;
9152
9153   while (tok && *tok)
9154     {
9155       const char *end_tok;
9156       int toklen;
9157       const char *cond_start = NULL;
9158       const char *cond_end = NULL;
9159
9160       tok = skip_spaces (tok);
9161
9162       if ((*tok == '"' || *tok == ',') && rest)
9163         {
9164           *rest = savestring (tok, strlen (tok));
9165           return;
9166         }
9167
9168       end_tok = skip_to_space (tok);
9169
9170       toklen = end_tok - tok;
9171
9172       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9173         {
9174           tok = cond_start = end_tok + 1;
9175           parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9176           cond_end = tok;
9177           *cond_string = savestring (cond_start, cond_end - cond_start);
9178         }
9179       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9180         {
9181           const char *tmptok;
9182           struct thread_info *thr;
9183
9184           tok = end_tok + 1;
9185           thr = parse_thread_id (tok, &tmptok);
9186           if (tok == tmptok)
9187             error (_("Junk after thread keyword."));
9188           *thread = thr->global_num;
9189           tok = tmptok;
9190         }
9191       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9192         {
9193           char *tmptok;
9194
9195           tok = end_tok + 1;
9196           *task = strtol (tok, &tmptok, 0);
9197           if (tok == tmptok)
9198             error (_("Junk after task keyword."));
9199           if (!valid_task_id (*task))
9200             error (_("Unknown task %d."), *task);
9201           tok = tmptok;
9202         }
9203       else if (rest)
9204         {
9205           *rest = savestring (tok, strlen (tok));
9206           return;
9207         }
9208       else
9209         error (_("Junk at end of arguments."));
9210     }
9211 }
9212
9213 /* Decode a static tracepoint marker spec.  */
9214
9215 static std::vector<symtab_and_line>
9216 decode_static_tracepoint_spec (const char **arg_p)
9217 {
9218   const char *p = &(*arg_p)[3];
9219   const char *endp;
9220
9221   p = skip_spaces (p);
9222
9223   endp = skip_to_space (p);
9224
9225   std::string marker_str (p, endp - p);
9226
9227   std::vector<static_tracepoint_marker> markers
9228     = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
9229   if (markers.empty ())
9230     error (_("No known static tracepoint marker named %s"),
9231            marker_str.c_str ());
9232
9233   std::vector<symtab_and_line> sals;
9234   sals.reserve (markers.size ());
9235
9236   for (const static_tracepoint_marker &marker : markers)
9237     {
9238       symtab_and_line sal = find_pc_line (marker.address, 0);
9239       sal.pc = marker.address;
9240       sals.push_back (sal);
9241    }
9242
9243   *arg_p = endp;
9244   return sals;
9245 }
9246
9247 /* See breakpoint.h.  */
9248
9249 int
9250 create_breakpoint (struct gdbarch *gdbarch,
9251                    const struct event_location *location,
9252                    const char *cond_string,
9253                    int thread, const char *extra_string,
9254                    int parse_extra,
9255                    int tempflag, enum bptype type_wanted,
9256                    int ignore_count,
9257                    enum auto_boolean pending_break_support,
9258                    const struct breakpoint_ops *ops,
9259                    int from_tty, int enabled, int internal,
9260                    unsigned flags)
9261 {
9262   struct linespec_result canonical;
9263   struct cleanup *bkpt_chain = NULL;
9264   int pending = 0;
9265   int task = 0;
9266   int prev_bkpt_count = breakpoint_count;
9267
9268   gdb_assert (ops != NULL);
9269
9270   /* If extra_string isn't useful, set it to NULL.  */
9271   if (extra_string != NULL && *extra_string == '\0')
9272     extra_string = NULL;
9273
9274   TRY
9275     {
9276       ops->create_sals_from_location (location, &canonical, type_wanted);
9277     }
9278   CATCH (e, RETURN_MASK_ERROR)
9279     {
9280       /* If caller is interested in rc value from parse, set
9281          value.  */
9282       if (e.error == NOT_FOUND_ERROR)
9283         {
9284           /* If pending breakpoint support is turned off, throw
9285              error.  */
9286
9287           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9288             throw_exception (e);
9289
9290           exception_print (gdb_stderr, e);
9291
9292           /* If pending breakpoint support is auto query and the user
9293              selects no, then simply return the error code.  */
9294           if (pending_break_support == AUTO_BOOLEAN_AUTO
9295               && !nquery (_("Make %s pending on future shared library load? "),
9296                           bptype_string (type_wanted)))
9297             return 0;
9298
9299           /* At this point, either the user was queried about setting
9300              a pending breakpoint and selected yes, or pending
9301              breakpoint behavior is on and thus a pending breakpoint
9302              is defaulted on behalf of the user.  */
9303           pending = 1;
9304         }
9305       else
9306         throw_exception (e);
9307     }
9308   END_CATCH
9309
9310   if (!pending && canonical.lsals.empty ())
9311     return 0;
9312
9313   /* ----------------------------- SNIP -----------------------------
9314      Anything added to the cleanup chain beyond this point is assumed
9315      to be part of a breakpoint.  If the breakpoint create succeeds
9316      then the memory is not reclaimed.  */
9317   bkpt_chain = make_cleanup (null_cleanup, 0);
9318
9319   /* Resolve all line numbers to PC's and verify that the addresses
9320      are ok for the target.  */
9321   if (!pending)
9322     {
9323       for (auto &lsal : canonical.lsals)
9324         breakpoint_sals_to_pc (lsal.sals);
9325     }
9326
9327   /* Fast tracepoints may have additional restrictions on location.  */
9328   if (!pending && type_wanted == bp_fast_tracepoint)
9329     {
9330       for (const auto &lsal : canonical.lsals)
9331         check_fast_tracepoint_sals (gdbarch, lsal.sals);
9332     }
9333
9334   /* Verify that condition can be parsed, before setting any
9335      breakpoints.  Allocate a separate condition expression for each
9336      breakpoint.  */
9337   if (!pending)
9338     {
9339       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9340       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9341
9342       if (parse_extra)
9343         {
9344           char *rest;
9345           char *cond;
9346
9347           const linespec_sals &lsal = canonical.lsals[0];
9348
9349           /* Here we only parse 'arg' to separate condition
9350              from thread number, so parsing in context of first
9351              sal is OK.  When setting the breakpoint we'll
9352              re-parse it in context of each sal.  */
9353
9354           find_condition_and_thread (extra_string, lsal.sals[0].pc,
9355                                      &cond, &thread, &task, &rest);
9356           cond_string_copy.reset (cond);
9357           extra_string_copy.reset (rest);
9358         }
9359       else
9360         {
9361           if (type_wanted != bp_dprintf
9362               && extra_string != NULL && *extra_string != '\0')
9363                 error (_("Garbage '%s' at end of location"), extra_string);
9364
9365           /* Create a private copy of condition string.  */
9366           if (cond_string)
9367             cond_string_copy.reset (xstrdup (cond_string));
9368           /* Create a private copy of any extra string.  */
9369           if (extra_string)
9370             extra_string_copy.reset (xstrdup (extra_string));
9371         }
9372
9373       ops->create_breakpoints_sal (gdbarch, &canonical,
9374                                    std::move (cond_string_copy),
9375                                    std::move (extra_string_copy),
9376                                    type_wanted,
9377                                    tempflag ? disp_del : disp_donttouch,
9378                                    thread, task, ignore_count, ops,
9379                                    from_tty, enabled, internal, flags);
9380     }
9381   else
9382     {
9383       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (type_wanted);
9384
9385       init_raw_breakpoint_without_location (b.get (), gdbarch, type_wanted, ops);
9386       b->location = copy_event_location (location);
9387
9388       if (parse_extra)
9389         b->cond_string = NULL;
9390       else
9391         {
9392           /* Create a private copy of condition string.  */
9393           b->cond_string = cond_string != NULL ? xstrdup (cond_string) : NULL;
9394           b->thread = thread;
9395         }
9396
9397       /* Create a private copy of any extra string.  */
9398       b->extra_string = extra_string != NULL ? xstrdup (extra_string) : NULL;
9399       b->ignore_count = ignore_count;
9400       b->disposition = tempflag ? disp_del : disp_donttouch;
9401       b->condition_not_parsed = 1;
9402       b->enable_state = enabled ? bp_enabled : bp_disabled;
9403       if ((type_wanted != bp_breakpoint
9404            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9405         b->pspace = current_program_space;
9406
9407       install_breakpoint (internal, std::move (b), 0);
9408     }
9409   
9410   if (canonical.lsals.size () > 1)
9411     {
9412       warning (_("Multiple breakpoints were set.\nUse the "
9413                  "\"delete\" command to delete unwanted breakpoints."));
9414       prev_breakpoint_count = prev_bkpt_count;
9415     }
9416
9417   /* That's it.  Discard the cleanups for data inserted into the
9418      breakpoint.  */
9419   discard_cleanups (bkpt_chain);
9420
9421   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9422   update_global_location_list (UGLL_MAY_INSERT);
9423
9424   return 1;
9425 }
9426
9427 /* Set a breakpoint.
9428    ARG is a string describing breakpoint address,
9429    condition, and thread.
9430    FLAG specifies if a breakpoint is hardware on,
9431    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9432    and BP_TEMPFLAG.  */
9433
9434 static void
9435 break_command_1 (const char *arg, int flag, int from_tty)
9436 {
9437   int tempflag = flag & BP_TEMPFLAG;
9438   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9439                              ? bp_hardware_breakpoint
9440                              : bp_breakpoint);
9441   struct breakpoint_ops *ops;
9442
9443   event_location_up location = string_to_event_location (&arg, current_language);
9444
9445   /* Matching breakpoints on probes.  */
9446   if (location != NULL
9447       && event_location_type (location.get ()) == PROBE_LOCATION)
9448     ops = &bkpt_probe_breakpoint_ops;
9449   else
9450     ops = &bkpt_breakpoint_ops;
9451
9452   create_breakpoint (get_current_arch (),
9453                      location.get (),
9454                      NULL, 0, arg, 1 /* parse arg */,
9455                      tempflag, type_wanted,
9456                      0 /* Ignore count */,
9457                      pending_break_support,
9458                      ops,
9459                      from_tty,
9460                      1 /* enabled */,
9461                      0 /* internal */,
9462                      0);
9463 }
9464
9465 /* Helper function for break_command_1 and disassemble_command.  */
9466
9467 void
9468 resolve_sal_pc (struct symtab_and_line *sal)
9469 {
9470   CORE_ADDR pc;
9471
9472   if (sal->pc == 0 && sal->symtab != NULL)
9473     {
9474       if (!find_line_pc (sal->symtab, sal->line, &pc))
9475         error (_("No line %d in file \"%s\"."),
9476                sal->line, symtab_to_filename_for_display (sal->symtab));
9477       sal->pc = pc;
9478
9479       /* If this SAL corresponds to a breakpoint inserted using a line
9480          number, then skip the function prologue if necessary.  */
9481       if (sal->explicit_line)
9482         skip_prologue_sal (sal);
9483     }
9484
9485   if (sal->section == 0 && sal->symtab != NULL)
9486     {
9487       const struct blockvector *bv;
9488       const struct block *b;
9489       struct symbol *sym;
9490
9491       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9492                                     SYMTAB_COMPUNIT (sal->symtab));
9493       if (bv != NULL)
9494         {
9495           sym = block_linkage_function (b);
9496           if (sym != NULL)
9497             {
9498               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9499               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9500                                                  sym);
9501             }
9502           else
9503             {
9504               /* It really is worthwhile to have the section, so we'll
9505                  just have to look harder. This case can be executed
9506                  if we have line numbers but no functions (as can
9507                  happen in assembly source).  */
9508
9509               scoped_restore_current_pspace_and_thread restore_pspace_thread;
9510               switch_to_program_space_and_thread (sal->pspace);
9511
9512               bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9513               if (msym.minsym)
9514                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9515             }
9516         }
9517     }
9518 }
9519
9520 void
9521 break_command (const char *arg, int from_tty)
9522 {
9523   break_command_1 (arg, 0, from_tty);
9524 }
9525
9526 void
9527 tbreak_command (const char *arg, int from_tty)
9528 {
9529   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9530 }
9531
9532 static void
9533 hbreak_command (const char *arg, int from_tty)
9534 {
9535   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9536 }
9537
9538 static void
9539 thbreak_command (const char *arg, int from_tty)
9540 {
9541   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9542 }
9543
9544 static void
9545 stop_command (const char *arg, int from_tty)
9546 {
9547   printf_filtered (_("Specify the type of breakpoint to set.\n\
9548 Usage: stop in <function | address>\n\
9549        stop at <line>\n"));
9550 }
9551
9552 static void
9553 stopin_command (const char *arg, int from_tty)
9554 {
9555   int badInput = 0;
9556
9557   if (arg == (char *) NULL)
9558     badInput = 1;
9559   else if (*arg != '*')
9560     {
9561       const char *argptr = arg;
9562       int hasColon = 0;
9563
9564       /* Look for a ':'.  If this is a line number specification, then
9565          say it is bad, otherwise, it should be an address or
9566          function/method name.  */
9567       while (*argptr && !hasColon)
9568         {
9569           hasColon = (*argptr == ':');
9570           argptr++;
9571         }
9572
9573       if (hasColon)
9574         badInput = (*argptr != ':');    /* Not a class::method */
9575       else
9576         badInput = isdigit (*arg);      /* a simple line number */
9577     }
9578
9579   if (badInput)
9580     printf_filtered (_("Usage: stop in <function | address>\n"));
9581   else
9582     break_command_1 (arg, 0, from_tty);
9583 }
9584
9585 static void
9586 stopat_command (const char *arg, int from_tty)
9587 {
9588   int badInput = 0;
9589
9590   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9591     badInput = 1;
9592   else
9593     {
9594       const char *argptr = arg;
9595       int hasColon = 0;
9596
9597       /* Look for a ':'.  If there is a '::' then get out, otherwise
9598          it is probably a line number.  */
9599       while (*argptr && !hasColon)
9600         {
9601           hasColon = (*argptr == ':');
9602           argptr++;
9603         }
9604
9605       if (hasColon)
9606         badInput = (*argptr == ':');    /* we have class::method */
9607       else
9608         badInput = !isdigit (*arg);     /* not a line number */
9609     }
9610
9611   if (badInput)
9612     printf_filtered (_("Usage: stop at <line>\n"));
9613   else
9614     break_command_1 (arg, 0, from_tty);
9615 }
9616
9617 /* The dynamic printf command is mostly like a regular breakpoint, but
9618    with a prewired command list consisting of a single output command,
9619    built from extra arguments supplied on the dprintf command
9620    line.  */
9621
9622 static void
9623 dprintf_command (const char *arg, int from_tty)
9624 {
9625   event_location_up location = string_to_event_location (&arg, current_language);
9626
9627   /* If non-NULL, ARG should have been advanced past the location;
9628      the next character must be ','.  */
9629   if (arg != NULL)
9630     {
9631       if (arg[0] != ',' || arg[1] == '\0')
9632         error (_("Format string required"));
9633       else
9634         {
9635           /* Skip the comma.  */
9636           ++arg;
9637         }
9638     }
9639
9640   create_breakpoint (get_current_arch (),
9641                      location.get (),
9642                      NULL, 0, arg, 1 /* parse arg */,
9643                      0, bp_dprintf,
9644                      0 /* Ignore count */,
9645                      pending_break_support,
9646                      &dprintf_breakpoint_ops,
9647                      from_tty,
9648                      1 /* enabled */,
9649                      0 /* internal */,
9650                      0);
9651 }
9652
9653 static void
9654 agent_printf_command (const char *arg, int from_tty)
9655 {
9656   error (_("May only run agent-printf on the target"));
9657 }
9658
9659 /* Implement the "breakpoint_hit" breakpoint_ops method for
9660    ranged breakpoints.  */
9661
9662 static int
9663 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9664                                   const address_space *aspace,
9665                                   CORE_ADDR bp_addr,
9666                                   const struct target_waitstatus *ws)
9667 {
9668   if (ws->kind != TARGET_WAITKIND_STOPPED
9669       || ws->value.sig != GDB_SIGNAL_TRAP)
9670     return 0;
9671
9672   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9673                                          bl->length, aspace, bp_addr);
9674 }
9675
9676 /* Implement the "resources_needed" breakpoint_ops method for
9677    ranged breakpoints.  */
9678
9679 static int
9680 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9681 {
9682   return target_ranged_break_num_registers ();
9683 }
9684
9685 /* Implement the "print_it" breakpoint_ops method for
9686    ranged breakpoints.  */
9687
9688 static enum print_stop_action
9689 print_it_ranged_breakpoint (bpstat bs)
9690 {
9691   struct breakpoint *b = bs->breakpoint_at;
9692   struct bp_location *bl = b->loc;
9693   struct ui_out *uiout = current_uiout;
9694
9695   gdb_assert (b->type == bp_hardware_breakpoint);
9696
9697   /* Ranged breakpoints have only one location.  */
9698   gdb_assert (bl && bl->next == NULL);
9699
9700   annotate_breakpoint (b->number);
9701
9702   maybe_print_thread_hit_breakpoint (uiout);
9703
9704   if (b->disposition == disp_del)
9705     uiout->text ("Temporary ranged breakpoint ");
9706   else
9707     uiout->text ("Ranged breakpoint ");
9708   if (uiout->is_mi_like_p ())
9709     {
9710       uiout->field_string ("reason",
9711                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9712       uiout->field_string ("disp", bpdisp_text (b->disposition));
9713     }
9714   uiout->field_int ("bkptno", b->number);
9715   uiout->text (", ");
9716
9717   return PRINT_SRC_AND_LOC;
9718 }
9719
9720 /* Implement the "print_one" breakpoint_ops method for
9721    ranged breakpoints.  */
9722
9723 static void
9724 print_one_ranged_breakpoint (struct breakpoint *b,
9725                              struct bp_location **last_loc)
9726 {
9727   struct bp_location *bl = b->loc;
9728   struct value_print_options opts;
9729   struct ui_out *uiout = current_uiout;
9730
9731   /* Ranged breakpoints have only one location.  */
9732   gdb_assert (bl && bl->next == NULL);
9733
9734   get_user_print_options (&opts);
9735
9736   if (opts.addressprint)
9737     /* We don't print the address range here, it will be printed later
9738        by print_one_detail_ranged_breakpoint.  */
9739     uiout->field_skip ("addr");
9740   annotate_field (5);
9741   print_breakpoint_location (b, bl);
9742   *last_loc = bl;
9743 }
9744
9745 /* Implement the "print_one_detail" breakpoint_ops method for
9746    ranged breakpoints.  */
9747
9748 static void
9749 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9750                                     struct ui_out *uiout)
9751 {
9752   CORE_ADDR address_start, address_end;
9753   struct bp_location *bl = b->loc;
9754   string_file stb;
9755
9756   gdb_assert (bl);
9757
9758   address_start = bl->address;
9759   address_end = address_start + bl->length - 1;
9760
9761   uiout->text ("\taddress range: ");
9762   stb.printf ("[%s, %s]",
9763               print_core_address (bl->gdbarch, address_start),
9764               print_core_address (bl->gdbarch, address_end));
9765   uiout->field_stream ("addr", stb);
9766   uiout->text ("\n");
9767 }
9768
9769 /* Implement the "print_mention" breakpoint_ops method for
9770    ranged breakpoints.  */
9771
9772 static void
9773 print_mention_ranged_breakpoint (struct breakpoint *b)
9774 {
9775   struct bp_location *bl = b->loc;
9776   struct ui_out *uiout = current_uiout;
9777
9778   gdb_assert (bl);
9779   gdb_assert (b->type == bp_hardware_breakpoint);
9780
9781   uiout->message (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9782                   b->number, paddress (bl->gdbarch, bl->address),
9783                   paddress (bl->gdbarch, bl->address + bl->length - 1));
9784 }
9785
9786 /* Implement the "print_recreate" breakpoint_ops method for
9787    ranged breakpoints.  */
9788
9789 static void
9790 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9791 {
9792   fprintf_unfiltered (fp, "break-range %s, %s",
9793                       event_location_to_string (b->location.get ()),
9794                       event_location_to_string (b->location_range_end.get ()));
9795   print_recreate_thread (b, fp);
9796 }
9797
9798 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9799
9800 static struct breakpoint_ops ranged_breakpoint_ops;
9801
9802 /* Find the address where the end of the breakpoint range should be
9803    placed, given the SAL of the end of the range.  This is so that if
9804    the user provides a line number, the end of the range is set to the
9805    last instruction of the given line.  */
9806
9807 static CORE_ADDR
9808 find_breakpoint_range_end (struct symtab_and_line sal)
9809 {
9810   CORE_ADDR end;
9811
9812   /* If the user provided a PC value, use it.  Otherwise,
9813      find the address of the end of the given location.  */
9814   if (sal.explicit_pc)
9815     end = sal.pc;
9816   else
9817     {
9818       int ret;
9819       CORE_ADDR start;
9820
9821       ret = find_line_pc_range (sal, &start, &end);
9822       if (!ret)
9823         error (_("Could not find location of the end of the range."));
9824
9825       /* find_line_pc_range returns the start of the next line.  */
9826       end--;
9827     }
9828
9829   return end;
9830 }
9831
9832 /* Implement the "break-range" CLI command.  */
9833
9834 static void
9835 break_range_command (const char *arg, int from_tty)
9836 {
9837   const char *arg_start;
9838   struct linespec_result canonical_start, canonical_end;
9839   int bp_count, can_use_bp, length;
9840   CORE_ADDR end;
9841   struct breakpoint *b;
9842
9843   /* We don't support software ranged breakpoints.  */
9844   if (target_ranged_break_num_registers () < 0)
9845     error (_("This target does not support hardware ranged breakpoints."));
9846
9847   bp_count = hw_breakpoint_used_count ();
9848   bp_count += target_ranged_break_num_registers ();
9849   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9850                                                    bp_count, 0);
9851   if (can_use_bp < 0)
9852     error (_("Hardware breakpoints used exceeds limit."));
9853
9854   arg = skip_spaces (arg);
9855   if (arg == NULL || arg[0] == '\0')
9856     error(_("No address range specified."));
9857
9858   arg_start = arg;
9859   event_location_up start_location = string_to_event_location (&arg,
9860                                                                current_language);
9861   parse_breakpoint_sals (start_location.get (), &canonical_start);
9862
9863   if (arg[0] != ',')
9864     error (_("Too few arguments."));
9865   else if (canonical_start.lsals.empty ())
9866     error (_("Could not find location of the beginning of the range."));
9867
9868   const linespec_sals &lsal_start = canonical_start.lsals[0];
9869
9870   if (canonical_start.lsals.size () > 1
9871       || lsal_start.sals.size () != 1)
9872     error (_("Cannot create a ranged breakpoint with multiple locations."));
9873
9874   const symtab_and_line &sal_start = lsal_start.sals[0];
9875   std::string addr_string_start (arg_start, arg - arg_start);
9876
9877   arg++;        /* Skip the comma.  */
9878   arg = skip_spaces (arg);
9879
9880   /* Parse the end location.  */
9881
9882   arg_start = arg;
9883
9884   /* We call decode_line_full directly here instead of using
9885      parse_breakpoint_sals because we need to specify the start location's
9886      symtab and line as the default symtab and line for the end of the
9887      range.  This makes it possible to have ranges like "foo.c:27, +14",
9888      where +14 means 14 lines from the start location.  */
9889   event_location_up end_location = string_to_event_location (&arg,
9890                                                              current_language);
9891   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
9892                     sal_start.symtab, sal_start.line,
9893                     &canonical_end, NULL, NULL);
9894
9895   if (canonical_end.lsals.empty ())
9896     error (_("Could not find location of the end of the range."));
9897
9898   const linespec_sals &lsal_end = canonical_end.lsals[0];
9899   if (canonical_end.lsals.size () > 1
9900       || lsal_end.sals.size () != 1)
9901     error (_("Cannot create a ranged breakpoint with multiple locations."));
9902
9903   const symtab_and_line &sal_end = lsal_end.sals[0];
9904
9905   end = find_breakpoint_range_end (sal_end);
9906   if (sal_start.pc > end)
9907     error (_("Invalid address range, end precedes start."));
9908
9909   length = end - sal_start.pc + 1;
9910   if (length < 0)
9911     /* Length overflowed.  */
9912     error (_("Address range too large."));
9913   else if (length == 1)
9914     {
9915       /* This range is simple enough to be handled by
9916          the `hbreak' command.  */
9917       hbreak_command (&addr_string_start[0], 1);
9918
9919       return;
9920     }
9921
9922   /* Now set up the breakpoint.  */
9923   b = set_raw_breakpoint (get_current_arch (), sal_start,
9924                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
9925   set_breakpoint_count (breakpoint_count + 1);
9926   b->number = breakpoint_count;
9927   b->disposition = disp_donttouch;
9928   b->location = std::move (start_location);
9929   b->location_range_end = std::move (end_location);
9930   b->loc->length = length;
9931
9932   mention (b);
9933   gdb::observers::breakpoint_created.notify (b);
9934   update_global_location_list (UGLL_MAY_INSERT);
9935 }
9936
9937 /*  Return non-zero if EXP is verified as constant.  Returned zero
9938     means EXP is variable.  Also the constant detection may fail for
9939     some constant expressions and in such case still falsely return
9940     zero.  */
9941
9942 static int
9943 watchpoint_exp_is_const (const struct expression *exp)
9944 {
9945   int i = exp->nelts;
9946
9947   while (i > 0)
9948     {
9949       int oplenp, argsp;
9950
9951       /* We are only interested in the descriptor of each element.  */
9952       operator_length (exp, i, &oplenp, &argsp);
9953       i -= oplenp;
9954
9955       switch (exp->elts[i].opcode)
9956         {
9957         case BINOP_ADD:
9958         case BINOP_SUB:
9959         case BINOP_MUL:
9960         case BINOP_DIV:
9961         case BINOP_REM:
9962         case BINOP_MOD:
9963         case BINOP_LSH:
9964         case BINOP_RSH:
9965         case BINOP_LOGICAL_AND:
9966         case BINOP_LOGICAL_OR:
9967         case BINOP_BITWISE_AND:
9968         case BINOP_BITWISE_IOR:
9969         case BINOP_BITWISE_XOR:
9970         case BINOP_EQUAL:
9971         case BINOP_NOTEQUAL:
9972         case BINOP_LESS:
9973         case BINOP_GTR:
9974         case BINOP_LEQ:
9975         case BINOP_GEQ:
9976         case BINOP_REPEAT:
9977         case BINOP_COMMA:
9978         case BINOP_EXP:
9979         case BINOP_MIN:
9980         case BINOP_MAX:
9981         case BINOP_INTDIV:
9982         case BINOP_CONCAT:
9983         case TERNOP_COND:
9984         case TERNOP_SLICE:
9985
9986         case OP_LONG:
9987         case OP_FLOAT:
9988         case OP_LAST:
9989         case OP_COMPLEX:
9990         case OP_STRING:
9991         case OP_ARRAY:
9992         case OP_TYPE:
9993         case OP_TYPEOF:
9994         case OP_DECLTYPE:
9995         case OP_TYPEID:
9996         case OP_NAME:
9997         case OP_OBJC_NSSTRING:
9998
9999         case UNOP_NEG:
10000         case UNOP_LOGICAL_NOT:
10001         case UNOP_COMPLEMENT:
10002         case UNOP_ADDR:
10003         case UNOP_HIGH:
10004         case UNOP_CAST:
10005
10006         case UNOP_CAST_TYPE:
10007         case UNOP_REINTERPRET_CAST:
10008         case UNOP_DYNAMIC_CAST:
10009           /* Unary, binary and ternary operators: We have to check
10010              their operands.  If they are constant, then so is the
10011              result of that operation.  For instance, if A and B are
10012              determined to be constants, then so is "A + B".
10013
10014              UNOP_IND is one exception to the rule above, because the
10015              value of *ADDR is not necessarily a constant, even when
10016              ADDR is.  */
10017           break;
10018
10019         case OP_VAR_VALUE:
10020           /* Check whether the associated symbol is a constant.
10021
10022              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10023              possible that a buggy compiler could mark a variable as
10024              constant even when it is not, and TYPE_CONST would return
10025              true in this case, while SYMBOL_CLASS wouldn't.
10026
10027              We also have to check for function symbols because they
10028              are always constant.  */
10029           {
10030             struct symbol *s = exp->elts[i + 2].symbol;
10031
10032             if (SYMBOL_CLASS (s) != LOC_BLOCK
10033                 && SYMBOL_CLASS (s) != LOC_CONST
10034                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10035               return 0;
10036             break;
10037           }
10038
10039         /* The default action is to return 0 because we are using
10040            the optimistic approach here: If we don't know something,
10041            then it is not a constant.  */
10042         default:
10043           return 0;
10044         }
10045     }
10046
10047   return 1;
10048 }
10049
10050 /* Watchpoint destructor.  */
10051
10052 watchpoint::~watchpoint ()
10053 {
10054   xfree (this->exp_string);
10055   xfree (this->exp_string_reparse);
10056 }
10057
10058 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10059
10060 static void
10061 re_set_watchpoint (struct breakpoint *b)
10062 {
10063   struct watchpoint *w = (struct watchpoint *) b;
10064
10065   /* Watchpoint can be either on expression using entirely global
10066      variables, or it can be on local variables.
10067
10068      Watchpoints of the first kind are never auto-deleted, and even
10069      persist across program restarts.  Since they can use variables
10070      from shared libraries, we need to reparse expression as libraries
10071      are loaded and unloaded.
10072
10073      Watchpoints on local variables can also change meaning as result
10074      of solib event.  For example, if a watchpoint uses both a local
10075      and a global variables in expression, it's a local watchpoint,
10076      but unloading of a shared library will make the expression
10077      invalid.  This is not a very common use case, but we still
10078      re-evaluate expression, to avoid surprises to the user.
10079
10080      Note that for local watchpoints, we re-evaluate it only if
10081      watchpoints frame id is still valid.  If it's not, it means the
10082      watchpoint is out of scope and will be deleted soon.  In fact,
10083      I'm not sure we'll ever be called in this case.
10084
10085      If a local watchpoint's frame id is still valid, then
10086      w->exp_valid_block is likewise valid, and we can safely use it.
10087
10088      Don't do anything about disabled watchpoints, since they will be
10089      reevaluated again when enabled.  */
10090   update_watchpoint (w, 1 /* reparse */);
10091 }
10092
10093 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10094
10095 static int
10096 insert_watchpoint (struct bp_location *bl)
10097 {
10098   struct watchpoint *w = (struct watchpoint *) bl->owner;
10099   int length = w->exact ? 1 : bl->length;
10100
10101   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10102                                    w->cond_exp.get ());
10103 }
10104
10105 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10106
10107 static int
10108 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10109 {
10110   struct watchpoint *w = (struct watchpoint *) bl->owner;
10111   int length = w->exact ? 1 : bl->length;
10112
10113   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10114                                    w->cond_exp.get ());
10115 }
10116
10117 static int
10118 breakpoint_hit_watchpoint (const struct bp_location *bl,
10119                            const address_space *aspace, CORE_ADDR bp_addr,
10120                            const struct target_waitstatus *ws)
10121 {
10122   struct breakpoint *b = bl->owner;
10123   struct watchpoint *w = (struct watchpoint *) b;
10124
10125   /* Continuable hardware watchpoints are treated as non-existent if the
10126      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10127      some data address).  Otherwise gdb won't stop on a break instruction
10128      in the code (not from a breakpoint) when a hardware watchpoint has
10129      been defined.  Also skip watchpoints which we know did not trigger
10130      (did not match the data address).  */
10131   if (is_hardware_watchpoint (b)
10132       && w->watchpoint_triggered == watch_triggered_no)
10133     return 0;
10134
10135   return 1;
10136 }
10137
10138 static void
10139 check_status_watchpoint (bpstat bs)
10140 {
10141   gdb_assert (is_watchpoint (bs->breakpoint_at));
10142
10143   bpstat_check_watchpoint (bs);
10144 }
10145
10146 /* Implement the "resources_needed" breakpoint_ops method for
10147    hardware watchpoints.  */
10148
10149 static int
10150 resources_needed_watchpoint (const struct bp_location *bl)
10151 {
10152   struct watchpoint *w = (struct watchpoint *) bl->owner;
10153   int length = w->exact? 1 : bl->length;
10154
10155   return target_region_ok_for_hw_watchpoint (bl->address, length);
10156 }
10157
10158 /* Implement the "works_in_software_mode" breakpoint_ops method for
10159    hardware watchpoints.  */
10160
10161 static int
10162 works_in_software_mode_watchpoint (const struct breakpoint *b)
10163 {
10164   /* Read and access watchpoints only work with hardware support.  */
10165   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10166 }
10167
10168 static enum print_stop_action
10169 print_it_watchpoint (bpstat bs)
10170 {
10171   struct breakpoint *b;
10172   enum print_stop_action result;
10173   struct watchpoint *w;
10174   struct ui_out *uiout = current_uiout;
10175
10176   gdb_assert (bs->bp_location_at != NULL);
10177
10178   b = bs->breakpoint_at;
10179   w = (struct watchpoint *) b;
10180
10181   annotate_watchpoint (b->number);
10182   maybe_print_thread_hit_breakpoint (uiout);
10183
10184   string_file stb;
10185
10186   gdb::optional<ui_out_emit_tuple> tuple_emitter;
10187   switch (b->type)
10188     {
10189     case bp_watchpoint:
10190     case bp_hardware_watchpoint:
10191       if (uiout->is_mi_like_p ())
10192         uiout->field_string
10193           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10194       mention (b);
10195       tuple_emitter.emplace (uiout, "value");
10196       uiout->text ("\nOld value = ");
10197       watchpoint_value_print (bs->old_val.get (), &stb);
10198       uiout->field_stream ("old", stb);
10199       uiout->text ("\nNew value = ");
10200       watchpoint_value_print (w->val.get (), &stb);
10201       uiout->field_stream ("new", stb);
10202       uiout->text ("\n");
10203       /* More than one watchpoint may have been triggered.  */
10204       result = PRINT_UNKNOWN;
10205       break;
10206
10207     case bp_read_watchpoint:
10208       if (uiout->is_mi_like_p ())
10209         uiout->field_string
10210           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10211       mention (b);
10212       tuple_emitter.emplace (uiout, "value");
10213       uiout->text ("\nValue = ");
10214       watchpoint_value_print (w->val.get (), &stb);
10215       uiout->field_stream ("value", stb);
10216       uiout->text ("\n");
10217       result = PRINT_UNKNOWN;
10218       break;
10219
10220     case bp_access_watchpoint:
10221       if (bs->old_val != NULL)
10222         {
10223           if (uiout->is_mi_like_p ())
10224             uiout->field_string
10225               ("reason",
10226                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10227           mention (b);
10228           tuple_emitter.emplace (uiout, "value");
10229           uiout->text ("\nOld value = ");
10230           watchpoint_value_print (bs->old_val.get (), &stb);
10231           uiout->field_stream ("old", stb);
10232           uiout->text ("\nNew value = ");
10233         }
10234       else
10235         {
10236           mention (b);
10237           if (uiout->is_mi_like_p ())
10238             uiout->field_string
10239               ("reason",
10240                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10241           tuple_emitter.emplace (uiout, "value");
10242           uiout->text ("\nValue = ");
10243         }
10244       watchpoint_value_print (w->val.get (), &stb);
10245       uiout->field_stream ("new", stb);
10246       uiout->text ("\n");
10247       result = PRINT_UNKNOWN;
10248       break;
10249     default:
10250       result = PRINT_UNKNOWN;
10251     }
10252
10253   return result;
10254 }
10255
10256 /* Implement the "print_mention" breakpoint_ops method for hardware
10257    watchpoints.  */
10258
10259 static void
10260 print_mention_watchpoint (struct breakpoint *b)
10261 {
10262   struct watchpoint *w = (struct watchpoint *) b;
10263   struct ui_out *uiout = current_uiout;
10264   const char *tuple_name;
10265
10266   switch (b->type)
10267     {
10268     case bp_watchpoint:
10269       uiout->text ("Watchpoint ");
10270       tuple_name = "wpt";
10271       break;
10272     case bp_hardware_watchpoint:
10273       uiout->text ("Hardware watchpoint ");
10274       tuple_name = "wpt";
10275       break;
10276     case bp_read_watchpoint:
10277       uiout->text ("Hardware read watchpoint ");
10278       tuple_name = "hw-rwpt";
10279       break;
10280     case bp_access_watchpoint:
10281       uiout->text ("Hardware access (read/write) watchpoint ");
10282       tuple_name = "hw-awpt";
10283       break;
10284     default:
10285       internal_error (__FILE__, __LINE__,
10286                       _("Invalid hardware watchpoint type."));
10287     }
10288
10289   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10290   uiout->field_int ("number", b->number);
10291   uiout->text (": ");
10292   uiout->field_string ("exp", w->exp_string);
10293 }
10294
10295 /* Implement the "print_recreate" breakpoint_ops method for
10296    watchpoints.  */
10297
10298 static void
10299 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10300 {
10301   struct watchpoint *w = (struct watchpoint *) b;
10302
10303   switch (b->type)
10304     {
10305     case bp_watchpoint:
10306     case bp_hardware_watchpoint:
10307       fprintf_unfiltered (fp, "watch");
10308       break;
10309     case bp_read_watchpoint:
10310       fprintf_unfiltered (fp, "rwatch");
10311       break;
10312     case bp_access_watchpoint:
10313       fprintf_unfiltered (fp, "awatch");
10314       break;
10315     default:
10316       internal_error (__FILE__, __LINE__,
10317                       _("Invalid watchpoint type."));
10318     }
10319
10320   fprintf_unfiltered (fp, " %s", w->exp_string);
10321   print_recreate_thread (b, fp);
10322 }
10323
10324 /* Implement the "explains_signal" breakpoint_ops method for
10325    watchpoints.  */
10326
10327 static int
10328 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10329 {
10330   /* A software watchpoint cannot cause a signal other than
10331      GDB_SIGNAL_TRAP.  */
10332   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10333     return 0;
10334
10335   return 1;
10336 }
10337
10338 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10339
10340 static struct breakpoint_ops watchpoint_breakpoint_ops;
10341
10342 /* Implement the "insert" breakpoint_ops method for
10343    masked hardware watchpoints.  */
10344
10345 static int
10346 insert_masked_watchpoint (struct bp_location *bl)
10347 {
10348   struct watchpoint *w = (struct watchpoint *) bl->owner;
10349
10350   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10351                                         bl->watchpoint_type);
10352 }
10353
10354 /* Implement the "remove" breakpoint_ops method for
10355    masked hardware watchpoints.  */
10356
10357 static int
10358 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10359 {
10360   struct watchpoint *w = (struct watchpoint *) bl->owner;
10361
10362   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10363                                         bl->watchpoint_type);
10364 }
10365
10366 /* Implement the "resources_needed" breakpoint_ops method for
10367    masked hardware watchpoints.  */
10368
10369 static int
10370 resources_needed_masked_watchpoint (const struct bp_location *bl)
10371 {
10372   struct watchpoint *w = (struct watchpoint *) bl->owner;
10373
10374   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10375 }
10376
10377 /* Implement the "works_in_software_mode" breakpoint_ops method for
10378    masked hardware watchpoints.  */
10379
10380 static int
10381 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10382 {
10383   return 0;
10384 }
10385
10386 /* Implement the "print_it" breakpoint_ops method for
10387    masked hardware watchpoints.  */
10388
10389 static enum print_stop_action
10390 print_it_masked_watchpoint (bpstat bs)
10391 {
10392   struct breakpoint *b = bs->breakpoint_at;
10393   struct ui_out *uiout = current_uiout;
10394
10395   /* Masked watchpoints have only one location.  */
10396   gdb_assert (b->loc && b->loc->next == NULL);
10397
10398   annotate_watchpoint (b->number);
10399   maybe_print_thread_hit_breakpoint (uiout);
10400
10401   switch (b->type)
10402     {
10403     case bp_hardware_watchpoint:
10404       if (uiout->is_mi_like_p ())
10405         uiout->field_string
10406           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10407       break;
10408
10409     case bp_read_watchpoint:
10410       if (uiout->is_mi_like_p ())
10411         uiout->field_string
10412           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10413       break;
10414
10415     case bp_access_watchpoint:
10416       if (uiout->is_mi_like_p ())
10417         uiout->field_string
10418           ("reason",
10419            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10420       break;
10421     default:
10422       internal_error (__FILE__, __LINE__,
10423                       _("Invalid hardware watchpoint type."));
10424     }
10425
10426   mention (b);
10427   uiout->text (_("\n\
10428 Check the underlying instruction at PC for the memory\n\
10429 address and value which triggered this watchpoint.\n"));
10430   uiout->text ("\n");
10431
10432   /* More than one watchpoint may have been triggered.  */
10433   return PRINT_UNKNOWN;
10434 }
10435
10436 /* Implement the "print_one_detail" breakpoint_ops method for
10437    masked hardware watchpoints.  */
10438
10439 static void
10440 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10441                                     struct ui_out *uiout)
10442 {
10443   struct watchpoint *w = (struct watchpoint *) b;
10444
10445   /* Masked watchpoints have only one location.  */
10446   gdb_assert (b->loc && b->loc->next == NULL);
10447
10448   uiout->text ("\tmask ");
10449   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10450   uiout->text ("\n");
10451 }
10452
10453 /* Implement the "print_mention" breakpoint_ops method for
10454    masked hardware watchpoints.  */
10455
10456 static void
10457 print_mention_masked_watchpoint (struct breakpoint *b)
10458 {
10459   struct watchpoint *w = (struct watchpoint *) b;
10460   struct ui_out *uiout = current_uiout;
10461   const char *tuple_name;
10462
10463   switch (b->type)
10464     {
10465     case bp_hardware_watchpoint:
10466       uiout->text ("Masked hardware watchpoint ");
10467       tuple_name = "wpt";
10468       break;
10469     case bp_read_watchpoint:
10470       uiout->text ("Masked hardware read watchpoint ");
10471       tuple_name = "hw-rwpt";
10472       break;
10473     case bp_access_watchpoint:
10474       uiout->text ("Masked hardware access (read/write) watchpoint ");
10475       tuple_name = "hw-awpt";
10476       break;
10477     default:
10478       internal_error (__FILE__, __LINE__,
10479                       _("Invalid hardware watchpoint type."));
10480     }
10481
10482   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10483   uiout->field_int ("number", b->number);
10484   uiout->text (": ");
10485   uiout->field_string ("exp", w->exp_string);
10486 }
10487
10488 /* Implement the "print_recreate" breakpoint_ops method for
10489    masked hardware watchpoints.  */
10490
10491 static void
10492 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10493 {
10494   struct watchpoint *w = (struct watchpoint *) b;
10495   char tmp[40];
10496
10497   switch (b->type)
10498     {
10499     case bp_hardware_watchpoint:
10500       fprintf_unfiltered (fp, "watch");
10501       break;
10502     case bp_read_watchpoint:
10503       fprintf_unfiltered (fp, "rwatch");
10504       break;
10505     case bp_access_watchpoint:
10506       fprintf_unfiltered (fp, "awatch");
10507       break;
10508     default:
10509       internal_error (__FILE__, __LINE__,
10510                       _("Invalid hardware watchpoint type."));
10511     }
10512
10513   sprintf_vma (tmp, w->hw_wp_mask);
10514   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10515   print_recreate_thread (b, fp);
10516 }
10517
10518 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10519
10520 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10521
10522 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10523
10524 static int
10525 is_masked_watchpoint (const struct breakpoint *b)
10526 {
10527   return b->ops == &masked_watchpoint_breakpoint_ops;
10528 }
10529
10530 /* accessflag:  hw_write:  watch write, 
10531                 hw_read:   watch read, 
10532                 hw_access: watch access (read or write) */
10533 static void
10534 watch_command_1 (const char *arg, int accessflag, int from_tty,
10535                  int just_location, int internal)
10536 {
10537   struct breakpoint *scope_breakpoint = NULL;
10538   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10539   struct value *mark, *result;
10540   int saved_bitpos = 0, saved_bitsize = 0;
10541   const char *exp_start = NULL;
10542   const char *exp_end = NULL;
10543   const char *tok, *end_tok;
10544   int toklen = -1;
10545   const char *cond_start = NULL;
10546   const char *cond_end = NULL;
10547   enum bptype bp_type;
10548   int thread = -1;
10549   int pc = 0;
10550   /* Flag to indicate whether we are going to use masks for
10551      the hardware watchpoint.  */
10552   int use_mask = 0;
10553   CORE_ADDR mask = 0;
10554
10555   /* Make sure that we actually have parameters to parse.  */
10556   if (arg != NULL && arg[0] != '\0')
10557     {
10558       const char *value_start;
10559
10560       exp_end = arg + strlen (arg);
10561
10562       /* Look for "parameter value" pairs at the end
10563          of the arguments string.  */
10564       for (tok = exp_end - 1; tok > arg; tok--)
10565         {
10566           /* Skip whitespace at the end of the argument list.  */
10567           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10568             tok--;
10569
10570           /* Find the beginning of the last token.
10571              This is the value of the parameter.  */
10572           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10573             tok--;
10574           value_start = tok + 1;
10575
10576           /* Skip whitespace.  */
10577           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10578             tok--;
10579
10580           end_tok = tok;
10581
10582           /* Find the beginning of the second to last token.
10583              This is the parameter itself.  */
10584           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10585             tok--;
10586           tok++;
10587           toklen = end_tok - tok + 1;
10588
10589           if (toklen == 6 && startswith (tok, "thread"))
10590             {
10591               struct thread_info *thr;
10592               /* At this point we've found a "thread" token, which means
10593                  the user is trying to set a watchpoint that triggers
10594                  only in a specific thread.  */
10595               const char *endp;
10596
10597               if (thread != -1)
10598                 error(_("You can specify only one thread."));
10599
10600               /* Extract the thread ID from the next token.  */
10601               thr = parse_thread_id (value_start, &endp);
10602
10603               /* Check if the user provided a valid thread ID.  */
10604               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10605                 invalid_thread_id_error (value_start);
10606
10607               thread = thr->global_num;
10608             }
10609           else if (toklen == 4 && startswith (tok, "mask"))
10610             {
10611               /* We've found a "mask" token, which means the user wants to
10612                  create a hardware watchpoint that is going to have the mask
10613                  facility.  */
10614               struct value *mask_value, *mark;
10615
10616               if (use_mask)
10617                 error(_("You can specify only one mask."));
10618
10619               use_mask = just_location = 1;
10620
10621               mark = value_mark ();
10622               mask_value = parse_to_comma_and_eval (&value_start);
10623               mask = value_as_address (mask_value);
10624               value_free_to_mark (mark);
10625             }
10626           else
10627             /* We didn't recognize what we found.  We should stop here.  */
10628             break;
10629
10630           /* Truncate the string and get rid of the "parameter value" pair before
10631              the arguments string is parsed by the parse_exp_1 function.  */
10632           exp_end = tok;
10633         }
10634     }
10635   else
10636     exp_end = arg;
10637
10638   /* Parse the rest of the arguments.  From here on out, everything
10639      is in terms of a newly allocated string instead of the original
10640      ARG.  */
10641   innermost_block.reset ();
10642   std::string expression (arg, exp_end - arg);
10643   exp_start = arg = expression.c_str ();
10644   expression_up exp = parse_exp_1 (&arg, 0, 0, 0);
10645   exp_end = arg;
10646   /* Remove trailing whitespace from the expression before saving it.
10647      This makes the eventual display of the expression string a bit
10648      prettier.  */
10649   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10650     --exp_end;
10651
10652   /* Checking if the expression is not constant.  */
10653   if (watchpoint_exp_is_const (exp.get ()))
10654     {
10655       int len;
10656
10657       len = exp_end - exp_start;
10658       while (len > 0 && isspace (exp_start[len - 1]))
10659         len--;
10660       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10661     }
10662
10663   exp_valid_block = innermost_block.block ();
10664   mark = value_mark ();
10665   struct value *val_as_value = nullptr;
10666   fetch_subexp_value (exp.get (), &pc, &val_as_value, &result, NULL,
10667                       just_location);
10668
10669   if (val_as_value != NULL && just_location)
10670     {
10671       saved_bitpos = value_bitpos (val_as_value);
10672       saved_bitsize = value_bitsize (val_as_value);
10673     }
10674
10675   value_ref_ptr val;
10676   if (just_location)
10677     {
10678       int ret;
10679
10680       exp_valid_block = NULL;
10681       val = release_value (value_addr (result));
10682       value_free_to_mark (mark);
10683
10684       if (use_mask)
10685         {
10686           ret = target_masked_watch_num_registers (value_as_address (val.get ()),
10687                                                    mask);
10688           if (ret == -1)
10689             error (_("This target does not support masked watchpoints."));
10690           else if (ret == -2)
10691             error (_("Invalid mask or memory region."));
10692         }
10693     }
10694   else if (val_as_value != NULL)
10695     val = release_value (val_as_value);
10696
10697   tok = skip_spaces (arg);
10698   end_tok = skip_to_space (tok);
10699
10700   toklen = end_tok - tok;
10701   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10702     {
10703       innermost_block.reset ();
10704       tok = cond_start = end_tok + 1;
10705       parse_exp_1 (&tok, 0, 0, 0);
10706
10707       /* The watchpoint expression may not be local, but the condition
10708          may still be.  E.g.: `watch global if local > 0'.  */
10709       cond_exp_valid_block = innermost_block.block ();
10710
10711       cond_end = tok;
10712     }
10713   if (*tok)
10714     error (_("Junk at end of command."));
10715
10716   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
10717
10718   /* Save this because create_internal_breakpoint below invalidates
10719      'wp_frame'.  */
10720   frame_id watchpoint_frame = get_frame_id (wp_frame);
10721
10722   /* If the expression is "local", then set up a "watchpoint scope"
10723      breakpoint at the point where we've left the scope of the watchpoint
10724      expression.  Create the scope breakpoint before the watchpoint, so
10725      that we will encounter it first in bpstat_stop_status.  */
10726   if (exp_valid_block != NULL && wp_frame != NULL)
10727     {
10728       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10729
10730       if (frame_id_p (caller_frame_id))
10731         {
10732           gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10733           CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10734
10735           scope_breakpoint
10736             = create_internal_breakpoint (caller_arch, caller_pc,
10737                                           bp_watchpoint_scope,
10738                                           &momentary_breakpoint_ops);
10739
10740           /* create_internal_breakpoint could invalidate WP_FRAME.  */
10741           wp_frame = NULL;
10742
10743           scope_breakpoint->enable_state = bp_enabled;
10744
10745           /* Automatically delete the breakpoint when it hits.  */
10746           scope_breakpoint->disposition = disp_del;
10747
10748           /* Only break in the proper frame (help with recursion).  */
10749           scope_breakpoint->frame_id = caller_frame_id;
10750
10751           /* Set the address at which we will stop.  */
10752           scope_breakpoint->loc->gdbarch = caller_arch;
10753           scope_breakpoint->loc->requested_address = caller_pc;
10754           scope_breakpoint->loc->address
10755             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10756                                          scope_breakpoint->loc->requested_address,
10757                                          scope_breakpoint->type);
10758         }
10759     }
10760
10761   /* Now set up the breakpoint.  We create all watchpoints as hardware
10762      watchpoints here even if hardware watchpoints are turned off, a call
10763      to update_watchpoint later in this function will cause the type to
10764      drop back to bp_watchpoint (software watchpoint) if required.  */
10765
10766   if (accessflag == hw_read)
10767     bp_type = bp_read_watchpoint;
10768   else if (accessflag == hw_access)
10769     bp_type = bp_access_watchpoint;
10770   else
10771     bp_type = bp_hardware_watchpoint;
10772
10773   std::unique_ptr<watchpoint> w (new watchpoint ());
10774
10775   if (use_mask)
10776     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10777                                           &masked_watchpoint_breakpoint_ops);
10778   else
10779     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10780                                           &watchpoint_breakpoint_ops);
10781   w->thread = thread;
10782   w->disposition = disp_donttouch;
10783   w->pspace = current_program_space;
10784   w->exp = std::move (exp);
10785   w->exp_valid_block = exp_valid_block;
10786   w->cond_exp_valid_block = cond_exp_valid_block;
10787   if (just_location)
10788     {
10789       struct type *t = value_type (val.get ());
10790       CORE_ADDR addr = value_as_address (val.get ());
10791
10792       w->exp_string_reparse
10793         = current_language->la_watch_location_expression (t, addr).release ();
10794
10795       w->exp_string = xstrprintf ("-location %.*s",
10796                                   (int) (exp_end - exp_start), exp_start);
10797     }
10798   else
10799     w->exp_string = savestring (exp_start, exp_end - exp_start);
10800
10801   if (use_mask)
10802     {
10803       w->hw_wp_mask = mask;
10804     }
10805   else
10806     {
10807       w->val = val;
10808       w->val_bitpos = saved_bitpos;
10809       w->val_bitsize = saved_bitsize;
10810       w->val_valid = 1;
10811     }
10812
10813   if (cond_start)
10814     w->cond_string = savestring (cond_start, cond_end - cond_start);
10815   else
10816     w->cond_string = 0;
10817
10818   if (frame_id_p (watchpoint_frame))
10819     {
10820       w->watchpoint_frame = watchpoint_frame;
10821       w->watchpoint_thread = inferior_ptid;
10822     }
10823   else
10824     {
10825       w->watchpoint_frame = null_frame_id;
10826       w->watchpoint_thread = null_ptid;
10827     }
10828
10829   if (scope_breakpoint != NULL)
10830     {
10831       /* The scope breakpoint is related to the watchpoint.  We will
10832          need to act on them together.  */
10833       w->related_breakpoint = scope_breakpoint;
10834       scope_breakpoint->related_breakpoint = w.get ();
10835     }
10836
10837   if (!just_location)
10838     value_free_to_mark (mark);
10839
10840   /* Finally update the new watchpoint.  This creates the locations
10841      that should be inserted.  */
10842   update_watchpoint (w.get (), 1);
10843
10844   install_breakpoint (internal, std::move (w), 1);
10845 }
10846
10847 /* Return count of debug registers needed to watch the given expression.
10848    If the watchpoint cannot be handled in hardware return zero.  */
10849
10850 static int
10851 can_use_hardware_watchpoint (const std::vector<value_ref_ptr> &vals)
10852 {
10853   int found_memory_cnt = 0;
10854
10855   /* Did the user specifically forbid us to use hardware watchpoints? */
10856   if (!can_use_hw_watchpoints)
10857     return 0;
10858
10859   gdb_assert (!vals.empty ());
10860   struct value *head = vals[0].get ();
10861
10862   /* Make sure that the value of the expression depends only upon
10863      memory contents, and values computed from them within GDB.  If we
10864      find any register references or function calls, we can't use a
10865      hardware watchpoint.
10866
10867      The idea here is that evaluating an expression generates a series
10868      of values, one holding the value of every subexpression.  (The
10869      expression a*b+c has five subexpressions: a, b, a*b, c, and
10870      a*b+c.)  GDB's values hold almost enough information to establish
10871      the criteria given above --- they identify memory lvalues,
10872      register lvalues, computed values, etcetera.  So we can evaluate
10873      the expression, and then scan the chain of values that leaves
10874      behind to decide whether we can detect any possible change to the
10875      expression's final value using only hardware watchpoints.
10876
10877      However, I don't think that the values returned by inferior
10878      function calls are special in any way.  So this function may not
10879      notice that an expression involving an inferior function call
10880      can't be watched with hardware watchpoints.  FIXME.  */
10881   for (const value_ref_ptr &iter : vals)
10882     {
10883       struct value *v = iter.get ();
10884
10885       if (VALUE_LVAL (v) == lval_memory)
10886         {
10887           if (v != head && value_lazy (v))
10888             /* A lazy memory lvalue in the chain is one that GDB never
10889                needed to fetch; we either just used its address (e.g.,
10890                `a' in `a.b') or we never needed it at all (e.g., `a'
10891                in `a,b').  This doesn't apply to HEAD; if that is
10892                lazy then it was not readable, but watch it anyway.  */
10893             ;
10894           else
10895             {
10896               /* Ahh, memory we actually used!  Check if we can cover
10897                  it with hardware watchpoints.  */
10898               struct type *vtype = check_typedef (value_type (v));
10899
10900               /* We only watch structs and arrays if user asked for it
10901                  explicitly, never if they just happen to appear in a
10902                  middle of some value chain.  */
10903               if (v == head
10904                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
10905                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
10906                 {
10907                   CORE_ADDR vaddr = value_address (v);
10908                   int len;
10909                   int num_regs;
10910
10911                   len = (target_exact_watchpoints
10912                          && is_scalar_type_recursive (vtype))?
10913                     1 : TYPE_LENGTH (value_type (v));
10914
10915                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10916                   if (!num_regs)
10917                     return 0;
10918                   else
10919                     found_memory_cnt += num_regs;
10920                 }
10921             }
10922         }
10923       else if (VALUE_LVAL (v) != not_lval
10924                && deprecated_value_modifiable (v) == 0)
10925         return 0;       /* These are values from the history (e.g., $1).  */
10926       else if (VALUE_LVAL (v) == lval_register)
10927         return 0;       /* Cannot watch a register with a HW watchpoint.  */
10928     }
10929
10930   /* The expression itself looks suitable for using a hardware
10931      watchpoint, but give the target machine a chance to reject it.  */
10932   return found_memory_cnt;
10933 }
10934
10935 void
10936 watch_command_wrapper (const char *arg, int from_tty, int internal)
10937 {
10938   watch_command_1 (arg, hw_write, from_tty, 0, internal);
10939 }
10940
10941 /* A helper function that looks for the "-location" argument and then
10942    calls watch_command_1.  */
10943
10944 static void
10945 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
10946 {
10947   int just_location = 0;
10948
10949   if (arg
10950       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
10951           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
10952     {
10953       arg = skip_spaces (arg);
10954       just_location = 1;
10955     }
10956
10957   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
10958 }
10959
10960 static void
10961 watch_command (const char *arg, int from_tty)
10962 {
10963   watch_maybe_just_location (arg, hw_write, from_tty);
10964 }
10965
10966 void
10967 rwatch_command_wrapper (const char *arg, int from_tty, int internal)
10968 {
10969   watch_command_1 (arg, hw_read, from_tty, 0, internal);
10970 }
10971
10972 static void
10973 rwatch_command (const char *arg, int from_tty)
10974 {
10975   watch_maybe_just_location (arg, hw_read, from_tty);
10976 }
10977
10978 void
10979 awatch_command_wrapper (const char *arg, int from_tty, int internal)
10980 {
10981   watch_command_1 (arg, hw_access, from_tty, 0, internal);
10982 }
10983
10984 static void
10985 awatch_command (const char *arg, int from_tty)
10986 {
10987   watch_maybe_just_location (arg, hw_access, from_tty);
10988 }
10989 \f
10990
10991 /* Data for the FSM that manages the until(location)/advance commands
10992    in infcmd.c.  Here because it uses the mechanisms of
10993    breakpoints.  */
10994
10995 struct until_break_fsm
10996 {
10997   /* The base class.  */
10998   struct thread_fsm thread_fsm;
10999
11000   /* The thread that as current when the command was executed.  */
11001   int thread;
11002
11003   /* The breakpoint set at the destination location.  */
11004   struct breakpoint *location_breakpoint;
11005
11006   /* Breakpoint set at the return address in the caller frame.  May be
11007      NULL.  */
11008   struct breakpoint *caller_breakpoint;
11009 };
11010
11011 static void until_break_fsm_clean_up (struct thread_fsm *self,
11012                                       struct thread_info *thread);
11013 static int until_break_fsm_should_stop (struct thread_fsm *self,
11014                                         struct thread_info *thread);
11015 static enum async_reply_reason
11016   until_break_fsm_async_reply_reason (struct thread_fsm *self);
11017
11018 /* until_break_fsm's vtable.  */
11019
11020 static struct thread_fsm_ops until_break_fsm_ops =
11021 {
11022   NULL, /* dtor */
11023   until_break_fsm_clean_up,
11024   until_break_fsm_should_stop,
11025   NULL, /* return_value */
11026   until_break_fsm_async_reply_reason,
11027 };
11028
11029 /* Allocate a new until_break_command_fsm.  */
11030
11031 static struct until_break_fsm *
11032 new_until_break_fsm (struct interp *cmd_interp, int thread,
11033                      breakpoint_up &&location_breakpoint,
11034                      breakpoint_up &&caller_breakpoint)
11035 {
11036   struct until_break_fsm *sm;
11037
11038   sm = XCNEW (struct until_break_fsm);
11039   thread_fsm_ctor (&sm->thread_fsm, &until_break_fsm_ops, cmd_interp);
11040
11041   sm->thread = thread;
11042   sm->location_breakpoint = location_breakpoint.release ();
11043   sm->caller_breakpoint = caller_breakpoint.release ();
11044
11045   return sm;
11046 }
11047
11048 /* Implementation of the 'should_stop' FSM method for the
11049    until(location)/advance commands.  */
11050
11051 static int
11052 until_break_fsm_should_stop (struct thread_fsm *self,
11053                              struct thread_info *tp)
11054 {
11055   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11056
11057   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11058                               sm->location_breakpoint) != NULL
11059       || (sm->caller_breakpoint != NULL
11060           && bpstat_find_breakpoint (tp->control.stop_bpstat,
11061                                      sm->caller_breakpoint) != NULL))
11062     thread_fsm_set_finished (self);
11063
11064   return 1;
11065 }
11066
11067 /* Implementation of the 'clean_up' FSM method for the
11068    until(location)/advance commands.  */
11069
11070 static void
11071 until_break_fsm_clean_up (struct thread_fsm *self,
11072                           struct thread_info *thread)
11073 {
11074   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11075
11076   /* Clean up our temporary breakpoints.  */
11077   if (sm->location_breakpoint != NULL)
11078     {
11079       delete_breakpoint (sm->location_breakpoint);
11080       sm->location_breakpoint = NULL;
11081     }
11082   if (sm->caller_breakpoint != NULL)
11083     {
11084       delete_breakpoint (sm->caller_breakpoint);
11085       sm->caller_breakpoint = NULL;
11086     }
11087   delete_longjmp_breakpoint (sm->thread);
11088 }
11089
11090 /* Implementation of the 'async_reply_reason' FSM method for the
11091    until(location)/advance commands.  */
11092
11093 static enum async_reply_reason
11094 until_break_fsm_async_reply_reason (struct thread_fsm *self)
11095 {
11096   return EXEC_ASYNC_LOCATION_REACHED;
11097 }
11098
11099 void
11100 until_break_command (const char *arg, int from_tty, int anywhere)
11101 {
11102   struct frame_info *frame;
11103   struct gdbarch *frame_gdbarch;
11104   struct frame_id stack_frame_id;
11105   struct frame_id caller_frame_id;
11106   struct cleanup *old_chain;
11107   int thread;
11108   struct thread_info *tp;
11109   struct until_break_fsm *sm;
11110
11111   clear_proceed_status (0);
11112
11113   /* Set a breakpoint where the user wants it and at return from
11114      this function.  */
11115
11116   event_location_up location = string_to_event_location (&arg, current_language);
11117
11118   std::vector<symtab_and_line> sals
11119     = (last_displayed_sal_is_valid ()
11120        ? decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
11121                         get_last_displayed_symtab (),
11122                         get_last_displayed_line ())
11123        : decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
11124                         NULL, (struct symtab *) NULL, 0));
11125
11126   if (sals.size () != 1)
11127     error (_("Couldn't get information on specified line."));
11128
11129   symtab_and_line &sal = sals[0];
11130
11131   if (*arg)
11132     error (_("Junk at end of arguments."));
11133
11134   resolve_sal_pc (&sal);
11135
11136   tp = inferior_thread ();
11137   thread = tp->global_num;
11138
11139   old_chain = make_cleanup (null_cleanup, NULL);
11140
11141   /* Note linespec handling above invalidates the frame chain.
11142      Installing a breakpoint also invalidates the frame chain (as it
11143      may need to switch threads), so do any frame handling before
11144      that.  */
11145
11146   frame = get_selected_frame (NULL);
11147   frame_gdbarch = get_frame_arch (frame);
11148   stack_frame_id = get_stack_frame_id (frame);
11149   caller_frame_id = frame_unwind_caller_id (frame);
11150
11151   /* Keep within the current frame, or in frames called by the current
11152      one.  */
11153
11154   breakpoint_up caller_breakpoint;
11155   if (frame_id_p (caller_frame_id))
11156     {
11157       struct symtab_and_line sal2;
11158       struct gdbarch *caller_gdbarch;
11159
11160       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11161       sal2.pc = frame_unwind_caller_pc (frame);
11162       caller_gdbarch = frame_unwind_caller_arch (frame);
11163       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11164                                                     sal2,
11165                                                     caller_frame_id,
11166                                                     bp_until);
11167
11168       set_longjmp_breakpoint (tp, caller_frame_id);
11169       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11170     }
11171
11172   /* set_momentary_breakpoint could invalidate FRAME.  */
11173   frame = NULL;
11174
11175   breakpoint_up location_breakpoint;
11176   if (anywhere)
11177     /* If the user told us to continue until a specified location,
11178        we don't specify a frame at which we need to stop.  */
11179     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11180                                                     null_frame_id, bp_until);
11181   else
11182     /* Otherwise, specify the selected frame, because we want to stop
11183        only at the very same frame.  */
11184     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11185                                                     stack_frame_id, bp_until);
11186
11187   sm = new_until_break_fsm (command_interp (), tp->global_num,
11188                             std::move (location_breakpoint),
11189                             std::move (caller_breakpoint));
11190   tp->thread_fsm = &sm->thread_fsm;
11191
11192   discard_cleanups (old_chain);
11193
11194   proceed (-1, GDB_SIGNAL_DEFAULT);
11195 }
11196
11197 /* This function attempts to parse an optional "if <cond>" clause
11198    from the arg string.  If one is not found, it returns NULL.
11199
11200    Else, it returns a pointer to the condition string.  (It does not
11201    attempt to evaluate the string against a particular block.)  And,
11202    it updates arg to point to the first character following the parsed
11203    if clause in the arg string.  */
11204
11205 const char *
11206 ep_parse_optional_if_clause (const char **arg)
11207 {
11208   const char *cond_string;
11209
11210   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11211     return NULL;
11212
11213   /* Skip the "if" keyword.  */
11214   (*arg) += 2;
11215
11216   /* Skip any extra leading whitespace, and record the start of the
11217      condition string.  */
11218   *arg = skip_spaces (*arg);
11219   cond_string = *arg;
11220
11221   /* Assume that the condition occupies the remainder of the arg
11222      string.  */
11223   (*arg) += strlen (cond_string);
11224
11225   return cond_string;
11226 }
11227
11228 /* Commands to deal with catching events, such as signals, exceptions,
11229    process start/exit, etc.  */
11230
11231 typedef enum
11232 {
11233   catch_fork_temporary, catch_vfork_temporary,
11234   catch_fork_permanent, catch_vfork_permanent
11235 }
11236 catch_fork_kind;
11237
11238 static void
11239 catch_fork_command_1 (const char *arg, int from_tty,
11240                       struct cmd_list_element *command)
11241 {
11242   struct gdbarch *gdbarch = get_current_arch ();
11243   const char *cond_string = NULL;
11244   catch_fork_kind fork_kind;
11245   int tempflag;
11246
11247   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11248   tempflag = (fork_kind == catch_fork_temporary
11249               || fork_kind == catch_vfork_temporary);
11250
11251   if (!arg)
11252     arg = "";
11253   arg = skip_spaces (arg);
11254
11255   /* The allowed syntax is:
11256      catch [v]fork
11257      catch [v]fork if <cond>
11258
11259      First, check if there's an if clause.  */
11260   cond_string = ep_parse_optional_if_clause (&arg);
11261
11262   if ((*arg != '\0') && !isspace (*arg))
11263     error (_("Junk at end of arguments."));
11264
11265   /* If this target supports it, create a fork or vfork catchpoint
11266      and enable reporting of such events.  */
11267   switch (fork_kind)
11268     {
11269     case catch_fork_temporary:
11270     case catch_fork_permanent:
11271       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11272                                           &catch_fork_breakpoint_ops);
11273       break;
11274     case catch_vfork_temporary:
11275     case catch_vfork_permanent:
11276       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11277                                           &catch_vfork_breakpoint_ops);
11278       break;
11279     default:
11280       error (_("unsupported or unknown fork kind; cannot catch it"));
11281       break;
11282     }
11283 }
11284
11285 static void
11286 catch_exec_command_1 (const char *arg, int from_tty,
11287                       struct cmd_list_element *command)
11288 {
11289   struct gdbarch *gdbarch = get_current_arch ();
11290   int tempflag;
11291   const char *cond_string = NULL;
11292
11293   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11294
11295   if (!arg)
11296     arg = "";
11297   arg = skip_spaces (arg);
11298
11299   /* The allowed syntax is:
11300      catch exec
11301      catch exec if <cond>
11302
11303      First, check if there's an if clause.  */
11304   cond_string = ep_parse_optional_if_clause (&arg);
11305
11306   if ((*arg != '\0') && !isspace (*arg))
11307     error (_("Junk at end of arguments."));
11308
11309   std::unique_ptr<exec_catchpoint> c (new exec_catchpoint ());
11310   init_catchpoint (c.get (), gdbarch, tempflag, cond_string,
11311                    &catch_exec_breakpoint_ops);
11312   c->exec_pathname = NULL;
11313
11314   install_breakpoint (0, std::move (c), 1);
11315 }
11316
11317 void
11318 init_ada_exception_breakpoint (struct breakpoint *b,
11319                                struct gdbarch *gdbarch,
11320                                struct symtab_and_line sal,
11321                                const char *addr_string,
11322                                const struct breakpoint_ops *ops,
11323                                int tempflag,
11324                                int enabled,
11325                                int from_tty)
11326 {
11327   if (from_tty)
11328     {
11329       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11330       if (!loc_gdbarch)
11331         loc_gdbarch = gdbarch;
11332
11333       describe_other_breakpoints (loc_gdbarch,
11334                                   sal.pspace, sal.pc, sal.section, -1);
11335       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11336          version for exception catchpoints, because two catchpoints
11337          used for different exception names will use the same address.
11338          In this case, a "breakpoint ... also set at..." warning is
11339          unproductive.  Besides, the warning phrasing is also a bit
11340          inappropriate, we should use the word catchpoint, and tell
11341          the user what type of catchpoint it is.  The above is good
11342          enough for now, though.  */
11343     }
11344
11345   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11346
11347   b->enable_state = enabled ? bp_enabled : bp_disabled;
11348   b->disposition = tempflag ? disp_del : disp_donttouch;
11349   b->location = string_to_event_location (&addr_string,
11350                                           language_def (language_ada));
11351   b->language = language_ada;
11352 }
11353
11354 static void
11355 catch_command (const char *arg, int from_tty)
11356 {
11357   error (_("Catch requires an event name."));
11358 }
11359 \f
11360
11361 static void
11362 tcatch_command (const char *arg, int from_tty)
11363 {
11364   error (_("Catch requires an event name."));
11365 }
11366
11367 /* Compare two breakpoints and return a strcmp-like result.  */
11368
11369 static int
11370 compare_breakpoints (const breakpoint *a, const breakpoint *b)
11371 {
11372   uintptr_t ua = (uintptr_t) a;
11373   uintptr_t ub = (uintptr_t) b;
11374
11375   if (a->number < b->number)
11376     return -1;
11377   else if (a->number > b->number)
11378     return 1;
11379
11380   /* Now sort by address, in case we see, e..g, two breakpoints with
11381      the number 0.  */
11382   if (ua < ub)
11383     return -1;
11384   return ua > ub ? 1 : 0;
11385 }
11386
11387 /* Delete breakpoints by address or line.  */
11388
11389 static void
11390 clear_command (const char *arg, int from_tty)
11391 {
11392   struct breakpoint *b;
11393   int default_match;
11394
11395   std::vector<symtab_and_line> decoded_sals;
11396   symtab_and_line last_sal;
11397   gdb::array_view<symtab_and_line> sals;
11398   if (arg)
11399     {
11400       decoded_sals
11401         = decode_line_with_current_source (arg,
11402                                            (DECODE_LINE_FUNFIRSTLINE
11403                                             | DECODE_LINE_LIST_MODE));
11404       default_match = 0;
11405       sals = decoded_sals;
11406     }
11407   else
11408     {
11409       /* Set sal's line, symtab, pc, and pspace to the values
11410          corresponding to the last call to print_frame_info.  If the
11411          codepoint is not valid, this will set all the fields to 0.  */
11412       last_sal = get_last_displayed_sal ();
11413       if (last_sal.symtab == 0)
11414         error (_("No source file specified."));
11415
11416       default_match = 1;
11417       sals = last_sal;
11418     }
11419
11420   /* We don't call resolve_sal_pc here.  That's not as bad as it
11421      seems, because all existing breakpoints typically have both
11422      file/line and pc set.  So, if clear is given file/line, we can
11423      match this to existing breakpoint without obtaining pc at all.
11424
11425      We only support clearing given the address explicitly 
11426      present in breakpoint table.  Say, we've set breakpoint 
11427      at file:line.  There were several PC values for that file:line,
11428      due to optimization, all in one block.
11429
11430      We've picked one PC value.  If "clear" is issued with another
11431      PC corresponding to the same file:line, the breakpoint won't
11432      be cleared.  We probably can still clear the breakpoint, but 
11433      since the other PC value is never presented to user, user
11434      can only find it by guessing, and it does not seem important
11435      to support that.  */
11436
11437   /* For each line spec given, delete bps which correspond to it.  Do
11438      it in two passes, solely to preserve the current behavior that
11439      from_tty is forced true if we delete more than one
11440      breakpoint.  */
11441
11442   std::vector<struct breakpoint *> found;
11443   for (const auto &sal : sals)
11444     {
11445       const char *sal_fullname;
11446
11447       /* If exact pc given, clear bpts at that pc.
11448          If line given (pc == 0), clear all bpts on specified line.
11449          If defaulting, clear all bpts on default line
11450          or at default pc.
11451
11452          defaulting    sal.pc != 0    tests to do
11453
11454          0              1             pc
11455          1              1             pc _and_ line
11456          0              0             line
11457          1              0             <can't happen> */
11458
11459       sal_fullname = (sal.symtab == NULL
11460                       ? NULL : symtab_to_fullname (sal.symtab));
11461
11462       /* Find all matching breakpoints and add them to 'found'.  */
11463       ALL_BREAKPOINTS (b)
11464         {
11465           int match = 0;
11466           /* Are we going to delete b?  */
11467           if (b->type != bp_none && !is_watchpoint (b))
11468             {
11469               struct bp_location *loc = b->loc;
11470               for (; loc; loc = loc->next)
11471                 {
11472                   /* If the user specified file:line, don't allow a PC
11473                      match.  This matches historical gdb behavior.  */
11474                   int pc_match = (!sal.explicit_line
11475                                   && sal.pc
11476                                   && (loc->pspace == sal.pspace)
11477                                   && (loc->address == sal.pc)
11478                                   && (!section_is_overlay (loc->section)
11479                                       || loc->section == sal.section));
11480                   int line_match = 0;
11481
11482                   if ((default_match || sal.explicit_line)
11483                       && loc->symtab != NULL
11484                       && sal_fullname != NULL
11485                       && sal.pspace == loc->pspace
11486                       && loc->line_number == sal.line
11487                       && filename_cmp (symtab_to_fullname (loc->symtab),
11488                                        sal_fullname) == 0)
11489                     line_match = 1;
11490
11491                   if (pc_match || line_match)
11492                     {
11493                       match = 1;
11494                       break;
11495                     }
11496                 }
11497             }
11498
11499           if (match)
11500             found.push_back (b);
11501         }
11502     }
11503
11504   /* Now go thru the 'found' chain and delete them.  */
11505   if (found.empty ())
11506     {
11507       if (arg)
11508         error (_("No breakpoint at %s."), arg);
11509       else
11510         error (_("No breakpoint at this line."));
11511     }
11512
11513   /* Remove duplicates from the vec.  */
11514   std::sort (found.begin (), found.end (),
11515              [] (const breakpoint *a, const breakpoint *b)
11516              {
11517                return compare_breakpoints (a, b) < 0;
11518              });
11519   found.erase (std::unique (found.begin (), found.end (),
11520                             [] (const breakpoint *a, const breakpoint *b)
11521                             {
11522                               return compare_breakpoints (a, b) == 0;
11523                             }),
11524                found.end ());
11525
11526   if (found.size () > 1)
11527     from_tty = 1;       /* Always report if deleted more than one.  */
11528   if (from_tty)
11529     {
11530       if (found.size () == 1)
11531         printf_unfiltered (_("Deleted breakpoint "));
11532       else
11533         printf_unfiltered (_("Deleted breakpoints "));
11534     }
11535
11536   for (breakpoint *iter : found)
11537     {
11538       if (from_tty)
11539         printf_unfiltered ("%d ", iter->number);
11540       delete_breakpoint (iter);
11541     }
11542   if (from_tty)
11543     putchar_unfiltered ('\n');
11544 }
11545 \f
11546 /* Delete breakpoint in BS if they are `delete' breakpoints and
11547    all breakpoints that are marked for deletion, whether hit or not.
11548    This is called after any breakpoint is hit, or after errors.  */
11549
11550 void
11551 breakpoint_auto_delete (bpstat bs)
11552 {
11553   struct breakpoint *b, *b_tmp;
11554
11555   for (; bs; bs = bs->next)
11556     if (bs->breakpoint_at
11557         && bs->breakpoint_at->disposition == disp_del
11558         && bs->stop)
11559       delete_breakpoint (bs->breakpoint_at);
11560
11561   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11562   {
11563     if (b->disposition == disp_del_at_next_stop)
11564       delete_breakpoint (b);
11565   }
11566 }
11567
11568 /* A comparison function for bp_location AP and BP being interfaced to
11569    qsort.  Sort elements primarily by their ADDRESS (no matter what
11570    does breakpoint_address_is_meaningful say for its OWNER),
11571    secondarily by ordering first permanent elements and
11572    terciarily just ensuring the array is sorted stable way despite
11573    qsort being an unstable algorithm.  */
11574
11575 static int
11576 bp_locations_compare (const void *ap, const void *bp)
11577 {
11578   const struct bp_location *a = *(const struct bp_location **) ap;
11579   const struct bp_location *b = *(const struct bp_location **) bp;
11580
11581   if (a->address != b->address)
11582     return (a->address > b->address) - (a->address < b->address);
11583
11584   /* Sort locations at the same address by their pspace number, keeping
11585      locations of the same inferior (in a multi-inferior environment)
11586      grouped.  */
11587
11588   if (a->pspace->num != b->pspace->num)
11589     return ((a->pspace->num > b->pspace->num)
11590             - (a->pspace->num < b->pspace->num));
11591
11592   /* Sort permanent breakpoints first.  */
11593   if (a->permanent != b->permanent)
11594     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
11595
11596   /* Make the internal GDB representation stable across GDB runs
11597      where A and B memory inside GDB can differ.  Breakpoint locations of
11598      the same type at the same address can be sorted in arbitrary order.  */
11599
11600   if (a->owner->number != b->owner->number)
11601     return ((a->owner->number > b->owner->number)
11602             - (a->owner->number < b->owner->number));
11603
11604   return (a > b) - (a < b);
11605 }
11606
11607 /* Set bp_locations_placed_address_before_address_max and
11608    bp_locations_shadow_len_after_address_max according to the current
11609    content of the bp_locations array.  */
11610
11611 static void
11612 bp_locations_target_extensions_update (void)
11613 {
11614   struct bp_location *bl, **blp_tmp;
11615
11616   bp_locations_placed_address_before_address_max = 0;
11617   bp_locations_shadow_len_after_address_max = 0;
11618
11619   ALL_BP_LOCATIONS (bl, blp_tmp)
11620     {
11621       CORE_ADDR start, end, addr;
11622
11623       if (!bp_location_has_shadow (bl))
11624         continue;
11625
11626       start = bl->target_info.placed_address;
11627       end = start + bl->target_info.shadow_len;
11628
11629       gdb_assert (bl->address >= start);
11630       addr = bl->address - start;
11631       if (addr > bp_locations_placed_address_before_address_max)
11632         bp_locations_placed_address_before_address_max = addr;
11633
11634       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11635
11636       gdb_assert (bl->address < end);
11637       addr = end - bl->address;
11638       if (addr > bp_locations_shadow_len_after_address_max)
11639         bp_locations_shadow_len_after_address_max = addr;
11640     }
11641 }
11642
11643 /* Download tracepoint locations if they haven't been.  */
11644
11645 static void
11646 download_tracepoint_locations (void)
11647 {
11648   struct breakpoint *b;
11649   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11650
11651   scoped_restore_current_pspace_and_thread restore_pspace_thread;
11652
11653   ALL_TRACEPOINTS (b)
11654     {
11655       struct bp_location *bl;
11656       struct tracepoint *t;
11657       int bp_location_downloaded = 0;
11658
11659       if ((b->type == bp_fast_tracepoint
11660            ? !may_insert_fast_tracepoints
11661            : !may_insert_tracepoints))
11662         continue;
11663
11664       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11665         {
11666           if (target_can_download_tracepoint ())
11667             can_download_tracepoint = TRIBOOL_TRUE;
11668           else
11669             can_download_tracepoint = TRIBOOL_FALSE;
11670         }
11671
11672       if (can_download_tracepoint == TRIBOOL_FALSE)
11673         break;
11674
11675       for (bl = b->loc; bl; bl = bl->next)
11676         {
11677           /* In tracepoint, locations are _never_ duplicated, so
11678              should_be_inserted is equivalent to
11679              unduplicated_should_be_inserted.  */
11680           if (!should_be_inserted (bl) || bl->inserted)
11681             continue;
11682
11683           switch_to_program_space_and_thread (bl->pspace);
11684
11685           target_download_tracepoint (bl);
11686
11687           bl->inserted = 1;
11688           bp_location_downloaded = 1;
11689         }
11690       t = (struct tracepoint *) b;
11691       t->number_on_target = b->number;
11692       if (bp_location_downloaded)
11693         gdb::observers::breakpoint_modified.notify (b);
11694     }
11695 }
11696
11697 /* Swap the insertion/duplication state between two locations.  */
11698
11699 static void
11700 swap_insertion (struct bp_location *left, struct bp_location *right)
11701 {
11702   const int left_inserted = left->inserted;
11703   const int left_duplicate = left->duplicate;
11704   const int left_needs_update = left->needs_update;
11705   const struct bp_target_info left_target_info = left->target_info;
11706
11707   /* Locations of tracepoints can never be duplicated.  */
11708   if (is_tracepoint (left->owner))
11709     gdb_assert (!left->duplicate);
11710   if (is_tracepoint (right->owner))
11711     gdb_assert (!right->duplicate);
11712
11713   left->inserted = right->inserted;
11714   left->duplicate = right->duplicate;
11715   left->needs_update = right->needs_update;
11716   left->target_info = right->target_info;
11717   right->inserted = left_inserted;
11718   right->duplicate = left_duplicate;
11719   right->needs_update = left_needs_update;
11720   right->target_info = left_target_info;
11721 }
11722
11723 /* Force the re-insertion of the locations at ADDRESS.  This is called
11724    once a new/deleted/modified duplicate location is found and we are evaluating
11725    conditions on the target's side.  Such conditions need to be updated on
11726    the target.  */
11727
11728 static void
11729 force_breakpoint_reinsertion (struct bp_location *bl)
11730 {
11731   struct bp_location **locp = NULL, **loc2p;
11732   struct bp_location *loc;
11733   CORE_ADDR address = 0;
11734   int pspace_num;
11735
11736   address = bl->address;
11737   pspace_num = bl->pspace->num;
11738
11739   /* This is only meaningful if the target is
11740      evaluating conditions and if the user has
11741      opted for condition evaluation on the target's
11742      side.  */
11743   if (gdb_evaluates_breakpoint_condition_p ()
11744       || !target_supports_evaluation_of_breakpoint_conditions ())
11745     return;
11746
11747   /* Flag all breakpoint locations with this address and
11748      the same program space as the location
11749      as "its condition has changed".  We need to
11750      update the conditions on the target's side.  */
11751   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11752     {
11753       loc = *loc2p;
11754
11755       if (!is_breakpoint (loc->owner)
11756           || pspace_num != loc->pspace->num)
11757         continue;
11758
11759       /* Flag the location appropriately.  We use a different state to
11760          let everyone know that we already updated the set of locations
11761          with addr bl->address and program space bl->pspace.  This is so
11762          we don't have to keep calling these functions just to mark locations
11763          that have already been marked.  */
11764       loc->condition_changed = condition_updated;
11765
11766       /* Free the agent expression bytecode as well.  We will compute
11767          it later on.  */
11768       loc->cond_bytecode.reset ();
11769     }
11770 }
11771 /* Called whether new breakpoints are created, or existing breakpoints
11772    deleted, to update the global location list and recompute which
11773    locations are duplicate of which.
11774
11775    The INSERT_MODE flag determines whether locations may not, may, or
11776    shall be inserted now.  See 'enum ugll_insert_mode' for more
11777    info.  */
11778
11779 static void
11780 update_global_location_list (enum ugll_insert_mode insert_mode)
11781 {
11782   struct breakpoint *b;
11783   struct bp_location **locp, *loc;
11784   /* Last breakpoint location address that was marked for update.  */
11785   CORE_ADDR last_addr = 0;
11786   /* Last breakpoint location program space that was marked for update.  */
11787   int last_pspace_num = -1;
11788
11789   /* Used in the duplicates detection below.  When iterating over all
11790      bp_locations, points to the first bp_location of a given address.
11791      Breakpoints and watchpoints of different types are never
11792      duplicates of each other.  Keep one pointer for each type of
11793      breakpoint/watchpoint, so we only need to loop over all locations
11794      once.  */
11795   struct bp_location *bp_loc_first;  /* breakpoint */
11796   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11797   struct bp_location *awp_loc_first; /* access watchpoint */
11798   struct bp_location *rwp_loc_first; /* read watchpoint */
11799
11800   /* Saved former bp_locations array which we compare against the newly
11801      built bp_locations from the current state of ALL_BREAKPOINTS.  */
11802   struct bp_location **old_locp;
11803   unsigned old_locations_count;
11804   gdb::unique_xmalloc_ptr<struct bp_location *> old_locations (bp_locations);
11805
11806   old_locations_count = bp_locations_count;
11807   bp_locations = NULL;
11808   bp_locations_count = 0;
11809
11810   ALL_BREAKPOINTS (b)
11811     for (loc = b->loc; loc; loc = loc->next)
11812       bp_locations_count++;
11813
11814   bp_locations = XNEWVEC (struct bp_location *, bp_locations_count);
11815   locp = bp_locations;
11816   ALL_BREAKPOINTS (b)
11817     for (loc = b->loc; loc; loc = loc->next)
11818       *locp++ = loc;
11819   qsort (bp_locations, bp_locations_count, sizeof (*bp_locations),
11820          bp_locations_compare);
11821
11822   bp_locations_target_extensions_update ();
11823
11824   /* Identify bp_location instances that are no longer present in the
11825      new list, and therefore should be freed.  Note that it's not
11826      necessary that those locations should be removed from inferior --
11827      if there's another location at the same address (previously
11828      marked as duplicate), we don't need to remove/insert the
11829      location.
11830      
11831      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11832      and former bp_location array state respectively.  */
11833
11834   locp = bp_locations;
11835   for (old_locp = old_locations.get ();
11836        old_locp < old_locations.get () + old_locations_count;
11837        old_locp++)
11838     {
11839       struct bp_location *old_loc = *old_locp;
11840       struct bp_location **loc2p;
11841
11842       /* Tells if 'old_loc' is found among the new locations.  If
11843          not, we have to free it.  */
11844       int found_object = 0;
11845       /* Tells if the location should remain inserted in the target.  */
11846       int keep_in_target = 0;
11847       int removed = 0;
11848
11849       /* Skip LOCP entries which will definitely never be needed.
11850          Stop either at or being the one matching OLD_LOC.  */
11851       while (locp < bp_locations + bp_locations_count
11852              && (*locp)->address < old_loc->address)
11853         locp++;
11854
11855       for (loc2p = locp;
11856            (loc2p < bp_locations + bp_locations_count
11857             && (*loc2p)->address == old_loc->address);
11858            loc2p++)
11859         {
11860           /* Check if this is a new/duplicated location or a duplicated
11861              location that had its condition modified.  If so, we want to send
11862              its condition to the target if evaluation of conditions is taking
11863              place there.  */
11864           if ((*loc2p)->condition_changed == condition_modified
11865               && (last_addr != old_loc->address
11866                   || last_pspace_num != old_loc->pspace->num))
11867             {
11868               force_breakpoint_reinsertion (*loc2p);
11869               last_pspace_num = old_loc->pspace->num;
11870             }
11871
11872           if (*loc2p == old_loc)
11873             found_object = 1;
11874         }
11875
11876       /* We have already handled this address, update it so that we don't
11877          have to go through updates again.  */
11878       last_addr = old_loc->address;
11879
11880       /* Target-side condition evaluation: Handle deleted locations.  */
11881       if (!found_object)
11882         force_breakpoint_reinsertion (old_loc);
11883
11884       /* If this location is no longer present, and inserted, look if
11885          there's maybe a new location at the same address.  If so,
11886          mark that one inserted, and don't remove this one.  This is
11887          needed so that we don't have a time window where a breakpoint
11888          at certain location is not inserted.  */
11889
11890       if (old_loc->inserted)
11891         {
11892           /* If the location is inserted now, we might have to remove
11893              it.  */
11894
11895           if (found_object && should_be_inserted (old_loc))
11896             {
11897               /* The location is still present in the location list,
11898                  and still should be inserted.  Don't do anything.  */
11899               keep_in_target = 1;
11900             }
11901           else
11902             {
11903               /* This location still exists, but it won't be kept in the
11904                  target since it may have been disabled.  We proceed to
11905                  remove its target-side condition.  */
11906
11907               /* The location is either no longer present, or got
11908                  disabled.  See if there's another location at the
11909                  same address, in which case we don't need to remove
11910                  this one from the target.  */
11911
11912               /* OLD_LOC comes from existing struct breakpoint.  */
11913               if (breakpoint_address_is_meaningful (old_loc->owner))
11914                 {
11915                   for (loc2p = locp;
11916                        (loc2p < bp_locations + bp_locations_count
11917                         && (*loc2p)->address == old_loc->address);
11918                        loc2p++)
11919                     {
11920                       struct bp_location *loc2 = *loc2p;
11921
11922                       if (breakpoint_locations_match (loc2, old_loc))
11923                         {
11924                           /* Read watchpoint locations are switched to
11925                              access watchpoints, if the former are not
11926                              supported, but the latter are.  */
11927                           if (is_hardware_watchpoint (old_loc->owner))
11928                             {
11929                               gdb_assert (is_hardware_watchpoint (loc2->owner));
11930                               loc2->watchpoint_type = old_loc->watchpoint_type;
11931                             }
11932
11933                           /* loc2 is a duplicated location. We need to check
11934                              if it should be inserted in case it will be
11935                              unduplicated.  */
11936                           if (loc2 != old_loc
11937                               && unduplicated_should_be_inserted (loc2))
11938                             {
11939                               swap_insertion (old_loc, loc2);
11940                               keep_in_target = 1;
11941                               break;
11942                             }
11943                         }
11944                     }
11945                 }
11946             }
11947
11948           if (!keep_in_target)
11949             {
11950               if (remove_breakpoint (old_loc))
11951                 {
11952                   /* This is just about all we can do.  We could keep
11953                      this location on the global list, and try to
11954                      remove it next time, but there's no particular
11955                      reason why we will succeed next time.
11956                      
11957                      Note that at this point, old_loc->owner is still
11958                      valid, as delete_breakpoint frees the breakpoint
11959                      only after calling us.  */
11960                   printf_filtered (_("warning: Error removing "
11961                                      "breakpoint %d\n"), 
11962                                    old_loc->owner->number);
11963                 }
11964               removed = 1;
11965             }
11966         }
11967
11968       if (!found_object)
11969         {
11970           if (removed && target_is_non_stop_p ()
11971               && need_moribund_for_location_type (old_loc))
11972             {
11973               /* This location was removed from the target.  In
11974                  non-stop mode, a race condition is possible where
11975                  we've removed a breakpoint, but stop events for that
11976                  breakpoint are already queued and will arrive later.
11977                  We apply an heuristic to be able to distinguish such
11978                  SIGTRAPs from other random SIGTRAPs: we keep this
11979                  breakpoint location for a bit, and will retire it
11980                  after we see some number of events.  The theory here
11981                  is that reporting of events should, "on the average",
11982                  be fair, so after a while we'll see events from all
11983                  threads that have anything of interest, and no longer
11984                  need to keep this breakpoint location around.  We
11985                  don't hold locations forever so to reduce chances of
11986                  mistaking a non-breakpoint SIGTRAP for a breakpoint
11987                  SIGTRAP.
11988
11989                  The heuristic failing can be disastrous on
11990                  decr_pc_after_break targets.
11991
11992                  On decr_pc_after_break targets, like e.g., x86-linux,
11993                  if we fail to recognize a late breakpoint SIGTRAP,
11994                  because events_till_retirement has reached 0 too
11995                  soon, we'll fail to do the PC adjustment, and report
11996                  a random SIGTRAP to the user.  When the user resumes
11997                  the inferior, it will most likely immediately crash
11998                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
11999                  corrupted, because of being resumed e.g., in the
12000                  middle of a multi-byte instruction, or skipped a
12001                  one-byte instruction.  This was actually seen happen
12002                  on native x86-linux, and should be less rare on
12003                  targets that do not support new thread events, like
12004                  remote, due to the heuristic depending on
12005                  thread_count.
12006
12007                  Mistaking a random SIGTRAP for a breakpoint trap
12008                  causes similar symptoms (PC adjustment applied when
12009                  it shouldn't), but then again, playing with SIGTRAPs
12010                  behind the debugger's back is asking for trouble.
12011
12012                  Since hardware watchpoint traps are always
12013                  distinguishable from other traps, so we don't need to
12014                  apply keep hardware watchpoint moribund locations
12015                  around.  We simply always ignore hardware watchpoint
12016                  traps we can no longer explain.  */
12017
12018               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12019               old_loc->owner = NULL;
12020
12021               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12022             }
12023           else
12024             {
12025               old_loc->owner = NULL;
12026               decref_bp_location (&old_loc);
12027             }
12028         }
12029     }
12030
12031   /* Rescan breakpoints at the same address and section, marking the
12032      first one as "first" and any others as "duplicates".  This is so
12033      that the bpt instruction is only inserted once.  If we have a
12034      permanent breakpoint at the same place as BPT, make that one the
12035      official one, and the rest as duplicates.  Permanent breakpoints
12036      are sorted first for the same address.
12037
12038      Do the same for hardware watchpoints, but also considering the
12039      watchpoint's type (regular/access/read) and length.  */
12040
12041   bp_loc_first = NULL;
12042   wp_loc_first = NULL;
12043   awp_loc_first = NULL;
12044   rwp_loc_first = NULL;
12045   ALL_BP_LOCATIONS (loc, locp)
12046     {
12047       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12048          non-NULL.  */
12049       struct bp_location **loc_first_p;
12050       b = loc->owner;
12051
12052       if (!unduplicated_should_be_inserted (loc)
12053           || !breakpoint_address_is_meaningful (b)
12054           /* Don't detect duplicate for tracepoint locations because they are
12055            never duplicated.  See the comments in field `duplicate' of
12056            `struct bp_location'.  */
12057           || is_tracepoint (b))
12058         {
12059           /* Clear the condition modification flag.  */
12060           loc->condition_changed = condition_unchanged;
12061           continue;
12062         }
12063
12064       if (b->type == bp_hardware_watchpoint)
12065         loc_first_p = &wp_loc_first;
12066       else if (b->type == bp_read_watchpoint)
12067         loc_first_p = &rwp_loc_first;
12068       else if (b->type == bp_access_watchpoint)
12069         loc_first_p = &awp_loc_first;
12070       else
12071         loc_first_p = &bp_loc_first;
12072
12073       if (*loc_first_p == NULL
12074           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12075           || !breakpoint_locations_match (loc, *loc_first_p))
12076         {
12077           *loc_first_p = loc;
12078           loc->duplicate = 0;
12079
12080           if (is_breakpoint (loc->owner) && loc->condition_changed)
12081             {
12082               loc->needs_update = 1;
12083               /* Clear the condition modification flag.  */
12084               loc->condition_changed = condition_unchanged;
12085             }
12086           continue;
12087         }
12088
12089
12090       /* This and the above ensure the invariant that the first location
12091          is not duplicated, and is the inserted one.
12092          All following are marked as duplicated, and are not inserted.  */
12093       if (loc->inserted)
12094         swap_insertion (loc, *loc_first_p);
12095       loc->duplicate = 1;
12096
12097       /* Clear the condition modification flag.  */
12098       loc->condition_changed = condition_unchanged;
12099     }
12100
12101   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12102     {
12103       if (insert_mode != UGLL_DONT_INSERT)
12104         insert_breakpoint_locations ();
12105       else
12106         {
12107           /* Even though the caller told us to not insert new
12108              locations, we may still need to update conditions on the
12109              target's side of breakpoints that were already inserted
12110              if the target is evaluating breakpoint conditions.  We
12111              only update conditions for locations that are marked
12112              "needs_update".  */
12113           update_inserted_breakpoint_locations ();
12114         }
12115     }
12116
12117   if (insert_mode != UGLL_DONT_INSERT)
12118     download_tracepoint_locations ();
12119 }
12120
12121 void
12122 breakpoint_retire_moribund (void)
12123 {
12124   struct bp_location *loc;
12125   int ix;
12126
12127   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12128     if (--(loc->events_till_retirement) == 0)
12129       {
12130         decref_bp_location (&loc);
12131         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12132         --ix;
12133       }
12134 }
12135
12136 static void
12137 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12138 {
12139
12140   TRY
12141     {
12142       update_global_location_list (insert_mode);
12143     }
12144   CATCH (e, RETURN_MASK_ERROR)
12145     {
12146     }
12147   END_CATCH
12148 }
12149
12150 /* Clear BKP from a BPS.  */
12151
12152 static void
12153 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12154 {
12155   bpstat bs;
12156
12157   for (bs = bps; bs; bs = bs->next)
12158     if (bs->breakpoint_at == bpt)
12159       {
12160         bs->breakpoint_at = NULL;
12161         bs->old_val = NULL;
12162         /* bs->commands will be freed later.  */
12163       }
12164 }
12165
12166 /* Callback for iterate_over_threads.  */
12167 static int
12168 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12169 {
12170   struct breakpoint *bpt = (struct breakpoint *) data;
12171
12172   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12173   return 0;
12174 }
12175
12176 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12177    callbacks.  */
12178
12179 static void
12180 say_where (struct breakpoint *b)
12181 {
12182   struct value_print_options opts;
12183
12184   get_user_print_options (&opts);
12185
12186   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12187      single string.  */
12188   if (b->loc == NULL)
12189     {
12190       /* For pending locations, the output differs slightly based
12191          on b->extra_string.  If this is non-NULL, it contains either
12192          a condition or dprintf arguments.  */
12193       if (b->extra_string == NULL)
12194         {
12195           printf_filtered (_(" (%s) pending."),
12196                            event_location_to_string (b->location.get ()));
12197         }
12198       else if (b->type == bp_dprintf)
12199         {
12200           printf_filtered (_(" (%s,%s) pending."),
12201                            event_location_to_string (b->location.get ()),
12202                            b->extra_string);
12203         }
12204       else
12205         {
12206           printf_filtered (_(" (%s %s) pending."),
12207                            event_location_to_string (b->location.get ()),
12208                            b->extra_string);
12209         }
12210     }
12211   else
12212     {
12213       if (opts.addressprint || b->loc->symtab == NULL)
12214         {
12215           printf_filtered (" at ");
12216           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12217                           gdb_stdout);
12218         }
12219       if (b->loc->symtab != NULL)
12220         {
12221           /* If there is a single location, we can print the location
12222              more nicely.  */
12223           if (b->loc->next == NULL)
12224             printf_filtered (": file %s, line %d.",
12225                              symtab_to_filename_for_display (b->loc->symtab),
12226                              b->loc->line_number);
12227           else
12228             /* This is not ideal, but each location may have a
12229                different file name, and this at least reflects the
12230                real situation somewhat.  */
12231             printf_filtered (": %s.",
12232                              event_location_to_string (b->location.get ()));
12233         }
12234
12235       if (b->loc->next)
12236         {
12237           struct bp_location *loc = b->loc;
12238           int n = 0;
12239           for (; loc; loc = loc->next)
12240             ++n;
12241           printf_filtered (" (%d locations)", n);
12242         }
12243     }
12244 }
12245
12246 /* Default bp_location_ops methods.  */
12247
12248 static void
12249 bp_location_dtor (struct bp_location *self)
12250 {
12251   xfree (self->function_name);
12252 }
12253
12254 static const struct bp_location_ops bp_location_ops =
12255 {
12256   bp_location_dtor
12257 };
12258
12259 /* Destructor for the breakpoint base class.  */
12260
12261 breakpoint::~breakpoint ()
12262 {
12263   xfree (this->cond_string);
12264   xfree (this->extra_string);
12265   xfree (this->filter);
12266 }
12267
12268 static struct bp_location *
12269 base_breakpoint_allocate_location (struct breakpoint *self)
12270 {
12271   return new bp_location (&bp_location_ops, self);
12272 }
12273
12274 static void
12275 base_breakpoint_re_set (struct breakpoint *b)
12276 {
12277   /* Nothing to re-set. */
12278 }
12279
12280 #define internal_error_pure_virtual_called() \
12281   gdb_assert_not_reached ("pure virtual function called")
12282
12283 static int
12284 base_breakpoint_insert_location (struct bp_location *bl)
12285 {
12286   internal_error_pure_virtual_called ();
12287 }
12288
12289 static int
12290 base_breakpoint_remove_location (struct bp_location *bl,
12291                                  enum remove_bp_reason reason)
12292 {
12293   internal_error_pure_virtual_called ();
12294 }
12295
12296 static int
12297 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12298                                 const address_space *aspace,
12299                                 CORE_ADDR bp_addr,
12300                                 const struct target_waitstatus *ws)
12301 {
12302   internal_error_pure_virtual_called ();
12303 }
12304
12305 static void
12306 base_breakpoint_check_status (bpstat bs)
12307 {
12308   /* Always stop.   */
12309 }
12310
12311 /* A "works_in_software_mode" breakpoint_ops method that just internal
12312    errors.  */
12313
12314 static int
12315 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12316 {
12317   internal_error_pure_virtual_called ();
12318 }
12319
12320 /* A "resources_needed" breakpoint_ops method that just internal
12321    errors.  */
12322
12323 static int
12324 base_breakpoint_resources_needed (const struct bp_location *bl)
12325 {
12326   internal_error_pure_virtual_called ();
12327 }
12328
12329 static enum print_stop_action
12330 base_breakpoint_print_it (bpstat bs)
12331 {
12332   internal_error_pure_virtual_called ();
12333 }
12334
12335 static void
12336 base_breakpoint_print_one_detail (const struct breakpoint *self,
12337                                   struct ui_out *uiout)
12338 {
12339   /* nothing */
12340 }
12341
12342 static void
12343 base_breakpoint_print_mention (struct breakpoint *b)
12344 {
12345   internal_error_pure_virtual_called ();
12346 }
12347
12348 static void
12349 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12350 {
12351   internal_error_pure_virtual_called ();
12352 }
12353
12354 static void
12355 base_breakpoint_create_sals_from_location
12356   (const struct event_location *location,
12357    struct linespec_result *canonical,
12358    enum bptype type_wanted)
12359 {
12360   internal_error_pure_virtual_called ();
12361 }
12362
12363 static void
12364 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12365                                         struct linespec_result *c,
12366                                         gdb::unique_xmalloc_ptr<char> cond_string,
12367                                         gdb::unique_xmalloc_ptr<char> extra_string,
12368                                         enum bptype type_wanted,
12369                                         enum bpdisp disposition,
12370                                         int thread,
12371                                         int task, int ignore_count,
12372                                         const struct breakpoint_ops *o,
12373                                         int from_tty, int enabled,
12374                                         int internal, unsigned flags)
12375 {
12376   internal_error_pure_virtual_called ();
12377 }
12378
12379 static std::vector<symtab_and_line>
12380 base_breakpoint_decode_location (struct breakpoint *b,
12381                                  const struct event_location *location,
12382                                  struct program_space *search_pspace)
12383 {
12384   internal_error_pure_virtual_called ();
12385 }
12386
12387 /* The default 'explains_signal' method.  */
12388
12389 static int
12390 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12391 {
12392   return 1;
12393 }
12394
12395 /* The default "after_condition_true" method.  */
12396
12397 static void
12398 base_breakpoint_after_condition_true (struct bpstats *bs)
12399 {
12400   /* Nothing to do.   */
12401 }
12402
12403 struct breakpoint_ops base_breakpoint_ops =
12404 {
12405   base_breakpoint_allocate_location,
12406   base_breakpoint_re_set,
12407   base_breakpoint_insert_location,
12408   base_breakpoint_remove_location,
12409   base_breakpoint_breakpoint_hit,
12410   base_breakpoint_check_status,
12411   base_breakpoint_resources_needed,
12412   base_breakpoint_works_in_software_mode,
12413   base_breakpoint_print_it,
12414   NULL,
12415   base_breakpoint_print_one_detail,
12416   base_breakpoint_print_mention,
12417   base_breakpoint_print_recreate,
12418   base_breakpoint_create_sals_from_location,
12419   base_breakpoint_create_breakpoints_sal,
12420   base_breakpoint_decode_location,
12421   base_breakpoint_explains_signal,
12422   base_breakpoint_after_condition_true,
12423 };
12424
12425 /* Default breakpoint_ops methods.  */
12426
12427 static void
12428 bkpt_re_set (struct breakpoint *b)
12429 {
12430   /* FIXME: is this still reachable?  */
12431   if (breakpoint_event_location_empty_p (b))
12432     {
12433       /* Anything without a location can't be re-set.  */
12434       delete_breakpoint (b);
12435       return;
12436     }
12437
12438   breakpoint_re_set_default (b);
12439 }
12440
12441 static int
12442 bkpt_insert_location (struct bp_location *bl)
12443 {
12444   CORE_ADDR addr = bl->target_info.reqstd_address;
12445
12446   bl->target_info.kind = breakpoint_kind (bl, &addr);
12447   bl->target_info.placed_address = addr;
12448
12449   if (bl->loc_type == bp_loc_hardware_breakpoint)
12450     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12451   else
12452     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12453 }
12454
12455 static int
12456 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
12457 {
12458   if (bl->loc_type == bp_loc_hardware_breakpoint)
12459     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12460   else
12461     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12462 }
12463
12464 static int
12465 bkpt_breakpoint_hit (const struct bp_location *bl,
12466                      const address_space *aspace, CORE_ADDR bp_addr,
12467                      const struct target_waitstatus *ws)
12468 {
12469   if (ws->kind != TARGET_WAITKIND_STOPPED
12470       || ws->value.sig != GDB_SIGNAL_TRAP)
12471     return 0;
12472
12473   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12474                                  aspace, bp_addr))
12475     return 0;
12476
12477   if (overlay_debugging         /* unmapped overlay section */
12478       && section_is_overlay (bl->section)
12479       && !section_is_mapped (bl->section))
12480     return 0;
12481
12482   return 1;
12483 }
12484
12485 static int
12486 dprintf_breakpoint_hit (const struct bp_location *bl,
12487                         const address_space *aspace, CORE_ADDR bp_addr,
12488                         const struct target_waitstatus *ws)
12489 {
12490   if (dprintf_style == dprintf_style_agent
12491       && target_can_run_breakpoint_commands ())
12492     {
12493       /* An agent-style dprintf never causes a stop.  If we see a trap
12494          for this address it must be for a breakpoint that happens to
12495          be set at the same address.  */
12496       return 0;
12497     }
12498
12499   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12500 }
12501
12502 static int
12503 bkpt_resources_needed (const struct bp_location *bl)
12504 {
12505   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12506
12507   return 1;
12508 }
12509
12510 static enum print_stop_action
12511 bkpt_print_it (bpstat bs)
12512 {
12513   struct breakpoint *b;
12514   const struct bp_location *bl;
12515   int bp_temp;
12516   struct ui_out *uiout = current_uiout;
12517
12518   gdb_assert (bs->bp_location_at != NULL);
12519
12520   bl = bs->bp_location_at;
12521   b = bs->breakpoint_at;
12522
12523   bp_temp = b->disposition == disp_del;
12524   if (bl->address != bl->requested_address)
12525     breakpoint_adjustment_warning (bl->requested_address,
12526                                    bl->address,
12527                                    b->number, 1);
12528   annotate_breakpoint (b->number);
12529   maybe_print_thread_hit_breakpoint (uiout);
12530
12531   if (bp_temp)
12532     uiout->text ("Temporary breakpoint ");
12533   else
12534     uiout->text ("Breakpoint ");
12535   if (uiout->is_mi_like_p ())
12536     {
12537       uiout->field_string ("reason",
12538                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12539       uiout->field_string ("disp", bpdisp_text (b->disposition));
12540     }
12541   uiout->field_int ("bkptno", b->number);
12542   uiout->text (", ");
12543
12544   return PRINT_SRC_AND_LOC;
12545 }
12546
12547 static void
12548 bkpt_print_mention (struct breakpoint *b)
12549 {
12550   if (current_uiout->is_mi_like_p ())
12551     return;
12552
12553   switch (b->type)
12554     {
12555     case bp_breakpoint:
12556     case bp_gnu_ifunc_resolver:
12557       if (b->disposition == disp_del)
12558         printf_filtered (_("Temporary breakpoint"));
12559       else
12560         printf_filtered (_("Breakpoint"));
12561       printf_filtered (_(" %d"), b->number);
12562       if (b->type == bp_gnu_ifunc_resolver)
12563         printf_filtered (_(" at gnu-indirect-function resolver"));
12564       break;
12565     case bp_hardware_breakpoint:
12566       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12567       break;
12568     case bp_dprintf:
12569       printf_filtered (_("Dprintf %d"), b->number);
12570       break;
12571     }
12572
12573   say_where (b);
12574 }
12575
12576 static void
12577 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12578 {
12579   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12580     fprintf_unfiltered (fp, "tbreak");
12581   else if (tp->type == bp_breakpoint)
12582     fprintf_unfiltered (fp, "break");
12583   else if (tp->type == bp_hardware_breakpoint
12584            && tp->disposition == disp_del)
12585     fprintf_unfiltered (fp, "thbreak");
12586   else if (tp->type == bp_hardware_breakpoint)
12587     fprintf_unfiltered (fp, "hbreak");
12588   else
12589     internal_error (__FILE__, __LINE__,
12590                     _("unhandled breakpoint type %d"), (int) tp->type);
12591
12592   fprintf_unfiltered (fp, " %s",
12593                       event_location_to_string (tp->location.get ()));
12594
12595   /* Print out extra_string if this breakpoint is pending.  It might
12596      contain, for example, conditions that were set by the user.  */
12597   if (tp->loc == NULL && tp->extra_string != NULL)
12598     fprintf_unfiltered (fp, " %s", tp->extra_string);
12599
12600   print_recreate_thread (tp, fp);
12601 }
12602
12603 static void
12604 bkpt_create_sals_from_location (const struct event_location *location,
12605                                 struct linespec_result *canonical,
12606                                 enum bptype type_wanted)
12607 {
12608   create_sals_from_location_default (location, canonical, type_wanted);
12609 }
12610
12611 static void
12612 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12613                              struct linespec_result *canonical,
12614                              gdb::unique_xmalloc_ptr<char> cond_string,
12615                              gdb::unique_xmalloc_ptr<char> extra_string,
12616                              enum bptype type_wanted,
12617                              enum bpdisp disposition,
12618                              int thread,
12619                              int task, int ignore_count,
12620                              const struct breakpoint_ops *ops,
12621                              int from_tty, int enabled,
12622                              int internal, unsigned flags)
12623 {
12624   create_breakpoints_sal_default (gdbarch, canonical,
12625                                   std::move (cond_string),
12626                                   std::move (extra_string),
12627                                   type_wanted,
12628                                   disposition, thread, task,
12629                                   ignore_count, ops, from_tty,
12630                                   enabled, internal, flags);
12631 }
12632
12633 static std::vector<symtab_and_line>
12634 bkpt_decode_location (struct breakpoint *b,
12635                       const struct event_location *location,
12636                       struct program_space *search_pspace)
12637 {
12638   return decode_location_default (b, location, search_pspace);
12639 }
12640
12641 /* Virtual table for internal breakpoints.  */
12642
12643 static void
12644 internal_bkpt_re_set (struct breakpoint *b)
12645 {
12646   switch (b->type)
12647     {
12648       /* Delete overlay event and longjmp master breakpoints; they
12649          will be reset later by breakpoint_re_set.  */
12650     case bp_overlay_event:
12651     case bp_longjmp_master:
12652     case bp_std_terminate_master:
12653     case bp_exception_master:
12654       delete_breakpoint (b);
12655       break;
12656
12657       /* This breakpoint is special, it's set up when the inferior
12658          starts and we really don't want to touch it.  */
12659     case bp_shlib_event:
12660
12661       /* Like bp_shlib_event, this breakpoint type is special.  Once
12662          it is set up, we do not want to touch it.  */
12663     case bp_thread_event:
12664       break;
12665     }
12666 }
12667
12668 static void
12669 internal_bkpt_check_status (bpstat bs)
12670 {
12671   if (bs->breakpoint_at->type == bp_shlib_event)
12672     {
12673       /* If requested, stop when the dynamic linker notifies GDB of
12674          events.  This allows the user to get control and place
12675          breakpoints in initializer routines for dynamically loaded
12676          objects (among other things).  */
12677       bs->stop = stop_on_solib_events;
12678       bs->print = stop_on_solib_events;
12679     }
12680   else
12681     bs->stop = 0;
12682 }
12683
12684 static enum print_stop_action
12685 internal_bkpt_print_it (bpstat bs)
12686 {
12687   struct breakpoint *b;
12688
12689   b = bs->breakpoint_at;
12690
12691   switch (b->type)
12692     {
12693     case bp_shlib_event:
12694       /* Did we stop because the user set the stop_on_solib_events
12695          variable?  (If so, we report this as a generic, "Stopped due
12696          to shlib event" message.) */
12697       print_solib_event (0);
12698       break;
12699
12700     case bp_thread_event:
12701       /* Not sure how we will get here.
12702          GDB should not stop for these breakpoints.  */
12703       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12704       break;
12705
12706     case bp_overlay_event:
12707       /* By analogy with the thread event, GDB should not stop for these.  */
12708       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12709       break;
12710
12711     case bp_longjmp_master:
12712       /* These should never be enabled.  */
12713       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12714       break;
12715
12716     case bp_std_terminate_master:
12717       /* These should never be enabled.  */
12718       printf_filtered (_("std::terminate Master Breakpoint: "
12719                          "gdb should not stop!\n"));
12720       break;
12721
12722     case bp_exception_master:
12723       /* These should never be enabled.  */
12724       printf_filtered (_("Exception Master Breakpoint: "
12725                          "gdb should not stop!\n"));
12726       break;
12727     }
12728
12729   return PRINT_NOTHING;
12730 }
12731
12732 static void
12733 internal_bkpt_print_mention (struct breakpoint *b)
12734 {
12735   /* Nothing to mention.  These breakpoints are internal.  */
12736 }
12737
12738 /* Virtual table for momentary breakpoints  */
12739
12740 static void
12741 momentary_bkpt_re_set (struct breakpoint *b)
12742 {
12743   /* Keep temporary breakpoints, which can be encountered when we step
12744      over a dlopen call and solib_add is resetting the breakpoints.
12745      Otherwise these should have been blown away via the cleanup chain
12746      or by breakpoint_init_inferior when we rerun the executable.  */
12747 }
12748
12749 static void
12750 momentary_bkpt_check_status (bpstat bs)
12751 {
12752   /* Nothing.  The point of these breakpoints is causing a stop.  */
12753 }
12754
12755 static enum print_stop_action
12756 momentary_bkpt_print_it (bpstat bs)
12757 {
12758   return PRINT_UNKNOWN;
12759 }
12760
12761 static void
12762 momentary_bkpt_print_mention (struct breakpoint *b)
12763 {
12764   /* Nothing to mention.  These breakpoints are internal.  */
12765 }
12766
12767 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12768
12769    It gets cleared already on the removal of the first one of such placed
12770    breakpoints.  This is OK as they get all removed altogether.  */
12771
12772 longjmp_breakpoint::~longjmp_breakpoint ()
12773 {
12774   thread_info *tp = find_thread_global_id (this->thread);
12775
12776   if (tp != NULL)
12777     tp->initiating_frame = null_frame_id;
12778 }
12779
12780 /* Specific methods for probe breakpoints.  */
12781
12782 static int
12783 bkpt_probe_insert_location (struct bp_location *bl)
12784 {
12785   int v = bkpt_insert_location (bl);
12786
12787   if (v == 0)
12788     {
12789       /* The insertion was successful, now let's set the probe's semaphore
12790          if needed.  */
12791       bl->probe.prob->set_semaphore (bl->probe.objfile, bl->gdbarch);
12792     }
12793
12794   return v;
12795 }
12796
12797 static int
12798 bkpt_probe_remove_location (struct bp_location *bl,
12799                             enum remove_bp_reason reason)
12800 {
12801   /* Let's clear the semaphore before removing the location.  */
12802   bl->probe.prob->clear_semaphore (bl->probe.objfile, bl->gdbarch);
12803
12804   return bkpt_remove_location (bl, reason);
12805 }
12806
12807 static void
12808 bkpt_probe_create_sals_from_location (const struct event_location *location,
12809                                       struct linespec_result *canonical,
12810                                       enum bptype type_wanted)
12811 {
12812   struct linespec_sals lsal;
12813
12814   lsal.sals = parse_probes (location, NULL, canonical);
12815   lsal.canonical
12816     = xstrdup (event_location_to_string (canonical->location.get ()));
12817   canonical->lsals.push_back (std::move (lsal));
12818 }
12819
12820 static std::vector<symtab_and_line>
12821 bkpt_probe_decode_location (struct breakpoint *b,
12822                             const struct event_location *location,
12823                             struct program_space *search_pspace)
12824 {
12825   std::vector<symtab_and_line> sals = parse_probes (location, search_pspace, NULL);
12826   if (sals.empty ())
12827     error (_("probe not found"));
12828   return sals;
12829 }
12830
12831 /* The breakpoint_ops structure to be used in tracepoints.  */
12832
12833 static void
12834 tracepoint_re_set (struct breakpoint *b)
12835 {
12836   breakpoint_re_set_default (b);
12837 }
12838
12839 static int
12840 tracepoint_breakpoint_hit (const struct bp_location *bl,
12841                            const address_space *aspace, CORE_ADDR bp_addr,
12842                            const struct target_waitstatus *ws)
12843 {
12844   /* By definition, the inferior does not report stops at
12845      tracepoints.  */
12846   return 0;
12847 }
12848
12849 static void
12850 tracepoint_print_one_detail (const struct breakpoint *self,
12851                              struct ui_out *uiout)
12852 {
12853   struct tracepoint *tp = (struct tracepoint *) self;
12854   if (!tp->static_trace_marker_id.empty ())
12855     {
12856       gdb_assert (self->type == bp_static_tracepoint);
12857
12858       uiout->text ("\tmarker id is ");
12859       uiout->field_string ("static-tracepoint-marker-string-id",
12860                            tp->static_trace_marker_id);
12861       uiout->text ("\n");
12862     }
12863 }
12864
12865 static void
12866 tracepoint_print_mention (struct breakpoint *b)
12867 {
12868   if (current_uiout->is_mi_like_p ())
12869     return;
12870
12871   switch (b->type)
12872     {
12873     case bp_tracepoint:
12874       printf_filtered (_("Tracepoint"));
12875       printf_filtered (_(" %d"), b->number);
12876       break;
12877     case bp_fast_tracepoint:
12878       printf_filtered (_("Fast tracepoint"));
12879       printf_filtered (_(" %d"), b->number);
12880       break;
12881     case bp_static_tracepoint:
12882       printf_filtered (_("Static tracepoint"));
12883       printf_filtered (_(" %d"), b->number);
12884       break;
12885     default:
12886       internal_error (__FILE__, __LINE__,
12887                       _("unhandled tracepoint type %d"), (int) b->type);
12888     }
12889
12890   say_where (b);
12891 }
12892
12893 static void
12894 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
12895 {
12896   struct tracepoint *tp = (struct tracepoint *) self;
12897
12898   if (self->type == bp_fast_tracepoint)
12899     fprintf_unfiltered (fp, "ftrace");
12900   else if (self->type == bp_static_tracepoint)
12901     fprintf_unfiltered (fp, "strace");
12902   else if (self->type == bp_tracepoint)
12903     fprintf_unfiltered (fp, "trace");
12904   else
12905     internal_error (__FILE__, __LINE__,
12906                     _("unhandled tracepoint type %d"), (int) self->type);
12907
12908   fprintf_unfiltered (fp, " %s",
12909                       event_location_to_string (self->location.get ()));
12910   print_recreate_thread (self, fp);
12911
12912   if (tp->pass_count)
12913     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
12914 }
12915
12916 static void
12917 tracepoint_create_sals_from_location (const struct event_location *location,
12918                                       struct linespec_result *canonical,
12919                                       enum bptype type_wanted)
12920 {
12921   create_sals_from_location_default (location, canonical, type_wanted);
12922 }
12923
12924 static void
12925 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12926                                    struct linespec_result *canonical,
12927                                    gdb::unique_xmalloc_ptr<char> cond_string,
12928                                    gdb::unique_xmalloc_ptr<char> extra_string,
12929                                    enum bptype type_wanted,
12930                                    enum bpdisp disposition,
12931                                    int thread,
12932                                    int task, int ignore_count,
12933                                    const struct breakpoint_ops *ops,
12934                                    int from_tty, int enabled,
12935                                    int internal, unsigned flags)
12936 {
12937   create_breakpoints_sal_default (gdbarch, canonical,
12938                                   std::move (cond_string),
12939                                   std::move (extra_string),
12940                                   type_wanted,
12941                                   disposition, thread, task,
12942                                   ignore_count, ops, from_tty,
12943                                   enabled, internal, flags);
12944 }
12945
12946 static std::vector<symtab_and_line>
12947 tracepoint_decode_location (struct breakpoint *b,
12948                             const struct event_location *location,
12949                             struct program_space *search_pspace)
12950 {
12951   return decode_location_default (b, location, search_pspace);
12952 }
12953
12954 struct breakpoint_ops tracepoint_breakpoint_ops;
12955
12956 /* The breakpoint_ops structure to be use on tracepoints placed in a
12957    static probe.  */
12958
12959 static void
12960 tracepoint_probe_create_sals_from_location
12961   (const struct event_location *location,
12962    struct linespec_result *canonical,
12963    enum bptype type_wanted)
12964 {
12965   /* We use the same method for breakpoint on probes.  */
12966   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
12967 }
12968
12969 static std::vector<symtab_and_line>
12970 tracepoint_probe_decode_location (struct breakpoint *b,
12971                                   const struct event_location *location,
12972                                   struct program_space *search_pspace)
12973 {
12974   /* We use the same method for breakpoint on probes.  */
12975   return bkpt_probe_decode_location (b, location, search_pspace);
12976 }
12977
12978 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
12979
12980 /* Dprintf breakpoint_ops methods.  */
12981
12982 static void
12983 dprintf_re_set (struct breakpoint *b)
12984 {
12985   breakpoint_re_set_default (b);
12986
12987   /* extra_string should never be non-NULL for dprintf.  */
12988   gdb_assert (b->extra_string != NULL);
12989
12990   /* 1 - connect to target 1, that can run breakpoint commands.
12991      2 - create a dprintf, which resolves fine.
12992      3 - disconnect from target 1
12993      4 - connect to target 2, that can NOT run breakpoint commands.
12994
12995      After steps #3/#4, you'll want the dprintf command list to
12996      be updated, because target 1 and 2 may well return different
12997      answers for target_can_run_breakpoint_commands().
12998      Given absence of finer grained resetting, we get to do
12999      it all the time.  */
13000   if (b->extra_string != NULL)
13001     update_dprintf_command_list (b);
13002 }
13003
13004 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13005
13006 static void
13007 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13008 {
13009   fprintf_unfiltered (fp, "dprintf %s,%s",
13010                       event_location_to_string (tp->location.get ()),
13011                       tp->extra_string);
13012   print_recreate_thread (tp, fp);
13013 }
13014
13015 /* Implement the "after_condition_true" breakpoint_ops method for
13016    dprintf.
13017
13018    dprintf's are implemented with regular commands in their command
13019    list, but we run the commands here instead of before presenting the
13020    stop to the user, as dprintf's don't actually cause a stop.  This
13021    also makes it so that the commands of multiple dprintfs at the same
13022    address are all handled.  */
13023
13024 static void
13025 dprintf_after_condition_true (struct bpstats *bs)
13026 {
13027   struct bpstats tmp_bs;
13028   struct bpstats *tmp_bs_p = &tmp_bs;
13029
13030   /* dprintf's never cause a stop.  This wasn't set in the
13031      check_status hook instead because that would make the dprintf's
13032      condition not be evaluated.  */
13033   bs->stop = 0;
13034
13035   /* Run the command list here.  Take ownership of it instead of
13036      copying.  We never want these commands to run later in
13037      bpstat_do_actions, if a breakpoint that causes a stop happens to
13038      be set at same address as this dprintf, or even if running the
13039      commands here throws.  */
13040   tmp_bs.commands = bs->commands;
13041   bs->commands = NULL;
13042
13043   bpstat_do_actions_1 (&tmp_bs_p);
13044
13045   /* 'tmp_bs.commands' will usually be NULL by now, but
13046      bpstat_do_actions_1 may return early without processing the whole
13047      list.  */
13048 }
13049
13050 /* The breakpoint_ops structure to be used on static tracepoints with
13051    markers (`-m').  */
13052
13053 static void
13054 strace_marker_create_sals_from_location (const struct event_location *location,
13055                                          struct linespec_result *canonical,
13056                                          enum bptype type_wanted)
13057 {
13058   struct linespec_sals lsal;
13059   const char *arg_start, *arg;
13060
13061   arg = arg_start = get_linespec_location (location)->spec_string;
13062   lsal.sals = decode_static_tracepoint_spec (&arg);
13063
13064   std::string str (arg_start, arg - arg_start);
13065   const char *ptr = str.c_str ();
13066   canonical->location
13067     = new_linespec_location (&ptr, symbol_name_match_type::FULL);
13068
13069   lsal.canonical
13070     = xstrdup (event_location_to_string (canonical->location.get ()));
13071   canonical->lsals.push_back (std::move (lsal));
13072 }
13073
13074 static void
13075 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13076                                       struct linespec_result *canonical,
13077                                       gdb::unique_xmalloc_ptr<char> cond_string,
13078                                       gdb::unique_xmalloc_ptr<char> extra_string,
13079                                       enum bptype type_wanted,
13080                                       enum bpdisp disposition,
13081                                       int thread,
13082                                       int task, int ignore_count,
13083                                       const struct breakpoint_ops *ops,
13084                                       int from_tty, int enabled,
13085                                       int internal, unsigned flags)
13086 {
13087   const linespec_sals &lsal = canonical->lsals[0];
13088
13089   /* If the user is creating a static tracepoint by marker id
13090      (strace -m MARKER_ID), then store the sals index, so that
13091      breakpoint_re_set can try to match up which of the newly
13092      found markers corresponds to this one, and, don't try to
13093      expand multiple locations for each sal, given than SALS
13094      already should contain all sals for MARKER_ID.  */
13095
13096   for (size_t i = 0; i < lsal.sals.size (); i++)
13097     {
13098       event_location_up location
13099         = copy_event_location (canonical->location.get ());
13100
13101       std::unique_ptr<tracepoint> tp (new tracepoint ());
13102       init_breakpoint_sal (tp.get (), gdbarch, lsal.sals[i],
13103                            std::move (location), NULL,
13104                            std::move (cond_string),
13105                            std::move (extra_string),
13106                            type_wanted, disposition,
13107                            thread, task, ignore_count, ops,
13108                            from_tty, enabled, internal, flags,
13109                            canonical->special_display);
13110       /* Given that its possible to have multiple markers with
13111          the same string id, if the user is creating a static
13112          tracepoint by marker id ("strace -m MARKER_ID"), then
13113          store the sals index, so that breakpoint_re_set can
13114          try to match up which of the newly found markers
13115          corresponds to this one  */
13116       tp->static_trace_marker_id_idx = i;
13117
13118       install_breakpoint (internal, std::move (tp), 0);
13119     }
13120 }
13121
13122 static std::vector<symtab_and_line>
13123 strace_marker_decode_location (struct breakpoint *b,
13124                                const struct event_location *location,
13125                                struct program_space *search_pspace)
13126 {
13127   struct tracepoint *tp = (struct tracepoint *) b;
13128   const char *s = get_linespec_location (location)->spec_string;
13129
13130   std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
13131   if (sals.size () > tp->static_trace_marker_id_idx)
13132     {
13133       sals[0] = sals[tp->static_trace_marker_id_idx];
13134       sals.resize (1);
13135       return sals;
13136     }
13137   else
13138     error (_("marker %s not found"), tp->static_trace_marker_id.c_str ());
13139 }
13140
13141 static struct breakpoint_ops strace_marker_breakpoint_ops;
13142
13143 static int
13144 strace_marker_p (struct breakpoint *b)
13145 {
13146   return b->ops == &strace_marker_breakpoint_ops;
13147 }
13148
13149 /* Delete a breakpoint and clean up all traces of it in the data
13150    structures.  */
13151
13152 void
13153 delete_breakpoint (struct breakpoint *bpt)
13154 {
13155   struct breakpoint *b;
13156
13157   gdb_assert (bpt != NULL);
13158
13159   /* Has this bp already been deleted?  This can happen because
13160      multiple lists can hold pointers to bp's.  bpstat lists are
13161      especial culprits.
13162
13163      One example of this happening is a watchpoint's scope bp.  When
13164      the scope bp triggers, we notice that the watchpoint is out of
13165      scope, and delete it.  We also delete its scope bp.  But the
13166      scope bp is marked "auto-deleting", and is already on a bpstat.
13167      That bpstat is then checked for auto-deleting bp's, which are
13168      deleted.
13169
13170      A real solution to this problem might involve reference counts in
13171      bp's, and/or giving them pointers back to their referencing
13172      bpstat's, and teaching delete_breakpoint to only free a bp's
13173      storage when no more references were extent.  A cheaper bandaid
13174      was chosen.  */
13175   if (bpt->type == bp_none)
13176     return;
13177
13178   /* At least avoid this stale reference until the reference counting
13179      of breakpoints gets resolved.  */
13180   if (bpt->related_breakpoint != bpt)
13181     {
13182       struct breakpoint *related;
13183       struct watchpoint *w;
13184
13185       if (bpt->type == bp_watchpoint_scope)
13186         w = (struct watchpoint *) bpt->related_breakpoint;
13187       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13188         w = (struct watchpoint *) bpt;
13189       else
13190         w = NULL;
13191       if (w != NULL)
13192         watchpoint_del_at_next_stop (w);
13193
13194       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13195       for (related = bpt; related->related_breakpoint != bpt;
13196            related = related->related_breakpoint);
13197       related->related_breakpoint = bpt->related_breakpoint;
13198       bpt->related_breakpoint = bpt;
13199     }
13200
13201   /* watch_command_1 creates a watchpoint but only sets its number if
13202      update_watchpoint succeeds in creating its bp_locations.  If there's
13203      a problem in that process, we'll be asked to delete the half-created
13204      watchpoint.  In that case, don't announce the deletion.  */
13205   if (bpt->number)
13206     gdb::observers::breakpoint_deleted.notify (bpt);
13207
13208   if (breakpoint_chain == bpt)
13209     breakpoint_chain = bpt->next;
13210
13211   ALL_BREAKPOINTS (b)
13212     if (b->next == bpt)
13213     {
13214       b->next = bpt->next;
13215       break;
13216     }
13217
13218   /* Be sure no bpstat's are pointing at the breakpoint after it's
13219      been freed.  */
13220   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13221      in all threads for now.  Note that we cannot just remove bpstats
13222      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13223      commands are associated with the bpstat; if we remove it here,
13224      then the later call to bpstat_do_actions (&stop_bpstat); in
13225      event-top.c won't do anything, and temporary breakpoints with
13226      commands won't work.  */
13227
13228   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13229
13230   /* Now that breakpoint is removed from breakpoint list, update the
13231      global location list.  This will remove locations that used to
13232      belong to this breakpoint.  Do this before freeing the breakpoint
13233      itself, since remove_breakpoint looks at location's owner.  It
13234      might be better design to have location completely
13235      self-contained, but it's not the case now.  */
13236   update_global_location_list (UGLL_DONT_INSERT);
13237
13238   /* On the chance that someone will soon try again to delete this
13239      same bp, we mark it as deleted before freeing its storage.  */
13240   bpt->type = bp_none;
13241   delete bpt;
13242 }
13243
13244 /* Iterator function to call a user-provided callback function once
13245    for each of B and its related breakpoints.  */
13246
13247 static void
13248 iterate_over_related_breakpoints (struct breakpoint *b,
13249                                   gdb::function_view<void (breakpoint *)> function)
13250 {
13251   struct breakpoint *related;
13252
13253   related = b;
13254   do
13255     {
13256       struct breakpoint *next;
13257
13258       /* FUNCTION may delete RELATED.  */
13259       next = related->related_breakpoint;
13260
13261       if (next == related)
13262         {
13263           /* RELATED is the last ring entry.  */
13264           function (related);
13265
13266           /* FUNCTION may have deleted it, so we'd never reach back to
13267              B.  There's nothing left to do anyway, so just break
13268              out.  */
13269           break;
13270         }
13271       else
13272         function (related);
13273
13274       related = next;
13275     }
13276   while (related != b);
13277 }
13278
13279 static void
13280 delete_command (const char *arg, int from_tty)
13281 {
13282   struct breakpoint *b, *b_tmp;
13283
13284   dont_repeat ();
13285
13286   if (arg == 0)
13287     {
13288       int breaks_to_delete = 0;
13289
13290       /* Delete all breakpoints if no argument.  Do not delete
13291          internal breakpoints, these have to be deleted with an
13292          explicit breakpoint number argument.  */
13293       ALL_BREAKPOINTS (b)
13294         if (user_breakpoint_p (b))
13295           {
13296             breaks_to_delete = 1;
13297             break;
13298           }
13299
13300       /* Ask user only if there are some breakpoints to delete.  */
13301       if (!from_tty
13302           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13303         {
13304           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13305             if (user_breakpoint_p (b))
13306               delete_breakpoint (b);
13307         }
13308     }
13309   else
13310     map_breakpoint_numbers
13311       (arg, [&] (breakpoint *b)
13312        {
13313          iterate_over_related_breakpoints (b, delete_breakpoint);
13314        });
13315 }
13316
13317 /* Return true if all locations of B bound to PSPACE are pending.  If
13318    PSPACE is NULL, all locations of all program spaces are
13319    considered.  */
13320
13321 static int
13322 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13323 {
13324   struct bp_location *loc;
13325
13326   for (loc = b->loc; loc != NULL; loc = loc->next)
13327     if ((pspace == NULL
13328          || loc->pspace == pspace)
13329         && !loc->shlib_disabled
13330         && !loc->pspace->executing_startup)
13331       return 0;
13332   return 1;
13333 }
13334
13335 /* Subroutine of update_breakpoint_locations to simplify it.
13336    Return non-zero if multiple fns in list LOC have the same name.
13337    Null names are ignored.  */
13338
13339 static int
13340 ambiguous_names_p (struct bp_location *loc)
13341 {
13342   struct bp_location *l;
13343   htab_t htab = htab_create_alloc (13, htab_hash_string, streq_hash, NULL,
13344                                    xcalloc, xfree);
13345
13346   for (l = loc; l != NULL; l = l->next)
13347     {
13348       const char **slot;
13349       const char *name = l->function_name;
13350
13351       /* Allow for some names to be NULL, ignore them.  */
13352       if (name == NULL)
13353         continue;
13354
13355       slot = (const char **) htab_find_slot (htab, (const void *) name,
13356                                              INSERT);
13357       /* NOTE: We can assume slot != NULL here because xcalloc never
13358          returns NULL.  */
13359       if (*slot != NULL)
13360         {
13361           htab_delete (htab);
13362           return 1;
13363         }
13364       *slot = name;
13365     }
13366
13367   htab_delete (htab);
13368   return 0;
13369 }
13370
13371 /* When symbols change, it probably means the sources changed as well,
13372    and it might mean the static tracepoint markers are no longer at
13373    the same address or line numbers they used to be at last we
13374    checked.  Losing your static tracepoints whenever you rebuild is
13375    undesirable.  This function tries to resync/rematch gdb static
13376    tracepoints with the markers on the target, for static tracepoints
13377    that have not been set by marker id.  Static tracepoint that have
13378    been set by marker id are reset by marker id in breakpoint_re_set.
13379    The heuristic is:
13380
13381    1) For a tracepoint set at a specific address, look for a marker at
13382    the old PC.  If one is found there, assume to be the same marker.
13383    If the name / string id of the marker found is different from the
13384    previous known name, assume that means the user renamed the marker
13385    in the sources, and output a warning.
13386
13387    2) For a tracepoint set at a given line number, look for a marker
13388    at the new address of the old line number.  If one is found there,
13389    assume to be the same marker.  If the name / string id of the
13390    marker found is different from the previous known name, assume that
13391    means the user renamed the marker in the sources, and output a
13392    warning.
13393
13394    3) If a marker is no longer found at the same address or line, it
13395    may mean the marker no longer exists.  But it may also just mean
13396    the code changed a bit.  Maybe the user added a few lines of code
13397    that made the marker move up or down (in line number terms).  Ask
13398    the target for info about the marker with the string id as we knew
13399    it.  If found, update line number and address in the matching
13400    static tracepoint.  This will get confused if there's more than one
13401    marker with the same ID (possible in UST, although unadvised
13402    precisely because it confuses tools).  */
13403
13404 static struct symtab_and_line
13405 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13406 {
13407   struct tracepoint *tp = (struct tracepoint *) b;
13408   struct static_tracepoint_marker marker;
13409   CORE_ADDR pc;
13410
13411   pc = sal.pc;
13412   if (sal.line)
13413     find_line_pc (sal.symtab, sal.line, &pc);
13414
13415   if (target_static_tracepoint_marker_at (pc, &marker))
13416     {
13417       if (tp->static_trace_marker_id != marker.str_id)
13418         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13419                  b->number, tp->static_trace_marker_id.c_str (),
13420                  marker.str_id.c_str ());
13421
13422       tp->static_trace_marker_id = std::move (marker.str_id);
13423
13424       return sal;
13425     }
13426
13427   /* Old marker wasn't found on target at lineno.  Try looking it up
13428      by string ID.  */
13429   if (!sal.explicit_pc
13430       && sal.line != 0
13431       && sal.symtab != NULL
13432       && !tp->static_trace_marker_id.empty ())
13433     {
13434       std::vector<static_tracepoint_marker> markers
13435         = target_static_tracepoint_markers_by_strid
13436             (tp->static_trace_marker_id.c_str ());
13437
13438       if (!markers.empty ())
13439         {
13440           struct symbol *sym;
13441           struct static_tracepoint_marker *tpmarker;
13442           struct ui_out *uiout = current_uiout;
13443           struct explicit_location explicit_loc;
13444
13445           tpmarker = &markers[0];
13446
13447           tp->static_trace_marker_id = std::move (tpmarker->str_id);
13448
13449           warning (_("marker for static tracepoint %d (%s) not "
13450                      "found at previous line number"),
13451                    b->number, tp->static_trace_marker_id.c_str ());
13452
13453           symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
13454           sym = find_pc_sect_function (tpmarker->address, NULL);
13455           uiout->text ("Now in ");
13456           if (sym)
13457             {
13458               uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
13459               uiout->text (" at ");
13460             }
13461           uiout->field_string ("file",
13462                                symtab_to_filename_for_display (sal2.symtab));
13463           uiout->text (":");
13464
13465           if (uiout->is_mi_like_p ())
13466             {
13467               const char *fullname = symtab_to_fullname (sal2.symtab);
13468
13469               uiout->field_string ("fullname", fullname);
13470             }
13471
13472           uiout->field_int ("line", sal2.line);
13473           uiout->text ("\n");
13474
13475           b->loc->line_number = sal2.line;
13476           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13477
13478           b->location.reset (NULL);
13479           initialize_explicit_location (&explicit_loc);
13480           explicit_loc.source_filename
13481             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
13482           explicit_loc.line_offset.offset = b->loc->line_number;
13483           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
13484           b->location = new_explicit_location (&explicit_loc);
13485
13486           /* Might be nice to check if function changed, and warn if
13487              so.  */
13488         }
13489     }
13490   return sal;
13491 }
13492
13493 /* Returns 1 iff locations A and B are sufficiently same that
13494    we don't need to report breakpoint as changed.  */
13495
13496 static int
13497 locations_are_equal (struct bp_location *a, struct bp_location *b)
13498 {
13499   while (a && b)
13500     {
13501       if (a->address != b->address)
13502         return 0;
13503
13504       if (a->shlib_disabled != b->shlib_disabled)
13505         return 0;
13506
13507       if (a->enabled != b->enabled)
13508         return 0;
13509
13510       a = a->next;
13511       b = b->next;
13512     }
13513
13514   if ((a == NULL) != (b == NULL))
13515     return 0;
13516
13517   return 1;
13518 }
13519
13520 /* Split all locations of B that are bound to PSPACE out of B's
13521    location list to a separate list and return that list's head.  If
13522    PSPACE is NULL, hoist out all locations of B.  */
13523
13524 static struct bp_location *
13525 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
13526 {
13527   struct bp_location head;
13528   struct bp_location *i = b->loc;
13529   struct bp_location **i_link = &b->loc;
13530   struct bp_location *hoisted = &head;
13531
13532   if (pspace == NULL)
13533     {
13534       i = b->loc;
13535       b->loc = NULL;
13536       return i;
13537     }
13538
13539   head.next = NULL;
13540
13541   while (i != NULL)
13542     {
13543       if (i->pspace == pspace)
13544         {
13545           *i_link = i->next;
13546           i->next = NULL;
13547           hoisted->next = i;
13548           hoisted = i;
13549         }
13550       else
13551         i_link = &i->next;
13552       i = *i_link;
13553     }
13554
13555   return head.next;
13556 }
13557
13558 /* Create new breakpoint locations for B (a hardware or software
13559    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
13560    zero, then B is a ranged breakpoint.  Only recreates locations for
13561    FILTER_PSPACE.  Locations of other program spaces are left
13562    untouched.  */
13563
13564 void
13565 update_breakpoint_locations (struct breakpoint *b,
13566                              struct program_space *filter_pspace,
13567                              gdb::array_view<const symtab_and_line> sals,
13568                              gdb::array_view<const symtab_and_line> sals_end)
13569 {
13570   struct bp_location *existing_locations;
13571
13572   if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
13573     {
13574       /* Ranged breakpoints have only one start location and one end
13575          location.  */
13576       b->enable_state = bp_disabled;
13577       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13578                            "multiple locations found\n"),
13579                          b->number);
13580       return;
13581     }
13582
13583   /* If there's no new locations, and all existing locations are
13584      pending, don't do anything.  This optimizes the common case where
13585      all locations are in the same shared library, that was unloaded.
13586      We'd like to retain the location, so that when the library is
13587      loaded again, we don't loose the enabled/disabled status of the
13588      individual locations.  */
13589   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
13590     return;
13591
13592   existing_locations = hoist_existing_locations (b, filter_pspace);
13593
13594   for (const auto &sal : sals)
13595     {
13596       struct bp_location *new_loc;
13597
13598       switch_to_program_space_and_thread (sal.pspace);
13599
13600       new_loc = add_location_to_breakpoint (b, &sal);
13601
13602       /* Reparse conditions, they might contain references to the
13603          old symtab.  */
13604       if (b->cond_string != NULL)
13605         {
13606           const char *s;
13607
13608           s = b->cond_string;
13609           TRY
13610             {
13611               new_loc->cond = parse_exp_1 (&s, sal.pc,
13612                                            block_for_pc (sal.pc),
13613                                            0);
13614             }
13615           CATCH (e, RETURN_MASK_ERROR)
13616             {
13617               warning (_("failed to reevaluate condition "
13618                          "for breakpoint %d: %s"), 
13619                        b->number, e.message);
13620               new_loc->enabled = 0;
13621             }
13622           END_CATCH
13623         }
13624
13625       if (!sals_end.empty ())
13626         {
13627           CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13628
13629           new_loc->length = end - sals[0].pc + 1;
13630         }
13631     }
13632
13633   /* If possible, carry over 'disable' status from existing
13634      breakpoints.  */
13635   {
13636     struct bp_location *e = existing_locations;
13637     /* If there are multiple breakpoints with the same function name,
13638        e.g. for inline functions, comparing function names won't work.
13639        Instead compare pc addresses; this is just a heuristic as things
13640        may have moved, but in practice it gives the correct answer
13641        often enough until a better solution is found.  */
13642     int have_ambiguous_names = ambiguous_names_p (b->loc);
13643
13644     for (; e; e = e->next)
13645       {
13646         if (!e->enabled && e->function_name)
13647           {
13648             struct bp_location *l = b->loc;
13649             if (have_ambiguous_names)
13650               {
13651                 for (; l; l = l->next)
13652                   if (breakpoint_locations_match (e, l))
13653                     {
13654                       l->enabled = 0;
13655                       break;
13656                     }
13657               }
13658             else
13659               {
13660                 for (; l; l = l->next)
13661                   if (l->function_name
13662                       && strcmp (e->function_name, l->function_name) == 0)
13663                     {
13664                       l->enabled = 0;
13665                       break;
13666                     }
13667               }
13668           }
13669       }
13670   }
13671
13672   if (!locations_are_equal (existing_locations, b->loc))
13673     gdb::observers::breakpoint_modified.notify (b);
13674 }
13675
13676 /* Find the SaL locations corresponding to the given LOCATION.
13677    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13678
13679 static std::vector<symtab_and_line>
13680 location_to_sals (struct breakpoint *b, struct event_location *location,
13681                   struct program_space *search_pspace, int *found)
13682 {
13683   struct gdb_exception exception = exception_none;
13684
13685   gdb_assert (b->ops != NULL);
13686
13687   std::vector<symtab_and_line> sals;
13688
13689   TRY
13690     {
13691       sals = b->ops->decode_location (b, location, search_pspace);
13692     }
13693   CATCH (e, RETURN_MASK_ERROR)
13694     {
13695       int not_found_and_ok = 0;
13696
13697       exception = e;
13698
13699       /* For pending breakpoints, it's expected that parsing will
13700          fail until the right shared library is loaded.  User has
13701          already told to create pending breakpoints and don't need
13702          extra messages.  If breakpoint is in bp_shlib_disabled
13703          state, then user already saw the message about that
13704          breakpoint being disabled, and don't want to see more
13705          errors.  */
13706       if (e.error == NOT_FOUND_ERROR
13707           && (b->condition_not_parsed
13708               || (b->loc != NULL
13709                   && search_pspace != NULL
13710                   && b->loc->pspace != search_pspace)
13711               || (b->loc && b->loc->shlib_disabled)
13712               || (b->loc && b->loc->pspace->executing_startup)
13713               || b->enable_state == bp_disabled))
13714         not_found_and_ok = 1;
13715
13716       if (!not_found_and_ok)
13717         {
13718           /* We surely don't want to warn about the same breakpoint
13719              10 times.  One solution, implemented here, is disable
13720              the breakpoint on error.  Another solution would be to
13721              have separate 'warning emitted' flag.  Since this
13722              happens only when a binary has changed, I don't know
13723              which approach is better.  */
13724           b->enable_state = bp_disabled;
13725           throw_exception (e);
13726         }
13727     }
13728   END_CATCH
13729
13730   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13731     {
13732       for (auto &sal : sals)
13733         resolve_sal_pc (&sal);
13734       if (b->condition_not_parsed && b->extra_string != NULL)
13735         {
13736           char *cond_string, *extra_string;
13737           int thread, task;
13738
13739           find_condition_and_thread (b->extra_string, sals[0].pc,
13740                                      &cond_string, &thread, &task,
13741                                      &extra_string);
13742           gdb_assert (b->cond_string == NULL);
13743           if (cond_string)
13744             b->cond_string = cond_string;
13745           b->thread = thread;
13746           b->task = task;
13747           if (extra_string)
13748             {
13749               xfree (b->extra_string);
13750               b->extra_string = extra_string;
13751             }
13752           b->condition_not_parsed = 0;
13753         }
13754
13755       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13756         sals[0] = update_static_tracepoint (b, sals[0]);
13757
13758       *found = 1;
13759     }
13760   else
13761     *found = 0;
13762
13763   return sals;
13764 }
13765
13766 /* The default re_set method, for typical hardware or software
13767    breakpoints.  Reevaluate the breakpoint and recreate its
13768    locations.  */
13769
13770 static void
13771 breakpoint_re_set_default (struct breakpoint *b)
13772 {
13773   struct program_space *filter_pspace = current_program_space;
13774   std::vector<symtab_and_line> expanded, expanded_end;
13775
13776   int found;
13777   std::vector<symtab_and_line> sals = location_to_sals (b, b->location.get (),
13778                                                         filter_pspace, &found);
13779   if (found)
13780     expanded = std::move (sals);
13781
13782   if (b->location_range_end != NULL)
13783     {
13784       std::vector<symtab_and_line> sals_end
13785         = location_to_sals (b, b->location_range_end.get (),
13786                             filter_pspace, &found);
13787       if (found)
13788         expanded_end = std::move (sals_end);
13789     }
13790
13791   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
13792 }
13793
13794 /* Default method for creating SALs from an address string.  It basically
13795    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13796
13797 static void
13798 create_sals_from_location_default (const struct event_location *location,
13799                                    struct linespec_result *canonical,
13800                                    enum bptype type_wanted)
13801 {
13802   parse_breakpoint_sals (location, canonical);
13803 }
13804
13805 /* Call create_breakpoints_sal for the given arguments.  This is the default
13806    function for the `create_breakpoints_sal' method of
13807    breakpoint_ops.  */
13808
13809 static void
13810 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13811                                 struct linespec_result *canonical,
13812                                 gdb::unique_xmalloc_ptr<char> cond_string,
13813                                 gdb::unique_xmalloc_ptr<char> extra_string,
13814                                 enum bptype type_wanted,
13815                                 enum bpdisp disposition,
13816                                 int thread,
13817                                 int task, int ignore_count,
13818                                 const struct breakpoint_ops *ops,
13819                                 int from_tty, int enabled,
13820                                 int internal, unsigned flags)
13821 {
13822   create_breakpoints_sal (gdbarch, canonical,
13823                           std::move (cond_string),
13824                           std::move (extra_string),
13825                           type_wanted, disposition,
13826                           thread, task, ignore_count, ops, from_tty,
13827                           enabled, internal, flags);
13828 }
13829
13830 /* Decode the line represented by S by calling decode_line_full.  This is the
13831    default function for the `decode_location' method of breakpoint_ops.  */
13832
13833 static std::vector<symtab_and_line>
13834 decode_location_default (struct breakpoint *b,
13835                          const struct event_location *location,
13836                          struct program_space *search_pspace)
13837 {
13838   struct linespec_result canonical;
13839
13840   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
13841                     (struct symtab *) NULL, 0,
13842                     &canonical, multiple_symbols_all,
13843                     b->filter);
13844
13845   /* We should get 0 or 1 resulting SALs.  */
13846   gdb_assert (canonical.lsals.size () < 2);
13847
13848   if (!canonical.lsals.empty ())
13849     {
13850       const linespec_sals &lsal = canonical.lsals[0];
13851       return std::move (lsal.sals);
13852     }
13853   return {};
13854 }
13855
13856 /* Reset a breakpoint.  */
13857
13858 static void
13859 breakpoint_re_set_one (breakpoint *b)
13860 {
13861   input_radix = b->input_radix;
13862   set_language (b->language);
13863
13864   b->ops->re_set (b);
13865 }
13866
13867 /* Re-set breakpoint locations for the current program space.
13868    Locations bound to other program spaces are left untouched.  */
13869
13870 void
13871 breakpoint_re_set (void)
13872 {
13873   struct breakpoint *b, *b_tmp;
13874
13875   {
13876     scoped_restore_current_language save_language;
13877     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
13878     scoped_restore_current_pspace_and_thread restore_pspace_thread;
13879
13880     /* breakpoint_re_set_one sets the current_language to the language
13881        of the breakpoint it is resetting (see prepare_re_set_context)
13882        before re-evaluating the breakpoint's location.  This change can
13883        unfortunately get undone by accident if the language_mode is set
13884        to auto, and we either switch frames, or more likely in this context,
13885        we select the current frame.
13886
13887        We prevent this by temporarily turning the language_mode to
13888        language_mode_manual.  We restore it once all breakpoints
13889        have been reset.  */
13890     scoped_restore save_language_mode = make_scoped_restore (&language_mode);
13891     language_mode = language_mode_manual;
13892
13893     /* Note: we must not try to insert locations until after all
13894        breakpoints have been re-set.  Otherwise, e.g., when re-setting
13895        breakpoint 1, we'd insert the locations of breakpoint 2, which
13896        hadn't been re-set yet, and thus may have stale locations.  */
13897
13898     ALL_BREAKPOINTS_SAFE (b, b_tmp)
13899       {
13900         TRY
13901           {
13902             breakpoint_re_set_one (b);
13903           }
13904         CATCH (ex, RETURN_MASK_ALL)
13905           {
13906             exception_fprintf (gdb_stderr, ex,
13907                                "Error in re-setting breakpoint %d: ",
13908                                b->number);
13909           }
13910         END_CATCH
13911       }
13912
13913     jit_breakpoint_re_set ();
13914   }
13915
13916   create_overlay_event_breakpoint ();
13917   create_longjmp_master_breakpoint ();
13918   create_std_terminate_master_breakpoint ();
13919   create_exception_master_breakpoint ();
13920
13921   /* Now we can insert.  */
13922   update_global_location_list (UGLL_MAY_INSERT);
13923 }
13924 \f
13925 /* Reset the thread number of this breakpoint:
13926
13927    - If the breakpoint is for all threads, leave it as-is.
13928    - Else, reset it to the current thread for inferior_ptid.  */
13929 void
13930 breakpoint_re_set_thread (struct breakpoint *b)
13931 {
13932   if (b->thread != -1)
13933     {
13934       b->thread = inferior_thread ()->global_num;
13935
13936       /* We're being called after following a fork.  The new fork is
13937          selected as current, and unless this was a vfork will have a
13938          different program space from the original thread.  Reset that
13939          as well.  */
13940       b->loc->pspace = current_program_space;
13941     }
13942 }
13943
13944 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13945    If from_tty is nonzero, it prints a message to that effect,
13946    which ends with a period (no newline).  */
13947
13948 void
13949 set_ignore_count (int bptnum, int count, int from_tty)
13950 {
13951   struct breakpoint *b;
13952
13953   if (count < 0)
13954     count = 0;
13955
13956   ALL_BREAKPOINTS (b)
13957     if (b->number == bptnum)
13958     {
13959       if (is_tracepoint (b))
13960         {
13961           if (from_tty && count != 0)
13962             printf_filtered (_("Ignore count ignored for tracepoint %d."),
13963                              bptnum);
13964           return;
13965         }
13966       
13967       b->ignore_count = count;
13968       if (from_tty)
13969         {
13970           if (count == 0)
13971             printf_filtered (_("Will stop next time "
13972                                "breakpoint %d is reached."),
13973                              bptnum);
13974           else if (count == 1)
13975             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
13976                              bptnum);
13977           else
13978             printf_filtered (_("Will ignore next %d "
13979                                "crossings of breakpoint %d."),
13980                              count, bptnum);
13981         }
13982       gdb::observers::breakpoint_modified.notify (b);
13983       return;
13984     }
13985
13986   error (_("No breakpoint number %d."), bptnum);
13987 }
13988
13989 /* Command to set ignore-count of breakpoint N to COUNT.  */
13990
13991 static void
13992 ignore_command (const char *args, int from_tty)
13993 {
13994   const char *p = args;
13995   int num;
13996
13997   if (p == 0)
13998     error_no_arg (_("a breakpoint number"));
13999
14000   num = get_number (&p);
14001   if (num == 0)
14002     error (_("bad breakpoint number: '%s'"), args);
14003   if (*p == 0)
14004     error (_("Second argument (specified ignore-count) is missing."));
14005
14006   set_ignore_count (num,
14007                     longest_to_int (value_as_long (parse_and_eval (p))),
14008                     from_tty);
14009   if (from_tty)
14010     printf_filtered ("\n");
14011 }
14012 \f
14013
14014 /* Call FUNCTION on each of the breakpoints with numbers in the range
14015    defined by BP_NUM_RANGE (an inclusive range).  */
14016
14017 static void
14018 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
14019                              gdb::function_view<void (breakpoint *)> function)
14020 {
14021   if (bp_num_range.first == 0)
14022     {
14023       warning (_("bad breakpoint number at or near '%d'"),
14024                bp_num_range.first);
14025     }
14026   else
14027     {
14028       struct breakpoint *b, *tmp;
14029
14030       for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
14031         {
14032           bool match = false;
14033
14034           ALL_BREAKPOINTS_SAFE (b, tmp)
14035             if (b->number == i)
14036               {
14037                 match = true;
14038                 function (b);
14039                 break;
14040               }
14041           if (!match)
14042             printf_unfiltered (_("No breakpoint number %d.\n"), i);
14043         }
14044     }
14045 }
14046
14047 /* Call FUNCTION on each of the breakpoints whose numbers are given in
14048    ARGS.  */
14049
14050 static void
14051 map_breakpoint_numbers (const char *args,
14052                         gdb::function_view<void (breakpoint *)> function)
14053 {
14054   if (args == NULL || *args == '\0')
14055     error_no_arg (_("one or more breakpoint numbers"));
14056
14057   number_or_range_parser parser (args);
14058
14059   while (!parser.finished ())
14060     {
14061       int num = parser.get_number ();
14062       map_breakpoint_number_range (std::make_pair (num, num), function);
14063     }
14064 }
14065
14066 /* Return the breakpoint location structure corresponding to the
14067    BP_NUM and LOC_NUM values.  */
14068
14069 static struct bp_location *
14070 find_location_by_number (int bp_num, int loc_num)
14071 {
14072   struct breakpoint *b;
14073
14074   ALL_BREAKPOINTS (b)
14075     if (b->number == bp_num)
14076       {
14077         break;
14078       }
14079
14080   if (!b || b->number != bp_num)
14081     error (_("Bad breakpoint number '%d'"), bp_num);
14082   
14083   if (loc_num == 0)
14084     error (_("Bad breakpoint location number '%d'"), loc_num);
14085
14086   int n = 0;
14087   for (bp_location *loc = b->loc; loc != NULL; loc = loc->next)
14088     if (++n == loc_num)
14089       return loc;
14090
14091   error (_("Bad breakpoint location number '%d'"), loc_num);
14092 }
14093
14094 /* Modes of operation for extract_bp_num.  */
14095 enum class extract_bp_kind
14096 {
14097   /* Extracting a breakpoint number.  */
14098   bp,
14099
14100   /* Extracting a location number.  */
14101   loc,
14102 };
14103
14104 /* Extract a breakpoint or location number (as determined by KIND)
14105    from the string starting at START.  TRAILER is a character which
14106    can be found after the number.  If you don't want a trailer, use
14107    '\0'.  If END_OUT is not NULL, it is set to point after the parsed
14108    string.  This always returns a positive integer.  */
14109
14110 static int
14111 extract_bp_num (extract_bp_kind kind, const char *start,
14112                 int trailer, const char **end_out = NULL)
14113 {
14114   const char *end = start;
14115   int num = get_number_trailer (&end, trailer);
14116   if (num < 0)
14117     error (kind == extract_bp_kind::bp
14118            ? _("Negative breakpoint number '%.*s'")
14119            : _("Negative breakpoint location number '%.*s'"),
14120            int (end - start), start);
14121   if (num == 0)
14122     error (kind == extract_bp_kind::bp
14123            ? _("Bad breakpoint number '%.*s'")
14124            : _("Bad breakpoint location number '%.*s'"),
14125            int (end - start), start);
14126
14127   if (end_out != NULL)
14128     *end_out = end;
14129   return num;
14130 }
14131
14132 /* Extract a breakpoint or location range (as determined by KIND) in
14133    the form NUM1-NUM2 stored at &ARG[arg_offset].  Returns a std::pair
14134    representing the (inclusive) range.  The returned pair's elements
14135    are always positive integers.  */
14136
14137 static std::pair<int, int>
14138 extract_bp_or_bp_range (extract_bp_kind kind,
14139                         const std::string &arg,
14140                         std::string::size_type arg_offset)
14141 {
14142   std::pair<int, int> range;
14143   const char *bp_loc = &arg[arg_offset];
14144   std::string::size_type dash = arg.find ('-', arg_offset);
14145   if (dash != std::string::npos)
14146     {
14147       /* bp_loc is a range (x-z).  */
14148       if (arg.length () == dash + 1)
14149         error (kind == extract_bp_kind::bp
14150                ? _("Bad breakpoint number at or near: '%s'")
14151                : _("Bad breakpoint location number at or near: '%s'"),
14152                bp_loc);
14153
14154       const char *end;
14155       const char *start_first = bp_loc;
14156       const char *start_second = &arg[dash + 1];
14157       range.first = extract_bp_num (kind, start_first, '-');
14158       range.second = extract_bp_num (kind, start_second, '\0', &end);
14159
14160       if (range.first > range.second)
14161         error (kind == extract_bp_kind::bp
14162                ? _("Inverted breakpoint range at '%.*s'")
14163                : _("Inverted breakpoint location range at '%.*s'"),
14164                int (end - start_first), start_first);
14165     }
14166   else
14167     {
14168       /* bp_loc is a single value.  */
14169       range.first = extract_bp_num (kind, bp_loc, '\0');
14170       range.second = range.first;
14171     }
14172   return range;
14173 }
14174
14175 /* Extract the breakpoint/location range specified by ARG.  Returns
14176    the breakpoint range in BP_NUM_RANGE, and the location range in
14177    BP_LOC_RANGE.
14178
14179    ARG may be in any of the following forms:
14180
14181    x     where 'x' is a breakpoint number.
14182    x-y   where 'x' and 'y' specify a breakpoint numbers range.
14183    x.y   where 'x' is a breakpoint number and 'y' a location number.
14184    x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
14185          location number range.
14186 */
14187
14188 static void
14189 extract_bp_number_and_location (const std::string &arg,
14190                                 std::pair<int, int> &bp_num_range,
14191                                 std::pair<int, int> &bp_loc_range)
14192 {
14193   std::string::size_type dot = arg.find ('.');
14194
14195   if (dot != std::string::npos)
14196     {
14197       /* Handle 'x.y' and 'x.y-z' cases.  */
14198
14199       if (arg.length () == dot + 1 || dot == 0)
14200         error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
14201
14202       bp_num_range.first
14203         = extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
14204       bp_num_range.second = bp_num_range.first;
14205
14206       bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
14207                                              arg, dot + 1);
14208     }
14209   else
14210     {
14211       /* Handle x and x-y cases.  */
14212
14213       bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
14214       bp_loc_range.first = 0;
14215       bp_loc_range.second = 0;
14216     }
14217 }
14218
14219 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM.  ENABLE
14220    specifies whether to enable or disable.  */
14221
14222 static void
14223 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
14224 {
14225   struct bp_location *loc = find_location_by_number (bp_num, loc_num);
14226   if (loc != NULL)
14227     {
14228       if (loc->enabled != enable)
14229         {
14230           loc->enabled = enable;
14231           mark_breakpoint_location_modified (loc);
14232         }
14233       if (target_supports_enable_disable_tracepoint ()
14234           && current_trace_status ()->running && loc->owner
14235           && is_tracepoint (loc->owner))
14236         target_disable_tracepoint (loc);
14237     }
14238   update_global_location_list (UGLL_DONT_INSERT);
14239 }
14240
14241 /* Enable or disable a range of breakpoint locations.  BP_NUM is the
14242    number of the breakpoint, and BP_LOC_RANGE specifies the
14243    (inclusive) range of location numbers of that breakpoint to
14244    enable/disable.  ENABLE specifies whether to enable or disable the
14245    location.  */
14246
14247 static void
14248 enable_disable_breakpoint_location_range (int bp_num,
14249                                           std::pair<int, int> &bp_loc_range,
14250                                           bool enable)
14251 {
14252   for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
14253     enable_disable_bp_num_loc (bp_num, i, enable);
14254 }
14255
14256 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14257    If from_tty is nonzero, it prints a message to that effect,
14258    which ends with a period (no newline).  */
14259
14260 void
14261 disable_breakpoint (struct breakpoint *bpt)
14262 {
14263   /* Never disable a watchpoint scope breakpoint; we want to
14264      hit them when we leave scope so we can delete both the
14265      watchpoint and its scope breakpoint at that time.  */
14266   if (bpt->type == bp_watchpoint_scope)
14267     return;
14268
14269   bpt->enable_state = bp_disabled;
14270
14271   /* Mark breakpoint locations modified.  */
14272   mark_breakpoint_modified (bpt);
14273
14274   if (target_supports_enable_disable_tracepoint ()
14275       && current_trace_status ()->running && is_tracepoint (bpt))
14276     {
14277       struct bp_location *location;
14278      
14279       for (location = bpt->loc; location; location = location->next)
14280         target_disable_tracepoint (location);
14281     }
14282
14283   update_global_location_list (UGLL_DONT_INSERT);
14284
14285   gdb::observers::breakpoint_modified.notify (bpt);
14286 }
14287
14288 /* Enable or disable the breakpoint(s) or breakpoint location(s)
14289    specified in ARGS.  ARGS may be in any of the formats handled by
14290    extract_bp_number_and_location.  ENABLE specifies whether to enable
14291    or disable the breakpoints/locations.  */
14292
14293 static void
14294 enable_disable_command (const char *args, int from_tty, bool enable)
14295 {
14296   if (args == 0)
14297     {
14298       struct breakpoint *bpt;
14299
14300       ALL_BREAKPOINTS (bpt)
14301         if (user_breakpoint_p (bpt))
14302           {
14303             if (enable)
14304               enable_breakpoint (bpt);
14305             else
14306               disable_breakpoint (bpt);
14307           }
14308     }
14309   else
14310     {
14311       std::string num = extract_arg (&args);
14312
14313       while (!num.empty ())
14314         {
14315           std::pair<int, int> bp_num_range, bp_loc_range;
14316
14317           extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
14318
14319           if (bp_loc_range.first == bp_loc_range.second
14320               && bp_loc_range.first == 0)
14321             {
14322               /* Handle breakpoint ids with formats 'x' or 'x-z'.  */
14323               map_breakpoint_number_range (bp_num_range,
14324                                            enable
14325                                            ? enable_breakpoint
14326                                            : disable_breakpoint);
14327             }
14328           else
14329             {
14330               /* Handle breakpoint ids with formats 'x.y' or
14331                  'x.y-z'.  */
14332               enable_disable_breakpoint_location_range
14333                 (bp_num_range.first, bp_loc_range, enable);
14334             }
14335           num = extract_arg (&args);
14336         }
14337     }
14338 }
14339
14340 /* The disable command disables the specified breakpoints/locations
14341    (or all defined breakpoints) so they're no longer effective in
14342    stopping the inferior.  ARGS may be in any of the forms defined in
14343    extract_bp_number_and_location.  */
14344
14345 static void
14346 disable_command (const char *args, int from_tty)
14347 {
14348   enable_disable_command (args, from_tty, false);
14349 }
14350
14351 static void
14352 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14353                         int count)
14354 {
14355   int target_resources_ok;
14356
14357   if (bpt->type == bp_hardware_breakpoint)
14358     {
14359       int i;
14360       i = hw_breakpoint_used_count ();
14361       target_resources_ok = 
14362         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14363                                             i + 1, 0);
14364       if (target_resources_ok == 0)
14365         error (_("No hardware breakpoint support in the target."));
14366       else if (target_resources_ok < 0)
14367         error (_("Hardware breakpoints used exceeds limit."));
14368     }
14369
14370   if (is_watchpoint (bpt))
14371     {
14372       /* Initialize it just to avoid a GCC false warning.  */
14373       enum enable_state orig_enable_state = bp_disabled;
14374
14375       TRY
14376         {
14377           struct watchpoint *w = (struct watchpoint *) bpt;
14378
14379           orig_enable_state = bpt->enable_state;
14380           bpt->enable_state = bp_enabled;
14381           update_watchpoint (w, 1 /* reparse */);
14382         }
14383       CATCH (e, RETURN_MASK_ALL)
14384         {
14385           bpt->enable_state = orig_enable_state;
14386           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14387                              bpt->number);
14388           return;
14389         }
14390       END_CATCH
14391     }
14392
14393   bpt->enable_state = bp_enabled;
14394
14395   /* Mark breakpoint locations modified.  */
14396   mark_breakpoint_modified (bpt);
14397
14398   if (target_supports_enable_disable_tracepoint ()
14399       && current_trace_status ()->running && is_tracepoint (bpt))
14400     {
14401       struct bp_location *location;
14402
14403       for (location = bpt->loc; location; location = location->next)
14404         target_enable_tracepoint (location);
14405     }
14406
14407   bpt->disposition = disposition;
14408   bpt->enable_count = count;
14409   update_global_location_list (UGLL_MAY_INSERT);
14410
14411   gdb::observers::breakpoint_modified.notify (bpt);
14412 }
14413
14414
14415 void
14416 enable_breakpoint (struct breakpoint *bpt)
14417 {
14418   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14419 }
14420
14421 /* The enable command enables the specified breakpoints/locations (or
14422    all defined breakpoints) so they once again become (or continue to
14423    be) effective in stopping the inferior.  ARGS may be in any of the
14424    forms defined in extract_bp_number_and_location.  */
14425
14426 static void
14427 enable_command (const char *args, int from_tty)
14428 {
14429   enable_disable_command (args, from_tty, true);
14430 }
14431
14432 static void
14433 enable_once_command (const char *args, int from_tty)
14434 {
14435   map_breakpoint_numbers
14436     (args, [&] (breakpoint *b)
14437      {
14438        iterate_over_related_breakpoints
14439          (b, [&] (breakpoint *bpt)
14440           {
14441             enable_breakpoint_disp (bpt, disp_disable, 1);
14442           });
14443      });
14444 }
14445
14446 static void
14447 enable_count_command (const char *args, int from_tty)
14448 {
14449   int count;
14450
14451   if (args == NULL)
14452     error_no_arg (_("hit count"));
14453
14454   count = get_number (&args);
14455
14456   map_breakpoint_numbers
14457     (args, [&] (breakpoint *b)
14458      {
14459        iterate_over_related_breakpoints
14460          (b, [&] (breakpoint *bpt)
14461           {
14462             enable_breakpoint_disp (bpt, disp_disable, count);
14463           });
14464      });
14465 }
14466
14467 static void
14468 enable_delete_command (const char *args, int from_tty)
14469 {
14470   map_breakpoint_numbers
14471     (args, [&] (breakpoint *b)
14472      {
14473        iterate_over_related_breakpoints
14474          (b, [&] (breakpoint *bpt)
14475           {
14476             enable_breakpoint_disp (bpt, disp_del, 1);
14477           });
14478      });
14479 }
14480 \f
14481 static void
14482 set_breakpoint_cmd (const char *args, int from_tty)
14483 {
14484 }
14485
14486 static void
14487 show_breakpoint_cmd (const char *args, int from_tty)
14488 {
14489 }
14490
14491 /* Invalidate last known value of any hardware watchpoint if
14492    the memory which that value represents has been written to by
14493    GDB itself.  */
14494
14495 static void
14496 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14497                                       CORE_ADDR addr, ssize_t len,
14498                                       const bfd_byte *data)
14499 {
14500   struct breakpoint *bp;
14501
14502   ALL_BREAKPOINTS (bp)
14503     if (bp->enable_state == bp_enabled
14504         && bp->type == bp_hardware_watchpoint)
14505       {
14506         struct watchpoint *wp = (struct watchpoint *) bp;
14507
14508         if (wp->val_valid && wp->val != nullptr)
14509           {
14510             struct bp_location *loc;
14511
14512             for (loc = bp->loc; loc != NULL; loc = loc->next)
14513               if (loc->loc_type == bp_loc_hardware_watchpoint
14514                   && loc->address + loc->length > addr
14515                   && addr + len > loc->address)
14516                 {
14517                   wp->val = NULL;
14518                   wp->val_valid = 0;
14519                 }
14520           }
14521       }
14522 }
14523
14524 /* Create and insert a breakpoint for software single step.  */
14525
14526 void
14527 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14528                                const address_space *aspace,
14529                                CORE_ADDR next_pc)
14530 {
14531   struct thread_info *tp = inferior_thread ();
14532   struct symtab_and_line sal;
14533   CORE_ADDR pc = next_pc;
14534
14535   if (tp->control.single_step_breakpoints == NULL)
14536     {
14537       tp->control.single_step_breakpoints
14538         = new_single_step_breakpoint (tp->global_num, gdbarch);
14539     }
14540
14541   sal = find_pc_line (pc, 0);
14542   sal.pc = pc;
14543   sal.section = find_pc_overlay (pc);
14544   sal.explicit_pc = 1;
14545   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14546
14547   update_global_location_list (UGLL_INSERT);
14548 }
14549
14550 /* Insert single step breakpoints according to the current state.  */
14551
14552 int
14553 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14554 {
14555   struct regcache *regcache = get_current_regcache ();
14556   std::vector<CORE_ADDR> next_pcs;
14557
14558   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14559
14560   if (!next_pcs.empty ())
14561     {
14562       struct frame_info *frame = get_current_frame ();
14563       const address_space *aspace = get_frame_address_space (frame);
14564
14565       for (CORE_ADDR pc : next_pcs)
14566         insert_single_step_breakpoint (gdbarch, aspace, pc);
14567
14568       return 1;
14569     }
14570   else
14571     return 0;
14572 }
14573
14574 /* See breakpoint.h.  */
14575
14576 int
14577 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14578                                        const address_space *aspace,
14579                                        CORE_ADDR pc)
14580 {
14581   struct bp_location *loc;
14582
14583   for (loc = bp->loc; loc != NULL; loc = loc->next)
14584     if (loc->inserted
14585         && breakpoint_location_address_match (loc, aspace, pc))
14586       return 1;
14587
14588   return 0;
14589 }
14590
14591 /* Check whether a software single-step breakpoint is inserted at
14592    PC.  */
14593
14594 int
14595 single_step_breakpoint_inserted_here_p (const address_space *aspace,
14596                                         CORE_ADDR pc)
14597 {
14598   struct breakpoint *bpt;
14599
14600   ALL_BREAKPOINTS (bpt)
14601     {
14602       if (bpt->type == bp_single_step
14603           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
14604         return 1;
14605     }
14606   return 0;
14607 }
14608
14609 /* Tracepoint-specific operations.  */
14610
14611 /* Set tracepoint count to NUM.  */
14612 static void
14613 set_tracepoint_count (int num)
14614 {
14615   tracepoint_count = num;
14616   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14617 }
14618
14619 static void
14620 trace_command (const char *arg, int from_tty)
14621 {
14622   struct breakpoint_ops *ops;
14623
14624   event_location_up location = string_to_event_location (&arg,
14625                                                          current_language);
14626   if (location != NULL
14627       && event_location_type (location.get ()) == PROBE_LOCATION)
14628     ops = &tracepoint_probe_breakpoint_ops;
14629   else
14630     ops = &tracepoint_breakpoint_ops;
14631
14632   create_breakpoint (get_current_arch (),
14633                      location.get (),
14634                      NULL, 0, arg, 1 /* parse arg */,
14635                      0 /* tempflag */,
14636                      bp_tracepoint /* type_wanted */,
14637                      0 /* Ignore count */,
14638                      pending_break_support,
14639                      ops,
14640                      from_tty,
14641                      1 /* enabled */,
14642                      0 /* internal */, 0);
14643 }
14644
14645 static void
14646 ftrace_command (const char *arg, int from_tty)
14647 {
14648   event_location_up location = string_to_event_location (&arg,
14649                                                          current_language);
14650   create_breakpoint (get_current_arch (),
14651                      location.get (),
14652                      NULL, 0, arg, 1 /* parse arg */,
14653                      0 /* tempflag */,
14654                      bp_fast_tracepoint /* type_wanted */,
14655                      0 /* Ignore count */,
14656                      pending_break_support,
14657                      &tracepoint_breakpoint_ops,
14658                      from_tty,
14659                      1 /* enabled */,
14660                      0 /* internal */, 0);
14661 }
14662
14663 /* strace command implementation.  Creates a static tracepoint.  */
14664
14665 static void
14666 strace_command (const char *arg, int from_tty)
14667 {
14668   struct breakpoint_ops *ops;
14669   event_location_up location;
14670
14671   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14672      or with a normal static tracepoint.  */
14673   if (arg && startswith (arg, "-m") && isspace (arg[2]))
14674     {
14675       ops = &strace_marker_breakpoint_ops;
14676       location = new_linespec_location (&arg, symbol_name_match_type::FULL);
14677     }
14678   else
14679     {
14680       ops = &tracepoint_breakpoint_ops;
14681       location = string_to_event_location (&arg, current_language);
14682     }
14683
14684   create_breakpoint (get_current_arch (),
14685                      location.get (),
14686                      NULL, 0, arg, 1 /* parse arg */,
14687                      0 /* tempflag */,
14688                      bp_static_tracepoint /* type_wanted */,
14689                      0 /* Ignore count */,
14690                      pending_break_support,
14691                      ops,
14692                      from_tty,
14693                      1 /* enabled */,
14694                      0 /* internal */, 0);
14695 }
14696
14697 /* Set up a fake reader function that gets command lines from a linked
14698    list that was acquired during tracepoint uploading.  */
14699
14700 static struct uploaded_tp *this_utp;
14701 static int next_cmd;
14702
14703 static char *
14704 read_uploaded_action (void)
14705 {
14706   char *rslt = nullptr;
14707
14708   if (next_cmd < this_utp->cmd_strings.size ())
14709     {
14710       rslt = this_utp->cmd_strings[next_cmd];
14711       next_cmd++;
14712     }
14713
14714   return rslt;
14715 }
14716
14717 /* Given information about a tracepoint as recorded on a target (which
14718    can be either a live system or a trace file), attempt to create an
14719    equivalent GDB tracepoint.  This is not a reliable process, since
14720    the target does not necessarily have all the information used when
14721    the tracepoint was originally defined.  */
14722   
14723 struct tracepoint *
14724 create_tracepoint_from_upload (struct uploaded_tp *utp)
14725 {
14726   const char *addr_str;
14727   char small_buf[100];
14728   struct tracepoint *tp;
14729
14730   if (utp->at_string)
14731     addr_str = utp->at_string;
14732   else
14733     {
14734       /* In the absence of a source location, fall back to raw
14735          address.  Since there is no way to confirm that the address
14736          means the same thing as when the trace was started, warn the
14737          user.  */
14738       warning (_("Uploaded tracepoint %d has no "
14739                  "source location, using raw address"),
14740                utp->number);
14741       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14742       addr_str = small_buf;
14743     }
14744
14745   /* There's not much we can do with a sequence of bytecodes.  */
14746   if (utp->cond && !utp->cond_string)
14747     warning (_("Uploaded tracepoint %d condition "
14748                "has no source form, ignoring it"),
14749              utp->number);
14750
14751   event_location_up location = string_to_event_location (&addr_str,
14752                                                          current_language);
14753   if (!create_breakpoint (get_current_arch (),
14754                           location.get (),
14755                           utp->cond_string, -1, addr_str,
14756                           0 /* parse cond/thread */,
14757                           0 /* tempflag */,
14758                           utp->type /* type_wanted */,
14759                           0 /* Ignore count */,
14760                           pending_break_support,
14761                           &tracepoint_breakpoint_ops,
14762                           0 /* from_tty */,
14763                           utp->enabled /* enabled */,
14764                           0 /* internal */,
14765                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14766     return NULL;
14767
14768   /* Get the tracepoint we just created.  */
14769   tp = get_tracepoint (tracepoint_count);
14770   gdb_assert (tp != NULL);
14771
14772   if (utp->pass > 0)
14773     {
14774       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14775                  tp->number);
14776
14777       trace_pass_command (small_buf, 0);
14778     }
14779
14780   /* If we have uploaded versions of the original commands, set up a
14781      special-purpose "reader" function and call the usual command line
14782      reader, then pass the result to the breakpoint command-setting
14783      function.  */
14784   if (!utp->cmd_strings.empty ())
14785     {
14786       counted_command_line cmd_list;
14787
14788       this_utp = utp;
14789       next_cmd = 0;
14790
14791       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL);
14792
14793       breakpoint_set_commands (tp, std::move (cmd_list));
14794     }
14795   else if (!utp->actions.empty ()
14796            || !utp->step_actions.empty ())
14797     warning (_("Uploaded tracepoint %d actions "
14798                "have no source form, ignoring them"),
14799              utp->number);
14800
14801   /* Copy any status information that might be available.  */
14802   tp->hit_count = utp->hit_count;
14803   tp->traceframe_usage = utp->traceframe_usage;
14804
14805   return tp;
14806 }
14807   
14808 /* Print information on tracepoint number TPNUM_EXP, or all if
14809    omitted.  */
14810
14811 static void
14812 info_tracepoints_command (const char *args, int from_tty)
14813 {
14814   struct ui_out *uiout = current_uiout;
14815   int num_printed;
14816
14817   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14818
14819   if (num_printed == 0)
14820     {
14821       if (args == NULL || *args == '\0')
14822         uiout->message ("No tracepoints.\n");
14823       else
14824         uiout->message ("No tracepoint matching '%s'.\n", args);
14825     }
14826
14827   default_collect_info ();
14828 }
14829
14830 /* The 'enable trace' command enables tracepoints.
14831    Not supported by all targets.  */
14832 static void
14833 enable_trace_command (const char *args, int from_tty)
14834 {
14835   enable_command (args, from_tty);
14836 }
14837
14838 /* The 'disable trace' command disables tracepoints.
14839    Not supported by all targets.  */
14840 static void
14841 disable_trace_command (const char *args, int from_tty)
14842 {
14843   disable_command (args, from_tty);
14844 }
14845
14846 /* Remove a tracepoint (or all if no argument).  */
14847 static void
14848 delete_trace_command (const char *arg, int from_tty)
14849 {
14850   struct breakpoint *b, *b_tmp;
14851
14852   dont_repeat ();
14853
14854   if (arg == 0)
14855     {
14856       int breaks_to_delete = 0;
14857
14858       /* Delete all breakpoints if no argument.
14859          Do not delete internal or call-dummy breakpoints, these
14860          have to be deleted with an explicit breakpoint number 
14861          argument.  */
14862       ALL_TRACEPOINTS (b)
14863         if (is_tracepoint (b) && user_breakpoint_p (b))
14864           {
14865             breaks_to_delete = 1;
14866             break;
14867           }
14868
14869       /* Ask user only if there are some breakpoints to delete.  */
14870       if (!from_tty
14871           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14872         {
14873           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14874             if (is_tracepoint (b) && user_breakpoint_p (b))
14875               delete_breakpoint (b);
14876         }
14877     }
14878   else
14879     map_breakpoint_numbers
14880       (arg, [&] (breakpoint *b)
14881        {
14882          iterate_over_related_breakpoints (b, delete_breakpoint);
14883        });
14884 }
14885
14886 /* Helper function for trace_pass_command.  */
14887
14888 static void
14889 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14890 {
14891   tp->pass_count = count;
14892   gdb::observers::breakpoint_modified.notify (tp);
14893   if (from_tty)
14894     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
14895                      tp->number, count);
14896 }
14897
14898 /* Set passcount for tracepoint.
14899
14900    First command argument is passcount, second is tracepoint number.
14901    If tracepoint number omitted, apply to most recently defined.
14902    Also accepts special argument "all".  */
14903
14904 static void
14905 trace_pass_command (const char *args, int from_tty)
14906 {
14907   struct tracepoint *t1;
14908   ULONGEST count;
14909
14910   if (args == 0 || *args == 0)
14911     error (_("passcount command requires an "
14912              "argument (count + optional TP num)"));
14913
14914   count = strtoulst (args, &args, 10);  /* Count comes first, then TP num.  */
14915
14916   args = skip_spaces (args);
14917   if (*args && strncasecmp (args, "all", 3) == 0)
14918     {
14919       struct breakpoint *b;
14920
14921       args += 3;                        /* Skip special argument "all".  */
14922       if (*args)
14923         error (_("Junk at end of arguments."));
14924
14925       ALL_TRACEPOINTS (b)
14926       {
14927         t1 = (struct tracepoint *) b;
14928         trace_pass_set_count (t1, count, from_tty);
14929       }
14930     }
14931   else if (*args == '\0')
14932     {
14933       t1 = get_tracepoint_by_number (&args, NULL);
14934       if (t1)
14935         trace_pass_set_count (t1, count, from_tty);
14936     }
14937   else
14938     {
14939       number_or_range_parser parser (args);
14940       while (!parser.finished ())
14941         {
14942           t1 = get_tracepoint_by_number (&args, &parser);
14943           if (t1)
14944             trace_pass_set_count (t1, count, from_tty);
14945         }
14946     }
14947 }
14948
14949 struct tracepoint *
14950 get_tracepoint (int num)
14951 {
14952   struct breakpoint *t;
14953
14954   ALL_TRACEPOINTS (t)
14955     if (t->number == num)
14956       return (struct tracepoint *) t;
14957
14958   return NULL;
14959 }
14960
14961 /* Find the tracepoint with the given target-side number (which may be
14962    different from the tracepoint number after disconnecting and
14963    reconnecting).  */
14964
14965 struct tracepoint *
14966 get_tracepoint_by_number_on_target (int num)
14967 {
14968   struct breakpoint *b;
14969
14970   ALL_TRACEPOINTS (b)
14971     {
14972       struct tracepoint *t = (struct tracepoint *) b;
14973
14974       if (t->number_on_target == num)
14975         return t;
14976     }
14977
14978   return NULL;
14979 }
14980
14981 /* Utility: parse a tracepoint number and look it up in the list.
14982    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14983    If the argument is missing, the most recent tracepoint
14984    (tracepoint_count) is returned.  */
14985
14986 struct tracepoint *
14987 get_tracepoint_by_number (const char **arg,
14988                           number_or_range_parser *parser)
14989 {
14990   struct breakpoint *t;
14991   int tpnum;
14992   const char *instring = arg == NULL ? NULL : *arg;
14993
14994   if (parser != NULL)
14995     {
14996       gdb_assert (!parser->finished ());
14997       tpnum = parser->get_number ();
14998     }
14999   else if (arg == NULL || *arg == NULL || ! **arg)
15000     tpnum = tracepoint_count;
15001   else
15002     tpnum = get_number (arg);
15003
15004   if (tpnum <= 0)
15005     {
15006       if (instring && *instring)
15007         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15008                          instring);
15009       else
15010         printf_filtered (_("No previous tracepoint\n"));
15011       return NULL;
15012     }
15013
15014   ALL_TRACEPOINTS (t)
15015     if (t->number == tpnum)
15016     {
15017       return (struct tracepoint *) t;
15018     }
15019
15020   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15021   return NULL;
15022 }
15023
15024 void
15025 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15026 {
15027   if (b->thread != -1)
15028     fprintf_unfiltered (fp, " thread %d", b->thread);
15029
15030   if (b->task != 0)
15031     fprintf_unfiltered (fp, " task %d", b->task);
15032
15033   fprintf_unfiltered (fp, "\n");
15034 }
15035
15036 /* Save information on user settable breakpoints (watchpoints, etc) to
15037    a new script file named FILENAME.  If FILTER is non-NULL, call it
15038    on each breakpoint and only include the ones for which it returns
15039    non-zero.  */
15040
15041 static void
15042 save_breakpoints (const char *filename, int from_tty,
15043                   int (*filter) (const struct breakpoint *))
15044 {
15045   struct breakpoint *tp;
15046   int any = 0;
15047   int extra_trace_bits = 0;
15048
15049   if (filename == 0 || *filename == 0)
15050     error (_("Argument required (file name in which to save)"));
15051
15052   /* See if we have anything to save.  */
15053   ALL_BREAKPOINTS (tp)
15054   {
15055     /* Skip internal and momentary breakpoints.  */
15056     if (!user_breakpoint_p (tp))
15057       continue;
15058
15059     /* If we have a filter, only save the breakpoints it accepts.  */
15060     if (filter && !filter (tp))
15061       continue;
15062
15063     any = 1;
15064
15065     if (is_tracepoint (tp))
15066       {
15067         extra_trace_bits = 1;
15068
15069         /* We can stop searching.  */
15070         break;
15071       }
15072   }
15073
15074   if (!any)
15075     {
15076       warning (_("Nothing to save."));
15077       return;
15078     }
15079
15080   gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
15081
15082   stdio_file fp;
15083
15084   if (!fp.open (expanded_filename.get (), "w"))
15085     error (_("Unable to open file '%s' for saving (%s)"),
15086            expanded_filename.get (), safe_strerror (errno));
15087
15088   if (extra_trace_bits)
15089     save_trace_state_variables (&fp);
15090
15091   ALL_BREAKPOINTS (tp)
15092   {
15093     /* Skip internal and momentary breakpoints.  */
15094     if (!user_breakpoint_p (tp))
15095       continue;
15096
15097     /* If we have a filter, only save the breakpoints it accepts.  */
15098     if (filter && !filter (tp))
15099       continue;
15100
15101     tp->ops->print_recreate (tp, &fp);
15102
15103     /* Note, we can't rely on tp->number for anything, as we can't
15104        assume the recreated breakpoint numbers will match.  Use $bpnum
15105        instead.  */
15106
15107     if (tp->cond_string)
15108       fp.printf ("  condition $bpnum %s\n", tp->cond_string);
15109
15110     if (tp->ignore_count)
15111       fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15112
15113     if (tp->type != bp_dprintf && tp->commands)
15114       {
15115         fp.puts ("  commands\n");
15116         
15117         current_uiout->redirect (&fp);
15118         TRY
15119           {
15120             print_command_lines (current_uiout, tp->commands.get (), 2);
15121           }
15122         CATCH (ex, RETURN_MASK_ALL)
15123           {
15124           current_uiout->redirect (NULL);
15125             throw_exception (ex);
15126           }
15127         END_CATCH
15128
15129         current_uiout->redirect (NULL);
15130         fp.puts ("  end\n");
15131       }
15132
15133     if (tp->enable_state == bp_disabled)
15134       fp.puts ("disable $bpnum\n");
15135
15136     /* If this is a multi-location breakpoint, check if the locations
15137        should be individually disabled.  Watchpoint locations are
15138        special, and not user visible.  */
15139     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15140       {
15141         struct bp_location *loc;
15142         int n = 1;
15143
15144         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15145           if (!loc->enabled)
15146             fp.printf ("disable $bpnum.%d\n", n);
15147       }
15148   }
15149
15150   if (extra_trace_bits && *default_collect)
15151     fp.printf ("set default-collect %s\n", default_collect);
15152
15153   if (from_tty)
15154     printf_filtered (_("Saved to file '%s'.\n"), expanded_filename.get ());
15155 }
15156
15157 /* The `save breakpoints' command.  */
15158
15159 static void
15160 save_breakpoints_command (const char *args, int from_tty)
15161 {
15162   save_breakpoints (args, from_tty, NULL);
15163 }
15164
15165 /* The `save tracepoints' command.  */
15166
15167 static void
15168 save_tracepoints_command (const char *args, int from_tty)
15169 {
15170   save_breakpoints (args, from_tty, is_tracepoint);
15171 }
15172
15173 /* Create a vector of all tracepoints.  */
15174
15175 std::vector<breakpoint *>
15176 all_tracepoints (void)
15177 {
15178   std::vector<breakpoint *> tp_vec;
15179   struct breakpoint *tp;
15180
15181   ALL_TRACEPOINTS (tp)
15182   {
15183     tp_vec.push_back (tp);
15184   }
15185
15186   return tp_vec;
15187 }
15188
15189 \f
15190 /* This help string is used to consolidate all the help string for specifying
15191    locations used by several commands.  */
15192
15193 #define LOCATION_HELP_STRING \
15194 "Linespecs are colon-separated lists of location parameters, such as\n\
15195 source filename, function name, label name, and line number.\n\
15196 Example: To specify the start of a label named \"the_top\" in the\n\
15197 function \"fact\" in the file \"factorial.c\", use\n\
15198 \"factorial.c:fact:the_top\".\n\
15199 \n\
15200 Address locations begin with \"*\" and specify an exact address in the\n\
15201 program.  Example: To specify the fourth byte past the start function\n\
15202 \"main\", use \"*main + 4\".\n\
15203 \n\
15204 Explicit locations are similar to linespecs but use an option/argument\n\
15205 syntax to specify location parameters.\n\
15206 Example: To specify the start of the label named \"the_top\" in the\n\
15207 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15208 -function fact -label the_top\".\n\
15209 \n\
15210 By default, a specified function is matched against the program's\n\
15211 functions in all scopes.  For C++, this means in all namespaces and\n\
15212 classes.  For Ada, this means in all packages.  E.g., in C++,\n\
15213 \"func()\" matches \"A::func()\", \"A::B::func()\", etc.  The\n\
15214 \"-qualified\" flag overrides this behavior, making GDB interpret the\n\
15215 specified name as a complete fully-qualified name instead.\n"
15216
15217 /* This help string is used for the break, hbreak, tbreak and thbreak
15218    commands.  It is defined as a macro to prevent duplication.
15219    COMMAND should be a string constant containing the name of the
15220    command.  */
15221
15222 #define BREAK_ARGS_HELP(command) \
15223 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15224 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15225 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15226 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15227 `-probe-dtrace' (for a DTrace probe).\n\
15228 LOCATION may be a linespec, address, or explicit location as described\n\
15229 below.\n\
15230 \n\
15231 With no LOCATION, uses current execution address of the selected\n\
15232 stack frame.  This is useful for breaking on return to a stack frame.\n\
15233 \n\
15234 THREADNUM is the number from \"info threads\".\n\
15235 CONDITION is a boolean expression.\n\
15236 \n" LOCATION_HELP_STRING "\n\
15237 Multiple breakpoints at one place are permitted, and useful if their\n\
15238 conditions are different.\n\
15239 \n\
15240 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15241
15242 /* List of subcommands for "catch".  */
15243 static struct cmd_list_element *catch_cmdlist;
15244
15245 /* List of subcommands for "tcatch".  */
15246 static struct cmd_list_element *tcatch_cmdlist;
15247
15248 void
15249 add_catch_command (const char *name, const char *docstring,
15250                    cmd_const_sfunc_ftype *sfunc,
15251                    completer_ftype *completer,
15252                    void *user_data_catch,
15253                    void *user_data_tcatch)
15254 {
15255   struct cmd_list_element *command;
15256
15257   command = add_cmd (name, class_breakpoint, docstring,
15258                      &catch_cmdlist);
15259   set_cmd_sfunc (command, sfunc);
15260   set_cmd_context (command, user_data_catch);
15261   set_cmd_completer (command, completer);
15262
15263   command = add_cmd (name, class_breakpoint, docstring,
15264                      &tcatch_cmdlist);
15265   set_cmd_sfunc (command, sfunc);
15266   set_cmd_context (command, user_data_tcatch);
15267   set_cmd_completer (command, completer);
15268 }
15269
15270 static void
15271 save_command (const char *arg, int from_tty)
15272 {
15273   printf_unfiltered (_("\"save\" must be followed by "
15274                        "the name of a save subcommand.\n"));
15275   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15276 }
15277
15278 struct breakpoint *
15279 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15280                           void *data)
15281 {
15282   struct breakpoint *b, *b_tmp;
15283
15284   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15285     {
15286       if ((*callback) (b, data))
15287         return b;
15288     }
15289
15290   return NULL;
15291 }
15292
15293 /* Zero if any of the breakpoint's locations could be a location where
15294    functions have been inlined, nonzero otherwise.  */
15295
15296 static int
15297 is_non_inline_function (struct breakpoint *b)
15298 {
15299   /* The shared library event breakpoint is set on the address of a
15300      non-inline function.  */
15301   if (b->type == bp_shlib_event)
15302     return 1;
15303
15304   return 0;
15305 }
15306
15307 /* Nonzero if the specified PC cannot be a location where functions
15308    have been inlined.  */
15309
15310 int
15311 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
15312                            const struct target_waitstatus *ws)
15313 {
15314   struct breakpoint *b;
15315   struct bp_location *bl;
15316
15317   ALL_BREAKPOINTS (b)
15318     {
15319       if (!is_non_inline_function (b))
15320         continue;
15321
15322       for (bl = b->loc; bl != NULL; bl = bl->next)
15323         {
15324           if (!bl->shlib_disabled
15325               && bpstat_check_location (bl, aspace, pc, ws))
15326             return 1;
15327         }
15328     }
15329
15330   return 0;
15331 }
15332
15333 /* Remove any references to OBJFILE which is going to be freed.  */
15334
15335 void
15336 breakpoint_free_objfile (struct objfile *objfile)
15337 {
15338   struct bp_location **locp, *loc;
15339
15340   ALL_BP_LOCATIONS (loc, locp)
15341     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15342       loc->symtab = NULL;
15343 }
15344
15345 void
15346 initialize_breakpoint_ops (void)
15347 {
15348   static int initialized = 0;
15349
15350   struct breakpoint_ops *ops;
15351
15352   if (initialized)
15353     return;
15354   initialized = 1;
15355
15356   /* The breakpoint_ops structure to be inherit by all kinds of
15357      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15358      internal and momentary breakpoints, etc.).  */
15359   ops = &bkpt_base_breakpoint_ops;
15360   *ops = base_breakpoint_ops;
15361   ops->re_set = bkpt_re_set;
15362   ops->insert_location = bkpt_insert_location;
15363   ops->remove_location = bkpt_remove_location;
15364   ops->breakpoint_hit = bkpt_breakpoint_hit;
15365   ops->create_sals_from_location = bkpt_create_sals_from_location;
15366   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15367   ops->decode_location = bkpt_decode_location;
15368
15369   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15370   ops = &bkpt_breakpoint_ops;
15371   *ops = bkpt_base_breakpoint_ops;
15372   ops->re_set = bkpt_re_set;
15373   ops->resources_needed = bkpt_resources_needed;
15374   ops->print_it = bkpt_print_it;
15375   ops->print_mention = bkpt_print_mention;
15376   ops->print_recreate = bkpt_print_recreate;
15377
15378   /* Ranged breakpoints.  */
15379   ops = &ranged_breakpoint_ops;
15380   *ops = bkpt_breakpoint_ops;
15381   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15382   ops->resources_needed = resources_needed_ranged_breakpoint;
15383   ops->print_it = print_it_ranged_breakpoint;
15384   ops->print_one = print_one_ranged_breakpoint;
15385   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15386   ops->print_mention = print_mention_ranged_breakpoint;
15387   ops->print_recreate = print_recreate_ranged_breakpoint;
15388
15389   /* Internal breakpoints.  */
15390   ops = &internal_breakpoint_ops;
15391   *ops = bkpt_base_breakpoint_ops;
15392   ops->re_set = internal_bkpt_re_set;
15393   ops->check_status = internal_bkpt_check_status;
15394   ops->print_it = internal_bkpt_print_it;
15395   ops->print_mention = internal_bkpt_print_mention;
15396
15397   /* Momentary breakpoints.  */
15398   ops = &momentary_breakpoint_ops;
15399   *ops = bkpt_base_breakpoint_ops;
15400   ops->re_set = momentary_bkpt_re_set;
15401   ops->check_status = momentary_bkpt_check_status;
15402   ops->print_it = momentary_bkpt_print_it;
15403   ops->print_mention = momentary_bkpt_print_mention;
15404
15405   /* Probe breakpoints.  */
15406   ops = &bkpt_probe_breakpoint_ops;
15407   *ops = bkpt_breakpoint_ops;
15408   ops->insert_location = bkpt_probe_insert_location;
15409   ops->remove_location = bkpt_probe_remove_location;
15410   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15411   ops->decode_location = bkpt_probe_decode_location;
15412
15413   /* Watchpoints.  */
15414   ops = &watchpoint_breakpoint_ops;
15415   *ops = base_breakpoint_ops;
15416   ops->re_set = re_set_watchpoint;
15417   ops->insert_location = insert_watchpoint;
15418   ops->remove_location = remove_watchpoint;
15419   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15420   ops->check_status = check_status_watchpoint;
15421   ops->resources_needed = resources_needed_watchpoint;
15422   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15423   ops->print_it = print_it_watchpoint;
15424   ops->print_mention = print_mention_watchpoint;
15425   ops->print_recreate = print_recreate_watchpoint;
15426   ops->explains_signal = explains_signal_watchpoint;
15427
15428   /* Masked watchpoints.  */
15429   ops = &masked_watchpoint_breakpoint_ops;
15430   *ops = watchpoint_breakpoint_ops;
15431   ops->insert_location = insert_masked_watchpoint;
15432   ops->remove_location = remove_masked_watchpoint;
15433   ops->resources_needed = resources_needed_masked_watchpoint;
15434   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15435   ops->print_it = print_it_masked_watchpoint;
15436   ops->print_one_detail = print_one_detail_masked_watchpoint;
15437   ops->print_mention = print_mention_masked_watchpoint;
15438   ops->print_recreate = print_recreate_masked_watchpoint;
15439
15440   /* Tracepoints.  */
15441   ops = &tracepoint_breakpoint_ops;
15442   *ops = base_breakpoint_ops;
15443   ops->re_set = tracepoint_re_set;
15444   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15445   ops->print_one_detail = tracepoint_print_one_detail;
15446   ops->print_mention = tracepoint_print_mention;
15447   ops->print_recreate = tracepoint_print_recreate;
15448   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15449   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15450   ops->decode_location = tracepoint_decode_location;
15451
15452   /* Probe tracepoints.  */
15453   ops = &tracepoint_probe_breakpoint_ops;
15454   *ops = tracepoint_breakpoint_ops;
15455   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15456   ops->decode_location = tracepoint_probe_decode_location;
15457
15458   /* Static tracepoints with marker (`-m').  */
15459   ops = &strace_marker_breakpoint_ops;
15460   *ops = tracepoint_breakpoint_ops;
15461   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15462   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15463   ops->decode_location = strace_marker_decode_location;
15464
15465   /* Fork catchpoints.  */
15466   ops = &catch_fork_breakpoint_ops;
15467   *ops = base_breakpoint_ops;
15468   ops->insert_location = insert_catch_fork;
15469   ops->remove_location = remove_catch_fork;
15470   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15471   ops->print_it = print_it_catch_fork;
15472   ops->print_one = print_one_catch_fork;
15473   ops->print_mention = print_mention_catch_fork;
15474   ops->print_recreate = print_recreate_catch_fork;
15475
15476   /* Vfork catchpoints.  */
15477   ops = &catch_vfork_breakpoint_ops;
15478   *ops = base_breakpoint_ops;
15479   ops->insert_location = insert_catch_vfork;
15480   ops->remove_location = remove_catch_vfork;
15481   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15482   ops->print_it = print_it_catch_vfork;
15483   ops->print_one = print_one_catch_vfork;
15484   ops->print_mention = print_mention_catch_vfork;
15485   ops->print_recreate = print_recreate_catch_vfork;
15486
15487   /* Exec catchpoints.  */
15488   ops = &catch_exec_breakpoint_ops;
15489   *ops = base_breakpoint_ops;
15490   ops->insert_location = insert_catch_exec;
15491   ops->remove_location = remove_catch_exec;
15492   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15493   ops->print_it = print_it_catch_exec;
15494   ops->print_one = print_one_catch_exec;
15495   ops->print_mention = print_mention_catch_exec;
15496   ops->print_recreate = print_recreate_catch_exec;
15497
15498   /* Solib-related catchpoints.  */
15499   ops = &catch_solib_breakpoint_ops;
15500   *ops = base_breakpoint_ops;
15501   ops->insert_location = insert_catch_solib;
15502   ops->remove_location = remove_catch_solib;
15503   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15504   ops->check_status = check_status_catch_solib;
15505   ops->print_it = print_it_catch_solib;
15506   ops->print_one = print_one_catch_solib;
15507   ops->print_mention = print_mention_catch_solib;
15508   ops->print_recreate = print_recreate_catch_solib;
15509
15510   ops = &dprintf_breakpoint_ops;
15511   *ops = bkpt_base_breakpoint_ops;
15512   ops->re_set = dprintf_re_set;
15513   ops->resources_needed = bkpt_resources_needed;
15514   ops->print_it = bkpt_print_it;
15515   ops->print_mention = bkpt_print_mention;
15516   ops->print_recreate = dprintf_print_recreate;
15517   ops->after_condition_true = dprintf_after_condition_true;
15518   ops->breakpoint_hit = dprintf_breakpoint_hit;
15519 }
15520
15521 /* Chain containing all defined "enable breakpoint" subcommands.  */
15522
15523 static struct cmd_list_element *enablebreaklist = NULL;
15524
15525 void
15526 _initialize_breakpoint (void)
15527 {
15528   struct cmd_list_element *c;
15529
15530   initialize_breakpoint_ops ();
15531
15532   gdb::observers::solib_unloaded.attach (disable_breakpoints_in_unloaded_shlib);
15533   gdb::observers::free_objfile.attach (disable_breakpoints_in_freed_objfile);
15534   gdb::observers::memory_changed.attach (invalidate_bp_value_on_memory_change);
15535
15536   breakpoint_objfile_key
15537     = register_objfile_data_with_cleanup (NULL, free_breakpoint_objfile_data);
15538
15539   breakpoint_chain = 0;
15540   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15541      before a breakpoint is set.  */
15542   breakpoint_count = 0;
15543
15544   tracepoint_count = 0;
15545
15546   add_com ("ignore", class_breakpoint, ignore_command, _("\
15547 Set ignore-count of breakpoint number N to COUNT.\n\
15548 Usage is `ignore N COUNT'."));
15549
15550   add_com ("commands", class_breakpoint, commands_command, _("\
15551 Set commands to be executed when the given breakpoints are hit.\n\
15552 Give a space-separated breakpoint list as argument after \"commands\".\n\
15553 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
15554 (e.g. `5-7').\n\
15555 With no argument, the targeted breakpoint is the last one set.\n\
15556 The commands themselves follow starting on the next line.\n\
15557 Type a line containing \"end\" to indicate the end of them.\n\
15558 Give \"silent\" as the first line to make the breakpoint silent;\n\
15559 then no output is printed when it is hit, except what the commands print."));
15560
15561   c = add_com ("condition", class_breakpoint, condition_command, _("\
15562 Specify breakpoint number N to break only if COND is true.\n\
15563 Usage is `condition N COND', where N is an integer and COND is an\n\
15564 expression to be evaluated whenever breakpoint N is reached."));
15565   set_cmd_completer (c, condition_completer);
15566
15567   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15568 Set a temporary breakpoint.\n\
15569 Like \"break\" except the breakpoint is only temporary,\n\
15570 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15571 by using \"enable delete\" on the breakpoint number.\n\
15572 \n"
15573 BREAK_ARGS_HELP ("tbreak")));
15574   set_cmd_completer (c, location_completer);
15575
15576   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15577 Set a hardware assisted breakpoint.\n\
15578 Like \"break\" except the breakpoint requires hardware support,\n\
15579 some target hardware may not have this support.\n\
15580 \n"
15581 BREAK_ARGS_HELP ("hbreak")));
15582   set_cmd_completer (c, location_completer);
15583
15584   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15585 Set a temporary hardware assisted breakpoint.\n\
15586 Like \"hbreak\" except the breakpoint is only temporary,\n\
15587 so it will be deleted when hit.\n\
15588 \n"
15589 BREAK_ARGS_HELP ("thbreak")));
15590   set_cmd_completer (c, location_completer);
15591
15592   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15593 Enable some breakpoints.\n\
15594 Give breakpoint numbers (separated by spaces) as arguments.\n\
15595 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15596 This is used to cancel the effect of the \"disable\" command.\n\
15597 With a subcommand you can enable temporarily."),
15598                   &enablelist, "enable ", 1, &cmdlist);
15599
15600   add_com_alias ("en", "enable", class_breakpoint, 1);
15601
15602   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15603 Enable some breakpoints.\n\
15604 Give breakpoint numbers (separated by spaces) as arguments.\n\
15605 This is used to cancel the effect of the \"disable\" command.\n\
15606 May be abbreviated to simply \"enable\".\n"),
15607                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15608
15609   add_cmd ("once", no_class, enable_once_command, _("\
15610 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15611 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15612            &enablebreaklist);
15613
15614   add_cmd ("delete", no_class, enable_delete_command, _("\
15615 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15616 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15617            &enablebreaklist);
15618
15619   add_cmd ("count", no_class, enable_count_command, _("\
15620 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15621 If a breakpoint is hit while enabled in this fashion,\n\
15622 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15623            &enablebreaklist);
15624
15625   add_cmd ("delete", no_class, enable_delete_command, _("\
15626 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15627 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15628            &enablelist);
15629
15630   add_cmd ("once", no_class, enable_once_command, _("\
15631 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15632 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15633            &enablelist);
15634
15635   add_cmd ("count", no_class, enable_count_command, _("\
15636 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15637 If a breakpoint is hit while enabled in this fashion,\n\
15638 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15639            &enablelist);
15640
15641   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15642 Disable some breakpoints.\n\
15643 Arguments are breakpoint numbers with spaces in between.\n\
15644 To disable all breakpoints, give no argument.\n\
15645 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15646                   &disablelist, "disable ", 1, &cmdlist);
15647   add_com_alias ("dis", "disable", class_breakpoint, 1);
15648   add_com_alias ("disa", "disable", class_breakpoint, 1);
15649
15650   add_cmd ("breakpoints", class_alias, disable_command, _("\
15651 Disable some breakpoints.\n\
15652 Arguments are breakpoint numbers with spaces in between.\n\
15653 To disable all breakpoints, give no argument.\n\
15654 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15655 This command may be abbreviated \"disable\"."),
15656            &disablelist);
15657
15658   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15659 Delete some breakpoints or auto-display expressions.\n\
15660 Arguments are breakpoint numbers with spaces in between.\n\
15661 To delete all breakpoints, give no argument.\n\
15662 \n\
15663 Also a prefix command for deletion of other GDB objects.\n\
15664 The \"unset\" command is also an alias for \"delete\"."),
15665                   &deletelist, "delete ", 1, &cmdlist);
15666   add_com_alias ("d", "delete", class_breakpoint, 1);
15667   add_com_alias ("del", "delete", class_breakpoint, 1);
15668
15669   add_cmd ("breakpoints", class_alias, delete_command, _("\
15670 Delete some breakpoints or auto-display expressions.\n\
15671 Arguments are breakpoint numbers with spaces in between.\n\
15672 To delete all breakpoints, give no argument.\n\
15673 This command may be abbreviated \"delete\"."),
15674            &deletelist);
15675
15676   add_com ("clear", class_breakpoint, clear_command, _("\
15677 Clear breakpoint at specified location.\n\
15678 Argument may be a linespec, explicit, or address location as described below.\n\
15679 \n\
15680 With no argument, clears all breakpoints in the line that the selected frame\n\
15681 is executing in.\n"
15682 "\n" LOCATION_HELP_STRING "\n\
15683 See also the \"delete\" command which clears breakpoints by number."));
15684   add_com_alias ("cl", "clear", class_breakpoint, 1);
15685
15686   c = add_com ("break", class_breakpoint, break_command, _("\
15687 Set breakpoint at specified location.\n"
15688 BREAK_ARGS_HELP ("break")));
15689   set_cmd_completer (c, location_completer);
15690
15691   add_com_alias ("b", "break", class_run, 1);
15692   add_com_alias ("br", "break", class_run, 1);
15693   add_com_alias ("bre", "break", class_run, 1);
15694   add_com_alias ("brea", "break", class_run, 1);
15695
15696   if (dbx_commands)
15697     {
15698       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15699 Break in function/address or break at a line in the current file."),
15700                              &stoplist, "stop ", 1, &cmdlist);
15701       add_cmd ("in", class_breakpoint, stopin_command,
15702                _("Break in function or address."), &stoplist);
15703       add_cmd ("at", class_breakpoint, stopat_command,
15704                _("Break at a line in the current file."), &stoplist);
15705       add_com ("status", class_info, info_breakpoints_command, _("\
15706 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15707 The \"Type\" column indicates one of:\n\
15708 \tbreakpoint     - normal breakpoint\n\
15709 \twatchpoint     - watchpoint\n\
15710 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15711 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15712 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15713 address and file/line number respectively.\n\
15714 \n\
15715 Convenience variable \"$_\" and default examine address for \"x\"\n\
15716 are set to the address of the last breakpoint listed unless the command\n\
15717 is prefixed with \"server \".\n\n\
15718 Convenience variable \"$bpnum\" contains the number of the last\n\
15719 breakpoint set."));
15720     }
15721
15722   add_info ("breakpoints", info_breakpoints_command, _("\
15723 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15724 The \"Type\" column indicates one of:\n\
15725 \tbreakpoint     - normal breakpoint\n\
15726 \twatchpoint     - watchpoint\n\
15727 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15728 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15729 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15730 address and file/line number respectively.\n\
15731 \n\
15732 Convenience variable \"$_\" and default examine address for \"x\"\n\
15733 are set to the address of the last breakpoint listed unless the command\n\
15734 is prefixed with \"server \".\n\n\
15735 Convenience variable \"$bpnum\" contains the number of the last\n\
15736 breakpoint set."));
15737
15738   add_info_alias ("b", "breakpoints", 1);
15739
15740   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15741 Status of all breakpoints, or breakpoint number NUMBER.\n\
15742 The \"Type\" column indicates one of:\n\
15743 \tbreakpoint     - normal breakpoint\n\
15744 \twatchpoint     - watchpoint\n\
15745 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15746 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15747 \tuntil          - internal breakpoint used by the \"until\" command\n\
15748 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15749 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15750 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15751 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15752 address and file/line number respectively.\n\
15753 \n\
15754 Convenience variable \"$_\" and default examine address for \"x\"\n\
15755 are set to the address of the last breakpoint listed unless the command\n\
15756 is prefixed with \"server \".\n\n\
15757 Convenience variable \"$bpnum\" contains the number of the last\n\
15758 breakpoint set."),
15759            &maintenanceinfolist);
15760
15761   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15762 Set catchpoints to catch events."),
15763                   &catch_cmdlist, "catch ",
15764                   0/*allow-unknown*/, &cmdlist);
15765
15766   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15767 Set temporary catchpoints to catch events."),
15768                   &tcatch_cmdlist, "tcatch ",
15769                   0/*allow-unknown*/, &cmdlist);
15770
15771   add_catch_command ("fork", _("Catch calls to fork."),
15772                      catch_fork_command_1,
15773                      NULL,
15774                      (void *) (uintptr_t) catch_fork_permanent,
15775                      (void *) (uintptr_t) catch_fork_temporary);
15776   add_catch_command ("vfork", _("Catch calls to vfork."),
15777                      catch_fork_command_1,
15778                      NULL,
15779                      (void *) (uintptr_t) catch_vfork_permanent,
15780                      (void *) (uintptr_t) catch_vfork_temporary);
15781   add_catch_command ("exec", _("Catch calls to exec."),
15782                      catch_exec_command_1,
15783                      NULL,
15784                      CATCH_PERMANENT,
15785                      CATCH_TEMPORARY);
15786   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15787 Usage: catch load [REGEX]\n\
15788 If REGEX is given, only stop for libraries matching the regular expression."),
15789                      catch_load_command_1,
15790                      NULL,
15791                      CATCH_PERMANENT,
15792                      CATCH_TEMPORARY);
15793   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15794 Usage: catch unload [REGEX]\n\
15795 If REGEX is given, only stop for libraries matching the regular expression."),
15796                      catch_unload_command_1,
15797                      NULL,
15798                      CATCH_PERMANENT,
15799                      CATCH_TEMPORARY);
15800
15801   c = add_com ("watch", class_breakpoint, watch_command, _("\
15802 Set a watchpoint for an expression.\n\
15803 Usage: watch [-l|-location] EXPRESSION\n\
15804 A watchpoint stops execution of your program whenever the value of\n\
15805 an expression changes.\n\
15806 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15807 the memory to which it refers."));
15808   set_cmd_completer (c, expression_completer);
15809
15810   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15811 Set a read watchpoint for an expression.\n\
15812 Usage: rwatch [-l|-location] EXPRESSION\n\
15813 A watchpoint stops execution of your program whenever the value of\n\
15814 an expression is read.\n\
15815 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15816 the memory to which it refers."));
15817   set_cmd_completer (c, expression_completer);
15818
15819   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15820 Set a watchpoint for an expression.\n\
15821 Usage: awatch [-l|-location] EXPRESSION\n\
15822 A watchpoint stops execution of your program whenever the value of\n\
15823 an expression is either read or written.\n\
15824 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15825 the memory to which it refers."));
15826   set_cmd_completer (c, expression_completer);
15827
15828   add_info ("watchpoints", info_watchpoints_command, _("\
15829 Status of specified watchpoints (all watchpoints if no argument)."));
15830
15831   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15832      respond to changes - contrary to the description.  */
15833   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15834                             &can_use_hw_watchpoints, _("\
15835 Set debugger's willingness to use watchpoint hardware."), _("\
15836 Show debugger's willingness to use watchpoint hardware."), _("\
15837 If zero, gdb will not use hardware for new watchpoints, even if\n\
15838 such is available.  (However, any hardware watchpoints that were\n\
15839 created before setting this to nonzero, will continue to use watchpoint\n\
15840 hardware.)"),
15841                             NULL,
15842                             show_can_use_hw_watchpoints,
15843                             &setlist, &showlist);
15844
15845   can_use_hw_watchpoints = 1;
15846
15847   /* Tracepoint manipulation commands.  */
15848
15849   c = add_com ("trace", class_breakpoint, trace_command, _("\
15850 Set a tracepoint at specified location.\n\
15851 \n"
15852 BREAK_ARGS_HELP ("trace") "\n\
15853 Do \"help tracepoints\" for info on other tracepoint commands."));
15854   set_cmd_completer (c, location_completer);
15855
15856   add_com_alias ("tp", "trace", class_alias, 0);
15857   add_com_alias ("tr", "trace", class_alias, 1);
15858   add_com_alias ("tra", "trace", class_alias, 1);
15859   add_com_alias ("trac", "trace", class_alias, 1);
15860
15861   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15862 Set a fast tracepoint at specified location.\n\
15863 \n"
15864 BREAK_ARGS_HELP ("ftrace") "\n\
15865 Do \"help tracepoints\" for info on other tracepoint commands."));
15866   set_cmd_completer (c, location_completer);
15867
15868   c = add_com ("strace", class_breakpoint, strace_command, _("\
15869 Set a static tracepoint at location or marker.\n\
15870 \n\
15871 strace [LOCATION] [if CONDITION]\n\
15872 LOCATION may be a linespec, explicit, or address location (described below) \n\
15873 or -m MARKER_ID.\n\n\
15874 If a marker id is specified, probe the marker with that name.  With\n\
15875 no LOCATION, uses current execution address of the selected stack frame.\n\
15876 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15877 This collects arbitrary user data passed in the probe point call to the\n\
15878 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15879 by printing the $_sdata variable like any other convenience variable.\n\
15880 \n\
15881 CONDITION is a boolean expression.\n\
15882 \n" LOCATION_HELP_STRING "\n\
15883 Multiple tracepoints at one place are permitted, and useful if their\n\
15884 conditions are different.\n\
15885 \n\
15886 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15887 Do \"help tracepoints\" for info on other tracepoint commands."));
15888   set_cmd_completer (c, location_completer);
15889
15890   add_info ("tracepoints", info_tracepoints_command, _("\
15891 Status of specified tracepoints (all tracepoints if no argument).\n\
15892 Convenience variable \"$tpnum\" contains the number of the\n\
15893 last tracepoint set."));
15894
15895   add_info_alias ("tp", "tracepoints", 1);
15896
15897   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15898 Delete specified tracepoints.\n\
15899 Arguments are tracepoint numbers, separated by spaces.\n\
15900 No argument means delete all tracepoints."),
15901            &deletelist);
15902   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
15903
15904   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15905 Disable specified tracepoints.\n\
15906 Arguments are tracepoint numbers, separated by spaces.\n\
15907 No argument means disable all tracepoints."),
15908            &disablelist);
15909   deprecate_cmd (c, "disable");
15910
15911   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15912 Enable specified tracepoints.\n\
15913 Arguments are tracepoint numbers, separated by spaces.\n\
15914 No argument means enable all tracepoints."),
15915            &enablelist);
15916   deprecate_cmd (c, "enable");
15917
15918   add_com ("passcount", class_trace, trace_pass_command, _("\
15919 Set the passcount for a tracepoint.\n\
15920 The trace will end when the tracepoint has been passed 'count' times.\n\
15921 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15922 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
15923
15924   add_prefix_cmd ("save", class_breakpoint, save_command,
15925                   _("Save breakpoint definitions as a script."),
15926                   &save_cmdlist, "save ",
15927                   0/*allow-unknown*/, &cmdlist);
15928
15929   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
15930 Save current breakpoint definitions as a script.\n\
15931 This includes all types of breakpoints (breakpoints, watchpoints,\n\
15932 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
15933 session to restore them."),
15934                &save_cmdlist);
15935   set_cmd_completer (c, filename_completer);
15936
15937   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
15938 Save current tracepoint definitions as a script.\n\
15939 Use the 'source' command in another debug session to restore them."),
15940                &save_cmdlist);
15941   set_cmd_completer (c, filename_completer);
15942
15943   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
15944   deprecate_cmd (c, "save tracepoints");
15945
15946   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
15947 Breakpoint specific settings\n\
15948 Configure various breakpoint-specific variables such as\n\
15949 pending breakpoint behavior"),
15950                   &breakpoint_set_cmdlist, "set breakpoint ",
15951                   0/*allow-unknown*/, &setlist);
15952   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
15953 Breakpoint specific settings\n\
15954 Configure various breakpoint-specific variables such as\n\
15955 pending breakpoint behavior"),
15956                   &breakpoint_show_cmdlist, "show breakpoint ",
15957                   0/*allow-unknown*/, &showlist);
15958
15959   add_setshow_auto_boolean_cmd ("pending", no_class,
15960                                 &pending_break_support, _("\
15961 Set debugger's behavior regarding pending breakpoints."), _("\
15962 Show debugger's behavior regarding pending breakpoints."), _("\
15963 If on, an unrecognized breakpoint location will cause gdb to create a\n\
15964 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
15965 an error.  If auto, an unrecognized breakpoint location results in a\n\
15966 user-query to see if a pending breakpoint should be created."),
15967                                 NULL,
15968                                 show_pending_break_support,
15969                                 &breakpoint_set_cmdlist,
15970                                 &breakpoint_show_cmdlist);
15971
15972   pending_break_support = AUTO_BOOLEAN_AUTO;
15973
15974   add_setshow_boolean_cmd ("auto-hw", no_class,
15975                            &automatic_hardware_breakpoints, _("\
15976 Set automatic usage of hardware breakpoints."), _("\
15977 Show automatic usage of hardware breakpoints."), _("\
15978 If set, the debugger will automatically use hardware breakpoints for\n\
15979 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
15980 a warning will be emitted for such breakpoints."),
15981                            NULL,
15982                            show_automatic_hardware_breakpoints,
15983                            &breakpoint_set_cmdlist,
15984                            &breakpoint_show_cmdlist);
15985
15986   add_setshow_boolean_cmd ("always-inserted", class_support,
15987                            &always_inserted_mode, _("\
15988 Set mode for inserting breakpoints."), _("\
15989 Show mode for inserting breakpoints."), _("\
15990 When this mode is on, breakpoints are inserted immediately as soon as\n\
15991 they're created, kept inserted even when execution stops, and removed\n\
15992 only when the user deletes them.  When this mode is off (the default),\n\
15993 breakpoints are inserted only when execution continues, and removed\n\
15994 when execution stops."),
15995                                 NULL,
15996                                 &show_always_inserted_mode,
15997                                 &breakpoint_set_cmdlist,
15998                                 &breakpoint_show_cmdlist);
15999
16000   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16001                         condition_evaluation_enums,
16002                         &condition_evaluation_mode_1, _("\
16003 Set mode of breakpoint condition evaluation."), _("\
16004 Show mode of breakpoint condition evaluation."), _("\
16005 When this is set to \"host\", breakpoint conditions will be\n\
16006 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16007 breakpoint conditions will be downloaded to the target (if the target\n\
16008 supports such feature) and conditions will be evaluated on the target's side.\n\
16009 If this is set to \"auto\" (default), this will be automatically set to\n\
16010 \"target\" if it supports condition evaluation, otherwise it will\n\
16011 be set to \"gdb\""),
16012                            &set_condition_evaluation_mode,
16013                            &show_condition_evaluation_mode,
16014                            &breakpoint_set_cmdlist,
16015                            &breakpoint_show_cmdlist);
16016
16017   add_com ("break-range", class_breakpoint, break_range_command, _("\
16018 Set a breakpoint for an address range.\n\
16019 break-range START-LOCATION, END-LOCATION\n\
16020 where START-LOCATION and END-LOCATION can be one of the following:\n\
16021   LINENUM, for that line in the current file,\n\
16022   FILE:LINENUM, for that line in that file,\n\
16023   +OFFSET, for that number of lines after the current line\n\
16024            or the start of the range\n\
16025   FUNCTION, for the first line in that function,\n\
16026   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16027   *ADDRESS, for the instruction at that address.\n\
16028 \n\
16029 The breakpoint will stop execution of the inferior whenever it executes\n\
16030 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16031 range (including START-LOCATION and END-LOCATION)."));
16032
16033   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16034 Set a dynamic printf at specified location.\n\
16035 dprintf location,format string,arg1,arg2,...\n\
16036 location may be a linespec, explicit, or address location.\n"
16037 "\n" LOCATION_HELP_STRING));
16038   set_cmd_completer (c, location_completer);
16039
16040   add_setshow_enum_cmd ("dprintf-style", class_support,
16041                         dprintf_style_enums, &dprintf_style, _("\
16042 Set the style of usage for dynamic printf."), _("\
16043 Show the style of usage for dynamic printf."), _("\
16044 This setting chooses how GDB will do a dynamic printf.\n\
16045 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16046 console, as with the \"printf\" command.\n\
16047 If the value is \"call\", the print is done by calling a function in your\n\
16048 program; by default printf(), but you can choose a different function or\n\
16049 output stream by setting dprintf-function and dprintf-channel."),
16050                         update_dprintf_commands, NULL,
16051                         &setlist, &showlist);
16052
16053   dprintf_function = xstrdup ("printf");
16054   add_setshow_string_cmd ("dprintf-function", class_support,
16055                           &dprintf_function, _("\
16056 Set the function to use for dynamic printf"), _("\
16057 Show the function to use for dynamic printf"), NULL,
16058                           update_dprintf_commands, NULL,
16059                           &setlist, &showlist);
16060
16061   dprintf_channel = xstrdup ("");
16062   add_setshow_string_cmd ("dprintf-channel", class_support,
16063                           &dprintf_channel, _("\
16064 Set the channel to use for dynamic printf"), _("\
16065 Show the channel to use for dynamic printf"), NULL,
16066                           update_dprintf_commands, NULL,
16067                           &setlist, &showlist);
16068
16069   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16070                            &disconnected_dprintf, _("\
16071 Set whether dprintf continues after GDB disconnects."), _("\
16072 Show whether dprintf continues after GDB disconnects."), _("\
16073 Use this to let dprintf commands continue to hit and produce output\n\
16074 even if GDB disconnects or detaches from the target."),
16075                            NULL,
16076                            NULL,
16077                            &setlist, &showlist);
16078
16079   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16080 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16081 (target agent only) This is useful for formatted output in user-defined commands."));
16082
16083   automatic_hardware_breakpoints = 1;
16084
16085   gdb::observers::about_to_proceed.attach (breakpoint_about_to_proceed);
16086   gdb::observers::thread_exit.attach (remove_threaded_breakpoints);
16087 }