Per-inferior thread list, thread ranges/iterators, down with ALL_THREADS, etc.
[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       if (always_inserted_mode)
404         {
405           /* The user wants breakpoints inserted even if all threads
406              are stopped.  */
407           return 1;
408         }
409
410       if (threads_are_executing ())
411         return 1;
412
413       /* Don't remove breakpoints yet if, even though all threads are
414          stopped, we still have events to process.  */
415       for (thread_info *tp : all_non_exited_threads ())
416         if (tp->resumed
417             && tp->suspend.waitstatus_pending_p)
418           return 1;
419     }
420   return 0;
421 }
422
423 static const char condition_evaluation_both[] = "host or target";
424
425 /* Modes for breakpoint condition evaluation.  */
426 static const char condition_evaluation_auto[] = "auto";
427 static const char condition_evaluation_host[] = "host";
428 static const char condition_evaluation_target[] = "target";
429 static const char *const condition_evaluation_enums[] = {
430   condition_evaluation_auto,
431   condition_evaluation_host,
432   condition_evaluation_target,
433   NULL
434 };
435
436 /* Global that holds the current mode for breakpoint condition evaluation.  */
437 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
438
439 /* Global that we use to display information to the user (gets its value from
440    condition_evaluation_mode_1.  */
441 static const char *condition_evaluation_mode = condition_evaluation_auto;
442
443 /* Translate a condition evaluation mode MODE into either "host"
444    or "target".  This is used mostly to translate from "auto" to the
445    real setting that is being used.  It returns the translated
446    evaluation mode.  */
447
448 static const char *
449 translate_condition_evaluation_mode (const char *mode)
450 {
451   if (mode == condition_evaluation_auto)
452     {
453       if (target_supports_evaluation_of_breakpoint_conditions ())
454         return condition_evaluation_target;
455       else
456         return condition_evaluation_host;
457     }
458   else
459     return mode;
460 }
461
462 /* Discovers what condition_evaluation_auto translates to.  */
463
464 static const char *
465 breakpoint_condition_evaluation_mode (void)
466 {
467   return translate_condition_evaluation_mode (condition_evaluation_mode);
468 }
469
470 /* Return true if GDB should evaluate breakpoint conditions or false
471    otherwise.  */
472
473 static int
474 gdb_evaluates_breakpoint_condition_p (void)
475 {
476   const char *mode = breakpoint_condition_evaluation_mode ();
477
478   return (mode == condition_evaluation_host);
479 }
480
481 /* Are we executing breakpoint commands?  */
482 static int executing_breakpoint_commands;
483
484 /* Are overlay event breakpoints enabled? */
485 static int overlay_events_enabled;
486
487 /* See description in breakpoint.h. */
488 int target_exact_watchpoints = 0;
489
490 /* Walk the following statement or block through all breakpoints.
491    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
492    current breakpoint.  */
493
494 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
495
496 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
497         for (B = breakpoint_chain;      \
498              B ? (TMP=B->next, 1): 0;   \
499              B = TMP)
500
501 /* Similar iterator for the low-level breakpoints.  SAFE variant is
502    not provided so update_global_location_list must not be called
503    while executing the block of ALL_BP_LOCATIONS.  */
504
505 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
506         for (BP_TMP = bp_locations;                                     \
507              BP_TMP < bp_locations + bp_locations_count && (B = *BP_TMP);\
508              BP_TMP++)
509
510 /* Iterates through locations with address ADDRESS for the currently selected
511    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
512    to where the loop should start from.
513    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
514    appropriate location to start with.  */
515
516 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
517         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
518              BP_LOCP_TMP = BP_LOCP_START;                               \
519              BP_LOCP_START                                              \
520              && (BP_LOCP_TMP < bp_locations + bp_locations_count        \
521              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
522              BP_LOCP_TMP++)
523
524 /* Iterator for tracepoints only.  */
525
526 #define ALL_TRACEPOINTS(B)  \
527   for (B = breakpoint_chain; B; B = B->next)  \
528     if (is_tracepoint (B))
529
530 /* Chains of all breakpoints defined.  */
531
532 struct breakpoint *breakpoint_chain;
533
534 /* Array is sorted by bp_locations_compare - primarily by the ADDRESS.  */
535
536 static struct bp_location **bp_locations;
537
538 /* Number of elements of BP_LOCATIONS.  */
539
540 static unsigned bp_locations_count;
541
542 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
543    ADDRESS for the current elements of BP_LOCATIONS which get a valid
544    result from bp_location_has_shadow.  You can use it for roughly
545    limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
546    an address you need to read.  */
547
548 static CORE_ADDR bp_locations_placed_address_before_address_max;
549
550 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
551    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
552    BP_LOCATIONS which get a valid result from bp_location_has_shadow.
553    You can use it for roughly limiting the subrange of BP_LOCATIONS to
554    scan for shadow bytes for an address you need to read.  */
555
556 static CORE_ADDR bp_locations_shadow_len_after_address_max;
557
558 /* The locations that no longer correspond to any breakpoint, unlinked
559    from the bp_locations array, but for which a hit may still be
560    reported by a target.  */
561 static std::vector<bp_location *> moribund_locations;
562
563 /* Number of last breakpoint made.  */
564
565 static int breakpoint_count;
566
567 /* The value of `breakpoint_count' before the last command that
568    created breakpoints.  If the last (break-like) command created more
569    than one breakpoint, then the difference between BREAKPOINT_COUNT
570    and PREV_BREAKPOINT_COUNT is more than one.  */
571 static int prev_breakpoint_count;
572
573 /* Number of last tracepoint made.  */
574
575 static int tracepoint_count;
576
577 static struct cmd_list_element *breakpoint_set_cmdlist;
578 static struct cmd_list_element *breakpoint_show_cmdlist;
579 struct cmd_list_element *save_cmdlist;
580
581 /* See declaration at breakpoint.h.  */
582
583 struct breakpoint *
584 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
585                     void *user_data)
586 {
587   struct breakpoint *b = NULL;
588
589   ALL_BREAKPOINTS (b)
590     {
591       if (func (b, user_data) != 0)
592         break;
593     }
594
595   return b;
596 }
597
598 /* Return whether a breakpoint is an active enabled breakpoint.  */
599 static int
600 breakpoint_enabled (struct breakpoint *b)
601 {
602   return (b->enable_state == bp_enabled);
603 }
604
605 /* Set breakpoint count to NUM.  */
606
607 static void
608 set_breakpoint_count (int num)
609 {
610   prev_breakpoint_count = breakpoint_count;
611   breakpoint_count = num;
612   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
613 }
614
615 /* Used by `start_rbreak_breakpoints' below, to record the current
616    breakpoint count before "rbreak" creates any breakpoint.  */
617 static int rbreak_start_breakpoint_count;
618
619 /* Called at the start an "rbreak" command to record the first
620    breakpoint made.  */
621
622 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
623 {
624   rbreak_start_breakpoint_count = breakpoint_count;
625 }
626
627 /* Called at the end of an "rbreak" command to record the last
628    breakpoint made.  */
629
630 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
631 {
632   prev_breakpoint_count = rbreak_start_breakpoint_count;
633 }
634
635 /* Used in run_command to zero the hit count when a new run starts.  */
636
637 void
638 clear_breakpoint_hit_counts (void)
639 {
640   struct breakpoint *b;
641
642   ALL_BREAKPOINTS (b)
643     b->hit_count = 0;
644 }
645
646 \f
647 /* Return the breakpoint with the specified number, or NULL
648    if the number does not refer to an existing breakpoint.  */
649
650 struct breakpoint *
651 get_breakpoint (int num)
652 {
653   struct breakpoint *b;
654
655   ALL_BREAKPOINTS (b)
656     if (b->number == num)
657       return b;
658   
659   return NULL;
660 }
661
662 \f
663
664 /* Mark locations as "conditions have changed" in case the target supports
665    evaluating conditions on its side.  */
666
667 static void
668 mark_breakpoint_modified (struct breakpoint *b)
669 {
670   struct bp_location *loc;
671
672   /* This is only meaningful if the target is
673      evaluating conditions and if the user has
674      opted for condition evaluation on the target's
675      side.  */
676   if (gdb_evaluates_breakpoint_condition_p ()
677       || !target_supports_evaluation_of_breakpoint_conditions ())
678     return;
679
680   if (!is_breakpoint (b))
681     return;
682
683   for (loc = b->loc; loc; loc = loc->next)
684     loc->condition_changed = condition_modified;
685 }
686
687 /* Mark location as "conditions have changed" in case the target supports
688    evaluating conditions on its side.  */
689
690 static void
691 mark_breakpoint_location_modified (struct bp_location *loc)
692 {
693   /* This is only meaningful if the target is
694      evaluating conditions and if the user has
695      opted for condition evaluation on the target's
696      side.  */
697   if (gdb_evaluates_breakpoint_condition_p ()
698       || !target_supports_evaluation_of_breakpoint_conditions ())
699
700     return;
701
702   if (!is_breakpoint (loc->owner))
703     return;
704
705   loc->condition_changed = condition_modified;
706 }
707
708 /* Sets the condition-evaluation mode using the static global
709    condition_evaluation_mode.  */
710
711 static void
712 set_condition_evaluation_mode (const char *args, int from_tty,
713                                struct cmd_list_element *c)
714 {
715   const char *old_mode, *new_mode;
716
717   if ((condition_evaluation_mode_1 == condition_evaluation_target)
718       && !target_supports_evaluation_of_breakpoint_conditions ())
719     {
720       condition_evaluation_mode_1 = condition_evaluation_mode;
721       warning (_("Target does not support breakpoint condition evaluation.\n"
722                  "Using host evaluation mode instead."));
723       return;
724     }
725
726   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
727   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
728
729   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
730      settings was "auto".  */
731   condition_evaluation_mode = condition_evaluation_mode_1;
732
733   /* Only update the mode if the user picked a different one.  */
734   if (new_mode != old_mode)
735     {
736       struct bp_location *loc, **loc_tmp;
737       /* If the user switched to a different evaluation mode, we
738          need to synch the changes with the target as follows:
739
740          "host" -> "target": Send all (valid) conditions to the target.
741          "target" -> "host": Remove all the conditions from the target.
742       */
743
744       if (new_mode == condition_evaluation_target)
745         {
746           /* Mark everything modified and synch conditions with the
747              target.  */
748           ALL_BP_LOCATIONS (loc, loc_tmp)
749             mark_breakpoint_location_modified (loc);
750         }
751       else
752         {
753           /* Manually mark non-duplicate locations to synch conditions
754              with the target.  We do this to remove all the conditions the
755              target knows about.  */
756           ALL_BP_LOCATIONS (loc, loc_tmp)
757             if (is_breakpoint (loc->owner) && loc->inserted)
758               loc->needs_update = 1;
759         }
760
761       /* Do the update.  */
762       update_global_location_list (UGLL_MAY_INSERT);
763     }
764
765   return;
766 }
767
768 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
769    what "auto" is translating to.  */
770
771 static void
772 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
773                                 struct cmd_list_element *c, const char *value)
774 {
775   if (condition_evaluation_mode == condition_evaluation_auto)
776     fprintf_filtered (file,
777                       _("Breakpoint condition evaluation "
778                         "mode is %s (currently %s).\n"),
779                       value,
780                       breakpoint_condition_evaluation_mode ());
781   else
782     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
783                       value);
784 }
785
786 /* A comparison function for bp_location AP and BP that is used by
787    bsearch.  This comparison function only cares about addresses, unlike
788    the more general bp_locations_compare function.  */
789
790 static int
791 bp_locations_compare_addrs (const void *ap, const void *bp)
792 {
793   const struct bp_location *a = *(const struct bp_location **) ap;
794   const struct bp_location *b = *(const struct bp_location **) bp;
795
796   if (a->address == b->address)
797     return 0;
798   else
799     return ((a->address > b->address) - (a->address < b->address));
800 }
801
802 /* Helper function to skip all bp_locations with addresses
803    less than ADDRESS.  It returns the first bp_location that
804    is greater than or equal to ADDRESS.  If none is found, just
805    return NULL.  */
806
807 static struct bp_location **
808 get_first_locp_gte_addr (CORE_ADDR address)
809 {
810   struct bp_location dummy_loc;
811   struct bp_location *dummy_locp = &dummy_loc;
812   struct bp_location **locp_found = NULL;
813
814   /* Initialize the dummy location's address field.  */
815   dummy_loc.address = address;
816
817   /* Find a close match to the first location at ADDRESS.  */
818   locp_found = ((struct bp_location **)
819                 bsearch (&dummy_locp, bp_locations, bp_locations_count,
820                          sizeof (struct bp_location **),
821                          bp_locations_compare_addrs));
822
823   /* Nothing was found, nothing left to do.  */
824   if (locp_found == NULL)
825     return NULL;
826
827   /* We may have found a location that is at ADDRESS but is not the first in the
828      location's list.  Go backwards (if possible) and locate the first one.  */
829   while ((locp_found - 1) >= bp_locations
830          && (*(locp_found - 1))->address == address)
831     locp_found--;
832
833   return locp_found;
834 }
835
836 void
837 set_breakpoint_condition (struct breakpoint *b, const char *exp,
838                           int from_tty)
839 {
840   xfree (b->cond_string);
841   b->cond_string = NULL;
842
843   if (is_watchpoint (b))
844     {
845       struct watchpoint *w = (struct watchpoint *) b;
846
847       w->cond_exp.reset ();
848     }
849   else
850     {
851       struct bp_location *loc;
852
853       for (loc = b->loc; loc; loc = loc->next)
854         {
855           loc->cond.reset ();
856
857           /* No need to free the condition agent expression
858              bytecode (if we have one).  We will handle this
859              when we go through update_global_location_list.  */
860         }
861     }
862
863   if (*exp == 0)
864     {
865       if (from_tty)
866         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
867     }
868   else
869     {
870       const char *arg = exp;
871
872       /* I don't know if it matters whether this is the string the user
873          typed in or the decompiled expression.  */
874       b->cond_string = xstrdup (arg);
875       b->condition_not_parsed = 0;
876
877       if (is_watchpoint (b))
878         {
879           struct watchpoint *w = (struct watchpoint *) b;
880
881           innermost_block.reset ();
882           arg = exp;
883           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
884           if (*arg)
885             error (_("Junk at end of expression"));
886           w->cond_exp_valid_block = innermost_block.block ();
887         }
888       else
889         {
890           struct bp_location *loc;
891
892           for (loc = b->loc; loc; loc = loc->next)
893             {
894               arg = exp;
895               loc->cond =
896                 parse_exp_1 (&arg, loc->address,
897                              block_for_pc (loc->address), 0);
898               if (*arg)
899                 error (_("Junk at end of expression"));
900             }
901         }
902     }
903   mark_breakpoint_modified (b);
904
905   gdb::observers::breakpoint_modified.notify (b);
906 }
907
908 /* Completion for the "condition" command.  */
909
910 static void
911 condition_completer (struct cmd_list_element *cmd,
912                      completion_tracker &tracker,
913                      const char *text, const char *word)
914 {
915   const char *space;
916
917   text = skip_spaces (text);
918   space = skip_to_space (text);
919   if (*space == '\0')
920     {
921       int len;
922       struct breakpoint *b;
923
924       if (text[0] == '$')
925         {
926           /* We don't support completion of history indices.  */
927           if (!isdigit (text[1]))
928             complete_internalvar (tracker, &text[1]);
929           return;
930         }
931
932       /* We're completing the breakpoint number.  */
933       len = strlen (text);
934
935       ALL_BREAKPOINTS (b)
936         {
937           char number[50];
938
939           xsnprintf (number, sizeof (number), "%d", b->number);
940
941           if (strncmp (number, text, len) == 0)
942             {
943               gdb::unique_xmalloc_ptr<char> copy (xstrdup (number));
944               tracker.add_completion (std::move (copy));
945             }
946         }
947
948       return;
949     }
950
951   /* We're completing the expression part.  */
952   text = skip_spaces (space);
953   expression_completer (cmd, tracker, text, word);
954 }
955
956 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
957
958 static void
959 condition_command (const char *arg, int from_tty)
960 {
961   struct breakpoint *b;
962   const char *p;
963   int bnum;
964
965   if (arg == 0)
966     error_no_arg (_("breakpoint number"));
967
968   p = arg;
969   bnum = get_number (&p);
970   if (bnum == 0)
971     error (_("Bad breakpoint argument: '%s'"), arg);
972
973   ALL_BREAKPOINTS (b)
974     if (b->number == bnum)
975       {
976         /* Check if this breakpoint has a "stop" method implemented in an
977            extension language.  This method and conditions entered into GDB
978            from the CLI are mutually exclusive.  */
979         const struct extension_language_defn *extlang
980           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
981
982         if (extlang != NULL)
983           {
984             error (_("Only one stop condition allowed.  There is currently"
985                      " a %s stop condition defined for this breakpoint."),
986                    ext_lang_capitalized_name (extlang));
987           }
988         set_breakpoint_condition (b, p, from_tty);
989
990         if (is_breakpoint (b))
991           update_global_location_list (UGLL_MAY_INSERT);
992
993         return;
994       }
995
996   error (_("No breakpoint number %d."), bnum);
997 }
998
999 /* Check that COMMAND do not contain commands that are suitable
1000    only for tracepoints and not suitable for ordinary breakpoints.
1001    Throw if any such commands is found.  */
1002
1003 static void
1004 check_no_tracepoint_commands (struct command_line *commands)
1005 {
1006   struct command_line *c;
1007
1008   for (c = commands; c; c = c->next)
1009     {
1010       if (c->control_type == while_stepping_control)
1011         error (_("The 'while-stepping' command can "
1012                  "only be used for tracepoints"));
1013
1014       check_no_tracepoint_commands (c->body_list_0.get ());
1015       check_no_tracepoint_commands (c->body_list_1.get ());
1016
1017       /* Not that command parsing removes leading whitespace and comment
1018          lines and also empty lines.  So, we only need to check for
1019          command directly.  */
1020       if (strstr (c->line, "collect ") == c->line)
1021         error (_("The 'collect' command can only be used for tracepoints"));
1022
1023       if (strstr (c->line, "teval ") == c->line)
1024         error (_("The 'teval' command can only be used for tracepoints"));
1025     }
1026 }
1027
1028 struct longjmp_breakpoint : public breakpoint
1029 {
1030   ~longjmp_breakpoint () override;
1031 };
1032
1033 /* Encapsulate tests for different types of tracepoints.  */
1034
1035 static bool
1036 is_tracepoint_type (bptype type)
1037 {
1038   return (type == bp_tracepoint
1039           || type == bp_fast_tracepoint
1040           || type == bp_static_tracepoint);
1041 }
1042
1043 static bool
1044 is_longjmp_type (bptype type)
1045 {
1046   return type == bp_longjmp || type == bp_exception;
1047 }
1048
1049 int
1050 is_tracepoint (const struct breakpoint *b)
1051 {
1052   return is_tracepoint_type (b->type);
1053 }
1054
1055 /* Factory function to create an appropriate instance of breakpoint given
1056    TYPE.  */
1057
1058 static std::unique_ptr<breakpoint>
1059 new_breakpoint_from_type (bptype type)
1060 {
1061   breakpoint *b;
1062
1063   if (is_tracepoint_type (type))
1064     b = new tracepoint ();
1065   else if (is_longjmp_type (type))
1066     b = new longjmp_breakpoint ();
1067   else
1068     b = new breakpoint ();
1069
1070   return std::unique_ptr<breakpoint> (b);
1071 }
1072
1073 /* A helper function that validates that COMMANDS are valid for a
1074    breakpoint.  This function will throw an exception if a problem is
1075    found.  */
1076
1077 static void
1078 validate_commands_for_breakpoint (struct breakpoint *b,
1079                                   struct command_line *commands)
1080 {
1081   if (is_tracepoint (b))
1082     {
1083       struct tracepoint *t = (struct tracepoint *) b;
1084       struct command_line *c;
1085       struct command_line *while_stepping = 0;
1086
1087       /* Reset the while-stepping step count.  The previous commands
1088          might have included a while-stepping action, while the new
1089          ones might not.  */
1090       t->step_count = 0;
1091
1092       /* We need to verify that each top-level element of commands is
1093          valid for tracepoints, that there's at most one
1094          while-stepping element, and that the while-stepping's body
1095          has valid tracing commands excluding nested while-stepping.
1096          We also need to validate the tracepoint action line in the
1097          context of the tracepoint --- validate_actionline actually
1098          has side effects, like setting the tracepoint's
1099          while-stepping STEP_COUNT, in addition to checking if the
1100          collect/teval actions parse and make sense in the
1101          tracepoint's context.  */
1102       for (c = commands; c; c = c->next)
1103         {
1104           if (c->control_type == while_stepping_control)
1105             {
1106               if (b->type == bp_fast_tracepoint)
1107                 error (_("The 'while-stepping' command "
1108                          "cannot be used for fast tracepoint"));
1109               else if (b->type == bp_static_tracepoint)
1110                 error (_("The 'while-stepping' command "
1111                          "cannot be used for static tracepoint"));
1112
1113               if (while_stepping)
1114                 error (_("The 'while-stepping' command "
1115                          "can be used only once"));
1116               else
1117                 while_stepping = c;
1118             }
1119
1120           validate_actionline (c->line, b);
1121         }
1122       if (while_stepping)
1123         {
1124           struct command_line *c2;
1125
1126           gdb_assert (while_stepping->body_list_1 == nullptr);
1127           c2 = while_stepping->body_list_0.get ();
1128           for (; c2; c2 = c2->next)
1129             {
1130               if (c2->control_type == while_stepping_control)
1131                 error (_("The 'while-stepping' command cannot be nested"));
1132             }
1133         }
1134     }
1135   else
1136     {
1137       check_no_tracepoint_commands (commands);
1138     }
1139 }
1140
1141 /* Return a vector of all the static tracepoints set at ADDR.  The
1142    caller is responsible for releasing the vector.  */
1143
1144 std::vector<breakpoint *>
1145 static_tracepoints_here (CORE_ADDR addr)
1146 {
1147   struct breakpoint *b;
1148   std::vector<breakpoint *> found;
1149   struct bp_location *loc;
1150
1151   ALL_BREAKPOINTS (b)
1152     if (b->type == bp_static_tracepoint)
1153       {
1154         for (loc = b->loc; loc; loc = loc->next)
1155           if (loc->address == addr)
1156             found.push_back (b);
1157       }
1158
1159   return found;
1160 }
1161
1162 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1163    validate that only allowed commands are included.  */
1164
1165 void
1166 breakpoint_set_commands (struct breakpoint *b, 
1167                          counted_command_line &&commands)
1168 {
1169   validate_commands_for_breakpoint (b, commands.get ());
1170
1171   b->commands = std::move (commands);
1172   gdb::observers::breakpoint_modified.notify (b);
1173 }
1174
1175 /* Set the internal `silent' flag on the breakpoint.  Note that this
1176    is not the same as the "silent" that may appear in the breakpoint's
1177    commands.  */
1178
1179 void
1180 breakpoint_set_silent (struct breakpoint *b, int silent)
1181 {
1182   int old_silent = b->silent;
1183
1184   b->silent = silent;
1185   if (old_silent != silent)
1186     gdb::observers::breakpoint_modified.notify (b);
1187 }
1188
1189 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1190    breakpoint work for any thread.  */
1191
1192 void
1193 breakpoint_set_thread (struct breakpoint *b, int thread)
1194 {
1195   int old_thread = b->thread;
1196
1197   b->thread = thread;
1198   if (old_thread != thread)
1199     gdb::observers::breakpoint_modified.notify (b);
1200 }
1201
1202 /* Set the task for this breakpoint.  If TASK is 0, make the
1203    breakpoint work for any task.  */
1204
1205 void
1206 breakpoint_set_task (struct breakpoint *b, int task)
1207 {
1208   int old_task = b->task;
1209
1210   b->task = task;
1211   if (old_task != task)
1212     gdb::observers::breakpoint_modified.notify (b);
1213 }
1214
1215 static void
1216 commands_command_1 (const char *arg, int from_tty,
1217                     struct command_line *control)
1218 {
1219   counted_command_line cmd;
1220   /* cmd_read will be true once we have read cmd.  Note that cmd might still be
1221      NULL after the call to read_command_lines if the user provides an empty
1222      list of command by just typing "end".  */
1223   bool cmd_read = false;
1224
1225   std::string new_arg;
1226
1227   if (arg == NULL || !*arg)
1228     {
1229       if (breakpoint_count - prev_breakpoint_count > 1)
1230         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1231                                  breakpoint_count);
1232       else if (breakpoint_count > 0)
1233         new_arg = string_printf ("%d", breakpoint_count);
1234       arg = new_arg.c_str ();
1235     }
1236
1237   map_breakpoint_numbers
1238     (arg, [&] (breakpoint *b)
1239      {
1240        if (!cmd_read)
1241          {
1242            gdb_assert (cmd == NULL);
1243            if (control != NULL)
1244              cmd = control->body_list_0;
1245            else
1246              {
1247                std::string str
1248                  = string_printf (_("Type commands for breakpoint(s) "
1249                                     "%s, one per line."),
1250                                   arg);
1251
1252                auto do_validate = [=] (const char *line)
1253                                   {
1254                                     validate_actionline (line, b);
1255                                   };
1256                gdb::function_view<void (const char *)> validator;
1257                if (is_tracepoint (b))
1258                  validator = do_validate;
1259
1260                cmd = read_command_lines (str.c_str (), from_tty, 1, validator);
1261              }
1262            cmd_read = true;
1263          }
1264
1265        /* If a breakpoint was on the list more than once, we don't need to
1266           do anything.  */
1267        if (b->commands != cmd)
1268          {
1269            validate_commands_for_breakpoint (b, cmd.get ());
1270            b->commands = cmd;
1271            gdb::observers::breakpoint_modified.notify (b);
1272          }
1273      });
1274 }
1275
1276 static void
1277 commands_command (const char *arg, int from_tty)
1278 {
1279   commands_command_1 (arg, from_tty, NULL);
1280 }
1281
1282 /* Like commands_command, but instead of reading the commands from
1283    input stream, takes them from an already parsed command structure.
1284
1285    This is used by cli-script.c to DTRT with breakpoint commands
1286    that are part of if and while bodies.  */
1287 enum command_control_type
1288 commands_from_control_command (const char *arg, struct command_line *cmd)
1289 {
1290   commands_command_1 (arg, 0, cmd);
1291   return simple_control;
1292 }
1293
1294 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1295
1296 static int
1297 bp_location_has_shadow (struct bp_location *bl)
1298 {
1299   if (bl->loc_type != bp_loc_software_breakpoint)
1300     return 0;
1301   if (!bl->inserted)
1302     return 0;
1303   if (bl->target_info.shadow_len == 0)
1304     /* BL isn't valid, or doesn't shadow memory.  */
1305     return 0;
1306   return 1;
1307 }
1308
1309 /* Update BUF, which is LEN bytes read from the target address
1310    MEMADDR, by replacing a memory breakpoint with its shadowed
1311    contents.
1312
1313    If READBUF is not NULL, this buffer must not overlap with the of
1314    the breakpoint location's shadow_contents buffer.  Otherwise, a
1315    failed assertion internal error will be raised.  */
1316
1317 static void
1318 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1319                             const gdb_byte *writebuf_org,
1320                             ULONGEST memaddr, LONGEST len,
1321                             struct bp_target_info *target_info,
1322                             struct gdbarch *gdbarch)
1323 {
1324   /* Now do full processing of the found relevant range of elements.  */
1325   CORE_ADDR bp_addr = 0;
1326   int bp_size = 0;
1327   int bptoffset = 0;
1328
1329   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1330                                  current_program_space->aspace, 0))
1331     {
1332       /* The breakpoint is inserted in a different address space.  */
1333       return;
1334     }
1335
1336   /* Addresses and length of the part of the breakpoint that
1337      we need to copy.  */
1338   bp_addr = target_info->placed_address;
1339   bp_size = target_info->shadow_len;
1340
1341   if (bp_addr + bp_size <= memaddr)
1342     {
1343       /* The breakpoint is entirely before the chunk of memory we are
1344          reading.  */
1345       return;
1346     }
1347
1348   if (bp_addr >= memaddr + len)
1349     {
1350       /* The breakpoint is entirely after the chunk of memory we are
1351          reading.  */
1352       return;
1353     }
1354
1355   /* Offset within shadow_contents.  */
1356   if (bp_addr < memaddr)
1357     {
1358       /* Only copy the second part of the breakpoint.  */
1359       bp_size -= memaddr - bp_addr;
1360       bptoffset = memaddr - bp_addr;
1361       bp_addr = memaddr;
1362     }
1363
1364   if (bp_addr + bp_size > memaddr + len)
1365     {
1366       /* Only copy the first part of the breakpoint.  */
1367       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1368     }
1369
1370   if (readbuf != NULL)
1371     {
1372       /* Verify that the readbuf buffer does not overlap with the
1373          shadow_contents buffer.  */
1374       gdb_assert (target_info->shadow_contents >= readbuf + len
1375                   || readbuf >= (target_info->shadow_contents
1376                                  + target_info->shadow_len));
1377
1378       /* Update the read buffer with this inserted breakpoint's
1379          shadow.  */
1380       memcpy (readbuf + bp_addr - memaddr,
1381               target_info->shadow_contents + bptoffset, bp_size);
1382     }
1383   else
1384     {
1385       const unsigned char *bp;
1386       CORE_ADDR addr = target_info->reqstd_address;
1387       int placed_size;
1388
1389       /* Update the shadow with what we want to write to memory.  */
1390       memcpy (target_info->shadow_contents + bptoffset,
1391               writebuf_org + bp_addr - memaddr, bp_size);
1392
1393       /* Determine appropriate breakpoint contents and size for this
1394          address.  */
1395       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1396
1397       /* Update the final write buffer with this inserted
1398          breakpoint's INSN.  */
1399       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1400     }
1401 }
1402
1403 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1404    by replacing any memory breakpoints with their shadowed contents.
1405
1406    If READBUF is not NULL, this buffer must not overlap with any of
1407    the breakpoint location's shadow_contents buffers.  Otherwise,
1408    a failed assertion internal error will be raised.
1409
1410    The range of shadowed area by each bp_location is:
1411      bl->address - bp_locations_placed_address_before_address_max
1412      up to bl->address + bp_locations_shadow_len_after_address_max
1413    The range we were requested to resolve shadows for is:
1414      memaddr ... memaddr + len
1415    Thus the safe cutoff boundaries for performance optimization are
1416      memaddr + len <= (bl->address
1417                        - bp_locations_placed_address_before_address_max)
1418    and:
1419      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1420
1421 void
1422 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1423                         const gdb_byte *writebuf_org,
1424                         ULONGEST memaddr, LONGEST len)
1425 {
1426   /* Left boundary, right boundary and median element of our binary
1427      search.  */
1428   unsigned bc_l, bc_r, bc;
1429
1430   /* Find BC_L which is a leftmost element which may affect BUF
1431      content.  It is safe to report lower value but a failure to
1432      report higher one.  */
1433
1434   bc_l = 0;
1435   bc_r = bp_locations_count;
1436   while (bc_l + 1 < bc_r)
1437     {
1438       struct bp_location *bl;
1439
1440       bc = (bc_l + bc_r) / 2;
1441       bl = bp_locations[bc];
1442
1443       /* Check first BL->ADDRESS will not overflow due to the added
1444          constant.  Then advance the left boundary only if we are sure
1445          the BC element can in no way affect the BUF content (MEMADDR
1446          to MEMADDR + LEN range).
1447
1448          Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1449          offset so that we cannot miss a breakpoint with its shadow
1450          range tail still reaching MEMADDR.  */
1451
1452       if ((bl->address + bp_locations_shadow_len_after_address_max
1453            >= bl->address)
1454           && (bl->address + bp_locations_shadow_len_after_address_max
1455               <= memaddr))
1456         bc_l = bc;
1457       else
1458         bc_r = bc;
1459     }
1460
1461   /* Due to the binary search above, we need to make sure we pick the
1462      first location that's at BC_L's address.  E.g., if there are
1463      multiple locations at the same address, BC_L may end up pointing
1464      at a duplicate location, and miss the "master"/"inserted"
1465      location.  Say, given locations L1, L2 and L3 at addresses A and
1466      B:
1467
1468       L1@A, L2@A, L3@B, ...
1469
1470      BC_L could end up pointing at location L2, while the "master"
1471      location could be L1.  Since the `loc->inserted' flag is only set
1472      on "master" locations, we'd forget to restore the shadow of L1
1473      and L2.  */
1474   while (bc_l > 0
1475          && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1476     bc_l--;
1477
1478   /* Now do full processing of the found relevant range of elements.  */
1479
1480   for (bc = bc_l; bc < bp_locations_count; bc++)
1481   {
1482     struct bp_location *bl = bp_locations[bc];
1483
1484     /* bp_location array has BL->OWNER always non-NULL.  */
1485     if (bl->owner->type == bp_none)
1486       warning (_("reading through apparently deleted breakpoint #%d?"),
1487                bl->owner->number);
1488
1489     /* Performance optimization: any further element can no longer affect BUF
1490        content.  */
1491
1492     if (bl->address >= bp_locations_placed_address_before_address_max
1493         && memaddr + len <= (bl->address
1494                              - bp_locations_placed_address_before_address_max))
1495       break;
1496
1497     if (!bp_location_has_shadow (bl))
1498       continue;
1499
1500     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1501                                 memaddr, len, &bl->target_info, bl->gdbarch);
1502   }
1503 }
1504
1505 \f
1506
1507 /* Return true if BPT is either a software breakpoint or a hardware
1508    breakpoint.  */
1509
1510 int
1511 is_breakpoint (const struct breakpoint *bpt)
1512 {
1513   return (bpt->type == bp_breakpoint
1514           || bpt->type == bp_hardware_breakpoint
1515           || bpt->type == bp_dprintf);
1516 }
1517
1518 /* Return true if BPT is of any hardware watchpoint kind.  */
1519
1520 static int
1521 is_hardware_watchpoint (const struct breakpoint *bpt)
1522 {
1523   return (bpt->type == bp_hardware_watchpoint
1524           || bpt->type == bp_read_watchpoint
1525           || bpt->type == bp_access_watchpoint);
1526 }
1527
1528 /* Return true if BPT is of any watchpoint kind, hardware or
1529    software.  */
1530
1531 int
1532 is_watchpoint (const struct breakpoint *bpt)
1533 {
1534   return (is_hardware_watchpoint (bpt)
1535           || bpt->type == bp_watchpoint);
1536 }
1537
1538 /* Returns true if the current thread and its running state are safe
1539    to evaluate or update watchpoint B.  Watchpoints on local
1540    expressions need to be evaluated in the context of the thread that
1541    was current when the watchpoint was created, and, that thread needs
1542    to be stopped to be able to select the correct frame context.
1543    Watchpoints on global expressions can be evaluated on any thread,
1544    and in any state.  It is presently left to the target allowing
1545    memory accesses when threads are running.  */
1546
1547 static int
1548 watchpoint_in_thread_scope (struct watchpoint *b)
1549 {
1550   return (b->pspace == current_program_space
1551           && (b->watchpoint_thread == null_ptid
1552               || (inferior_ptid == b->watchpoint_thread
1553                   && !inferior_thread ()->executing)));
1554 }
1555
1556 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1557    associated bp_watchpoint_scope breakpoint.  */
1558
1559 static void
1560 watchpoint_del_at_next_stop (struct watchpoint *w)
1561 {
1562   if (w->related_breakpoint != w)
1563     {
1564       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1565       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1566       w->related_breakpoint->disposition = disp_del_at_next_stop;
1567       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1568       w->related_breakpoint = w;
1569     }
1570   w->disposition = disp_del_at_next_stop;
1571 }
1572
1573 /* Extract a bitfield value from value VAL using the bit parameters contained in
1574    watchpoint W.  */
1575
1576 static struct value *
1577 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1578 {
1579   struct value *bit_val;
1580
1581   if (val == NULL)
1582     return NULL;
1583
1584   bit_val = allocate_value (value_type (val));
1585
1586   unpack_value_bitfield (bit_val,
1587                          w->val_bitpos,
1588                          w->val_bitsize,
1589                          value_contents_for_printing (val),
1590                          value_offset (val),
1591                          val);
1592
1593   return bit_val;
1594 }
1595
1596 /* Allocate a dummy location and add it to B, which must be a software
1597    watchpoint.  This is required because even if a software watchpoint
1598    is not watching any memory, bpstat_stop_status requires a location
1599    to be able to report stops.  */
1600
1601 static void
1602 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1603                                             struct program_space *pspace)
1604 {
1605   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1606
1607   b->loc = allocate_bp_location (b);
1608   b->loc->pspace = pspace;
1609   b->loc->address = -1;
1610   b->loc->length = -1;
1611 }
1612
1613 /* Returns true if B is a software watchpoint that is not watching any
1614    memory (e.g., "watch $pc").  */
1615
1616 static int
1617 is_no_memory_software_watchpoint (struct breakpoint *b)
1618 {
1619   return (b->type == bp_watchpoint
1620           && b->loc != NULL
1621           && b->loc->next == NULL
1622           && b->loc->address == -1
1623           && b->loc->length == -1);
1624 }
1625
1626 /* Assuming that B is a watchpoint:
1627    - Reparse watchpoint expression, if REPARSE is non-zero
1628    - Evaluate expression and store the result in B->val
1629    - Evaluate the condition if there is one, and store the result
1630      in b->loc->cond.
1631    - Update the list of values that must be watched in B->loc.
1632
1633    If the watchpoint disposition is disp_del_at_next_stop, then do
1634    nothing.  If this is local watchpoint that is out of scope, delete
1635    it.
1636
1637    Even with `set breakpoint always-inserted on' the watchpoints are
1638    removed + inserted on each stop here.  Normal breakpoints must
1639    never be removed because they might be missed by a running thread
1640    when debugging in non-stop mode.  On the other hand, hardware
1641    watchpoints (is_hardware_watchpoint; processed here) are specific
1642    to each LWP since they are stored in each LWP's hardware debug
1643    registers.  Therefore, such LWP must be stopped first in order to
1644    be able to modify its hardware watchpoints.
1645
1646    Hardware watchpoints must be reset exactly once after being
1647    presented to the user.  It cannot be done sooner, because it would
1648    reset the data used to present the watchpoint hit to the user.  And
1649    it must not be done later because it could display the same single
1650    watchpoint hit during multiple GDB stops.  Note that the latter is
1651    relevant only to the hardware watchpoint types bp_read_watchpoint
1652    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1653    not user-visible - its hit is suppressed if the memory content has
1654    not changed.
1655
1656    The following constraints influence the location where we can reset
1657    hardware watchpoints:
1658
1659    * target_stopped_by_watchpoint and target_stopped_data_address are
1660      called several times when GDB stops.
1661
1662    [linux] 
1663    * Multiple hardware watchpoints can be hit at the same time,
1664      causing GDB to stop.  GDB only presents one hardware watchpoint
1665      hit at a time as the reason for stopping, and all the other hits
1666      are presented later, one after the other, each time the user
1667      requests the execution to be resumed.  Execution is not resumed
1668      for the threads still having pending hit event stored in
1669      LWP_INFO->STATUS.  While the watchpoint is already removed from
1670      the inferior on the first stop the thread hit event is kept being
1671      reported from its cached value by linux_nat_stopped_data_address
1672      until the real thread resume happens after the watchpoint gets
1673      presented and thus its LWP_INFO->STATUS gets reset.
1674
1675    Therefore the hardware watchpoint hit can get safely reset on the
1676    watchpoint removal from inferior.  */
1677
1678 static void
1679 update_watchpoint (struct watchpoint *b, int reparse)
1680 {
1681   int within_current_scope;
1682   struct frame_id saved_frame_id;
1683   int frame_saved;
1684
1685   /* If this is a local watchpoint, we only want to check if the
1686      watchpoint frame is in scope if the current thread is the thread
1687      that was used to create the watchpoint.  */
1688   if (!watchpoint_in_thread_scope (b))
1689     return;
1690
1691   if (b->disposition == disp_del_at_next_stop)
1692     return;
1693  
1694   frame_saved = 0;
1695
1696   /* Determine if the watchpoint is within scope.  */
1697   if (b->exp_valid_block == NULL)
1698     within_current_scope = 1;
1699   else
1700     {
1701       struct frame_info *fi = get_current_frame ();
1702       struct gdbarch *frame_arch = get_frame_arch (fi);
1703       CORE_ADDR frame_pc = get_frame_pc (fi);
1704
1705       /* If we're at a point where the stack has been destroyed
1706          (e.g. in a function epilogue), unwinding may not work
1707          properly. Do not attempt to recreate locations at this
1708          point.  See similar comments in watchpoint_check.  */
1709       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1710         return;
1711
1712       /* Save the current frame's ID so we can restore it after
1713          evaluating the watchpoint expression on its own frame.  */
1714       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1715          took a frame parameter, so that we didn't have to change the
1716          selected frame.  */
1717       frame_saved = 1;
1718       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1719
1720       fi = frame_find_by_id (b->watchpoint_frame);
1721       within_current_scope = (fi != NULL);
1722       if (within_current_scope)
1723         select_frame (fi);
1724     }
1725
1726   /* We don't free locations.  They are stored in the bp_location array
1727      and update_global_location_list will eventually delete them and
1728      remove breakpoints if needed.  */
1729   b->loc = NULL;
1730
1731   if (within_current_scope && reparse)
1732     {
1733       const char *s;
1734
1735       b->exp.reset ();
1736       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1737       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1738       /* If the meaning of expression itself changed, the old value is
1739          no longer relevant.  We don't want to report a watchpoint hit
1740          to the user when the old value and the new value may actually
1741          be completely different objects.  */
1742       b->val = NULL;
1743       b->val_valid = 0;
1744
1745       /* Note that unlike with breakpoints, the watchpoint's condition
1746          expression is stored in the breakpoint object, not in the
1747          locations (re)created below.  */
1748       if (b->cond_string != NULL)
1749         {
1750           b->cond_exp.reset ();
1751
1752           s = b->cond_string;
1753           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1754         }
1755     }
1756
1757   /* If we failed to parse the expression, for example because
1758      it refers to a global variable in a not-yet-loaded shared library,
1759      don't try to insert watchpoint.  We don't automatically delete
1760      such watchpoint, though, since failure to parse expression
1761      is different from out-of-scope watchpoint.  */
1762   if (!target_has_execution)
1763     {
1764       /* Without execution, memory can't change.  No use to try and
1765          set watchpoint locations.  The watchpoint will be reset when
1766          the target gains execution, through breakpoint_re_set.  */
1767       if (!can_use_hw_watchpoints)
1768         {
1769           if (b->ops->works_in_software_mode (b))
1770             b->type = bp_watchpoint;
1771           else
1772             error (_("Can't set read/access watchpoint when "
1773                      "hardware watchpoints are disabled."));
1774         }
1775     }
1776   else if (within_current_scope && b->exp)
1777     {
1778       int pc = 0;
1779       std::vector<value_ref_ptr> val_chain;
1780       struct value *v, *result;
1781       struct program_space *frame_pspace;
1782
1783       fetch_subexp_value (b->exp.get (), &pc, &v, &result, &val_chain, 0);
1784
1785       /* Avoid setting b->val if it's already set.  The meaning of
1786          b->val is 'the last value' user saw, and we should update
1787          it only if we reported that last value to user.  As it
1788          happens, the code that reports it updates b->val directly.
1789          We don't keep track of the memory value for masked
1790          watchpoints.  */
1791       if (!b->val_valid && !is_masked_watchpoint (b))
1792         {
1793           if (b->val_bitsize != 0)
1794             v = extract_bitfield_from_watchpoint_value (b, v);
1795           b->val = release_value (v);
1796           b->val_valid = 1;
1797         }
1798
1799       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1800
1801       /* Look at each value on the value chain.  */
1802       gdb_assert (!val_chain.empty ());
1803       for (const value_ref_ptr &iter : val_chain)
1804         {
1805           v = iter.get ();
1806
1807           /* If it's a memory location, and GDB actually needed
1808              its contents to evaluate the expression, then we
1809              must watch it.  If the first value returned is
1810              still lazy, that means an error occurred reading it;
1811              watch it anyway in case it becomes readable.  */
1812           if (VALUE_LVAL (v) == lval_memory
1813               && (v == val_chain[0] || ! value_lazy (v)))
1814             {
1815               struct type *vtype = check_typedef (value_type (v));
1816
1817               /* We only watch structs and arrays if user asked
1818                  for it explicitly, never if they just happen to
1819                  appear in the middle of some value chain.  */
1820               if (v == result
1821                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1822                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1823                 {
1824                   CORE_ADDR addr;
1825                   enum target_hw_bp_type type;
1826                   struct bp_location *loc, **tmp;
1827                   int bitpos = 0, bitsize = 0;
1828
1829                   if (value_bitsize (v) != 0)
1830                     {
1831                       /* Extract the bit parameters out from the bitfield
1832                          sub-expression.  */
1833                       bitpos = value_bitpos (v);
1834                       bitsize = value_bitsize (v);
1835                     }
1836                   else if (v == result && b->val_bitsize != 0)
1837                     {
1838                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1839                         lvalue whose bit parameters are saved in the fields
1840                         VAL_BITPOS and VAL_BITSIZE.  */
1841                       bitpos = b->val_bitpos;
1842                       bitsize = b->val_bitsize;
1843                     }
1844
1845                   addr = value_address (v);
1846                   if (bitsize != 0)
1847                     {
1848                       /* Skip the bytes that don't contain the bitfield.  */
1849                       addr += bitpos / 8;
1850                     }
1851
1852                   type = hw_write;
1853                   if (b->type == bp_read_watchpoint)
1854                     type = hw_read;
1855                   else if (b->type == bp_access_watchpoint)
1856                     type = hw_access;
1857
1858                   loc = allocate_bp_location (b);
1859                   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
1860                     ;
1861                   *tmp = loc;
1862                   loc->gdbarch = get_type_arch (value_type (v));
1863
1864                   loc->pspace = frame_pspace;
1865                   loc->address = address_significant (loc->gdbarch, addr);
1866
1867                   if (bitsize != 0)
1868                     {
1869                       /* Just cover the bytes that make up the bitfield.  */
1870                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
1871                     }
1872                   else
1873                     loc->length = TYPE_LENGTH (value_type (v));
1874
1875                   loc->watchpoint_type = type;
1876                 }
1877             }
1878         }
1879
1880       /* Change the type of breakpoint between hardware assisted or
1881          an ordinary watchpoint depending on the hardware support
1882          and free hardware slots.  REPARSE is set when the inferior
1883          is started.  */
1884       if (reparse)
1885         {
1886           int reg_cnt;
1887           enum bp_loc_type loc_type;
1888           struct bp_location *bl;
1889
1890           reg_cnt = can_use_hardware_watchpoint (val_chain);
1891
1892           if (reg_cnt)
1893             {
1894               int i, target_resources_ok, other_type_used;
1895               enum bptype type;
1896
1897               /* Use an exact watchpoint when there's only one memory region to be
1898                  watched, and only one debug register is needed to watch it.  */
1899               b->exact = target_exact_watchpoints && reg_cnt == 1;
1900
1901               /* We need to determine how many resources are already
1902                  used for all other hardware watchpoints plus this one
1903                  to see if we still have enough resources to also fit
1904                  this watchpoint in as well.  */
1905
1906               /* If this is a software watchpoint, we try to turn it
1907                  to a hardware one -- count resources as if B was of
1908                  hardware watchpoint type.  */
1909               type = b->type;
1910               if (type == bp_watchpoint)
1911                 type = bp_hardware_watchpoint;
1912
1913               /* This watchpoint may or may not have been placed on
1914                  the list yet at this point (it won't be in the list
1915                  if we're trying to create it for the first time,
1916                  through watch_command), so always account for it
1917                  manually.  */
1918
1919               /* Count resources used by all watchpoints except B.  */
1920               i = hw_watchpoint_used_count_others (b, type, &other_type_used);
1921
1922               /* Add in the resources needed for B.  */
1923               i += hw_watchpoint_use_count (b);
1924
1925               target_resources_ok
1926                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1927               if (target_resources_ok <= 0)
1928                 {
1929                   int sw_mode = b->ops->works_in_software_mode (b);
1930
1931                   if (target_resources_ok == 0 && !sw_mode)
1932                     error (_("Target does not support this type of "
1933                              "hardware watchpoint."));
1934                   else if (target_resources_ok < 0 && !sw_mode)
1935                     error (_("There are not enough available hardware "
1936                              "resources for this watchpoint."));
1937
1938                   /* Downgrade to software watchpoint.  */
1939                   b->type = bp_watchpoint;
1940                 }
1941               else
1942                 {
1943                   /* If this was a software watchpoint, we've just
1944                      found we have enough resources to turn it to a
1945                      hardware watchpoint.  Otherwise, this is a
1946                      nop.  */
1947                   b->type = type;
1948                 }
1949             }
1950           else if (!b->ops->works_in_software_mode (b))
1951             {
1952               if (!can_use_hw_watchpoints)
1953                 error (_("Can't set read/access watchpoint when "
1954                          "hardware watchpoints are disabled."));
1955               else
1956                 error (_("Expression cannot be implemented with "
1957                          "read/access watchpoint."));
1958             }
1959           else
1960             b->type = bp_watchpoint;
1961
1962           loc_type = (b->type == bp_watchpoint? bp_loc_other
1963                       : bp_loc_hardware_watchpoint);
1964           for (bl = b->loc; bl; bl = bl->next)
1965             bl->loc_type = loc_type;
1966         }
1967
1968       /* If a software watchpoint is not watching any memory, then the
1969          above left it without any location set up.  But,
1970          bpstat_stop_status requires a location to be able to report
1971          stops, so make sure there's at least a dummy one.  */
1972       if (b->type == bp_watchpoint && b->loc == NULL)
1973         software_watchpoint_add_no_memory_location (b, frame_pspace);
1974     }
1975   else if (!within_current_scope)
1976     {
1977       printf_filtered (_("\
1978 Watchpoint %d deleted because the program has left the block\n\
1979 in which its expression is valid.\n"),
1980                        b->number);
1981       watchpoint_del_at_next_stop (b);
1982     }
1983
1984   /* Restore the selected frame.  */
1985   if (frame_saved)
1986     select_frame (frame_find_by_id (saved_frame_id));
1987 }
1988
1989
1990 /* Returns 1 iff breakpoint location should be
1991    inserted in the inferior.  We don't differentiate the type of BL's owner
1992    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1993    breakpoint_ops is not defined, because in insert_bp_location,
1994    tracepoint's insert_location will not be called.  */
1995 static int
1996 should_be_inserted (struct bp_location *bl)
1997 {
1998   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
1999     return 0;
2000
2001   if (bl->owner->disposition == disp_del_at_next_stop)
2002     return 0;
2003
2004   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2005     return 0;
2006
2007   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2008     return 0;
2009
2010   /* This is set for example, when we're attached to the parent of a
2011      vfork, and have detached from the child.  The child is running
2012      free, and we expect it to do an exec or exit, at which point the
2013      OS makes the parent schedulable again (and the target reports
2014      that the vfork is done).  Until the child is done with the shared
2015      memory region, do not insert breakpoints in the parent, otherwise
2016      the child could still trip on the parent's breakpoints.  Since
2017      the parent is blocked anyway, it won't miss any breakpoint.  */
2018   if (bl->pspace->breakpoints_not_allowed)
2019     return 0;
2020
2021   /* Don't insert a breakpoint if we're trying to step past its
2022      location, except if the breakpoint is a single-step breakpoint,
2023      and the breakpoint's thread is the thread which is stepping past
2024      a breakpoint.  */
2025   if ((bl->loc_type == bp_loc_software_breakpoint
2026        || bl->loc_type == bp_loc_hardware_breakpoint)
2027       && stepping_past_instruction_at (bl->pspace->aspace,
2028                                        bl->address)
2029       /* The single-step breakpoint may be inserted at the location
2030          we're trying to step if the instruction branches to itself.
2031          However, the instruction won't be executed at all and it may
2032          break the semantics of the instruction, for example, the
2033          instruction is a conditional branch or updates some flags.
2034          We can't fix it unless GDB is able to emulate the instruction
2035          or switch to displaced stepping.  */
2036       && !(bl->owner->type == bp_single_step
2037            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2038     {
2039       if (debug_infrun)
2040         {
2041           fprintf_unfiltered (gdb_stdlog,
2042                               "infrun: skipping breakpoint: "
2043                               "stepping past insn at: %s\n",
2044                               paddress (bl->gdbarch, bl->address));
2045         }
2046       return 0;
2047     }
2048
2049   /* Don't insert watchpoints if we're trying to step past the
2050      instruction that triggered one.  */
2051   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2052       && stepping_past_nonsteppable_watchpoint ())
2053     {
2054       if (debug_infrun)
2055         {
2056           fprintf_unfiltered (gdb_stdlog,
2057                               "infrun: stepping past non-steppable watchpoint. "
2058                               "skipping watchpoint at %s:%d\n",
2059                               paddress (bl->gdbarch, bl->address),
2060                               bl->length);
2061         }
2062       return 0;
2063     }
2064
2065   return 1;
2066 }
2067
2068 /* Same as should_be_inserted but does the check assuming
2069    that the location is not duplicated.  */
2070
2071 static int
2072 unduplicated_should_be_inserted (struct bp_location *bl)
2073 {
2074   int result;
2075   const int save_duplicate = bl->duplicate;
2076
2077   bl->duplicate = 0;
2078   result = should_be_inserted (bl);
2079   bl->duplicate = save_duplicate;
2080   return result;
2081 }
2082
2083 /* Parses a conditional described by an expression COND into an
2084    agent expression bytecode suitable for evaluation
2085    by the bytecode interpreter.  Return NULL if there was
2086    any error during parsing.  */
2087
2088 static agent_expr_up
2089 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2090 {
2091   if (cond == NULL)
2092     return NULL;
2093
2094   agent_expr_up aexpr;
2095
2096   /* We don't want to stop processing, so catch any errors
2097      that may show up.  */
2098   TRY
2099     {
2100       aexpr = gen_eval_for_expr (scope, cond);
2101     }
2102
2103   CATCH (ex, RETURN_MASK_ERROR)
2104     {
2105       /* If we got here, it means the condition could not be parsed to a valid
2106          bytecode expression and thus can't be evaluated on the target's side.
2107          It's no use iterating through the conditions.  */
2108     }
2109   END_CATCH
2110
2111   /* We have a valid agent expression.  */
2112   return aexpr;
2113 }
2114
2115 /* Based on location BL, create a list of breakpoint conditions to be
2116    passed on to the target.  If we have duplicated locations with different
2117    conditions, we will add such conditions to the list.  The idea is that the
2118    target will evaluate the list of conditions and will only notify GDB when
2119    one of them is true.  */
2120
2121 static void
2122 build_target_condition_list (struct bp_location *bl)
2123 {
2124   struct bp_location **locp = NULL, **loc2p;
2125   int null_condition_or_parse_error = 0;
2126   int modified = bl->needs_update;
2127   struct bp_location *loc;
2128
2129   /* Release conditions left over from a previous insert.  */
2130   bl->target_info.conditions.clear ();
2131
2132   /* This is only meaningful if the target is
2133      evaluating conditions and if the user has
2134      opted for condition evaluation on the target's
2135      side.  */
2136   if (gdb_evaluates_breakpoint_condition_p ()
2137       || !target_supports_evaluation_of_breakpoint_conditions ())
2138     return;
2139
2140   /* Do a first pass to check for locations with no assigned
2141      conditions or conditions that fail to parse to a valid agent expression
2142      bytecode.  If any of these happen, then it's no use to send conditions
2143      to the target since this location will always trigger and generate a
2144      response back to GDB.  */
2145   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2146     {
2147       loc = (*loc2p);
2148       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2149         {
2150           if (modified)
2151             {
2152               /* Re-parse the conditions since something changed.  In that
2153                  case we already freed the condition bytecodes (see
2154                  force_breakpoint_reinsertion).  We just
2155                  need to parse the condition to bytecodes again.  */
2156               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2157                                                         loc->cond.get ());
2158             }
2159
2160           /* If we have a NULL bytecode expression, it means something
2161              went wrong or we have a null condition expression.  */
2162           if (!loc->cond_bytecode)
2163             {
2164               null_condition_or_parse_error = 1;
2165               break;
2166             }
2167         }
2168     }
2169
2170   /* If any of these happened, it means we will have to evaluate the conditions
2171      for the location's address on gdb's side.  It is no use keeping bytecodes
2172      for all the other duplicate locations, thus we free all of them here.
2173
2174      This is so we have a finer control over which locations' conditions are
2175      being evaluated by GDB or the remote stub.  */
2176   if (null_condition_or_parse_error)
2177     {
2178       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2179         {
2180           loc = (*loc2p);
2181           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2182             {
2183               /* Only go as far as the first NULL bytecode is
2184                  located.  */
2185               if (!loc->cond_bytecode)
2186                 return;
2187
2188               loc->cond_bytecode.reset ();
2189             }
2190         }
2191     }
2192
2193   /* No NULL conditions or failed bytecode generation.  Build a condition list
2194      for this location's address.  */
2195   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2196     {
2197       loc = (*loc2p);
2198       if (loc->cond
2199           && is_breakpoint (loc->owner)
2200           && loc->pspace->num == bl->pspace->num
2201           && loc->owner->enable_state == bp_enabled
2202           && loc->enabled)
2203         {
2204           /* Add the condition to the vector.  This will be used later
2205              to send the conditions to the target.  */
2206           bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2207         }
2208     }
2209
2210   return;
2211 }
2212
2213 /* Parses a command described by string CMD into an agent expression
2214    bytecode suitable for evaluation by the bytecode interpreter.
2215    Return NULL if there was any error during parsing.  */
2216
2217 static agent_expr_up
2218 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2219 {
2220   const char *cmdrest;
2221   const char *format_start, *format_end;
2222   struct gdbarch *gdbarch = get_current_arch ();
2223
2224   if (cmd == NULL)
2225     return NULL;
2226
2227   cmdrest = cmd;
2228
2229   if (*cmdrest == ',')
2230     ++cmdrest;
2231   cmdrest = skip_spaces (cmdrest);
2232
2233   if (*cmdrest++ != '"')
2234     error (_("No format string following the location"));
2235
2236   format_start = cmdrest;
2237
2238   format_pieces fpieces (&cmdrest);
2239
2240   format_end = cmdrest;
2241
2242   if (*cmdrest++ != '"')
2243     error (_("Bad format string, non-terminated '\"'."));
2244   
2245   cmdrest = skip_spaces (cmdrest);
2246
2247   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2248     error (_("Invalid argument syntax"));
2249
2250   if (*cmdrest == ',')
2251     cmdrest++;
2252   cmdrest = skip_spaces (cmdrest);
2253
2254   /* For each argument, make an expression.  */
2255
2256   std::vector<struct expression *> argvec;
2257   while (*cmdrest != '\0')
2258     {
2259       const char *cmd1;
2260
2261       cmd1 = cmdrest;
2262       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2263       argvec.push_back (expr.release ());
2264       cmdrest = cmd1;
2265       if (*cmdrest == ',')
2266         ++cmdrest;
2267     }
2268
2269   agent_expr_up aexpr;
2270
2271   /* We don't want to stop processing, so catch any errors
2272      that may show up.  */
2273   TRY
2274     {
2275       aexpr = gen_printf (scope, gdbarch, 0, 0,
2276                           format_start, format_end - format_start,
2277                           argvec.size (), argvec.data ());
2278     }
2279   CATCH (ex, RETURN_MASK_ERROR)
2280     {
2281       /* If we got here, it means the command could not be parsed to a valid
2282          bytecode expression and thus can't be evaluated on the target's side.
2283          It's no use iterating through the other commands.  */
2284     }
2285   END_CATCH
2286
2287   /* We have a valid agent expression, return it.  */
2288   return aexpr;
2289 }
2290
2291 /* Based on location BL, create a list of breakpoint commands to be
2292    passed on to the target.  If we have duplicated locations with
2293    different commands, we will add any such to the list.  */
2294
2295 static void
2296 build_target_command_list (struct bp_location *bl)
2297 {
2298   struct bp_location **locp = NULL, **loc2p;
2299   int null_command_or_parse_error = 0;
2300   int modified = bl->needs_update;
2301   struct bp_location *loc;
2302
2303   /* Clear commands left over from a previous insert.  */
2304   bl->target_info.tcommands.clear ();
2305
2306   if (!target_can_run_breakpoint_commands ())
2307     return;
2308
2309   /* For now, limit to agent-style dprintf breakpoints.  */
2310   if (dprintf_style != dprintf_style_agent)
2311     return;
2312
2313   /* For now, if we have any duplicate location that isn't a dprintf,
2314      don't install the target-side commands, as that would make the
2315      breakpoint not be reported to the core, and we'd lose
2316      control.  */
2317   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2318     {
2319       loc = (*loc2p);
2320       if (is_breakpoint (loc->owner)
2321           && loc->pspace->num == bl->pspace->num
2322           && loc->owner->type != bp_dprintf)
2323         return;
2324     }
2325
2326   /* Do a first pass to check for locations with no assigned
2327      conditions or conditions that fail to parse to a valid agent expression
2328      bytecode.  If any of these happen, then it's no use to send conditions
2329      to the target since this location will always trigger and generate a
2330      response back to GDB.  */
2331   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2332     {
2333       loc = (*loc2p);
2334       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2335         {
2336           if (modified)
2337             {
2338               /* Re-parse the commands since something changed.  In that
2339                  case we already freed the command bytecodes (see
2340                  force_breakpoint_reinsertion).  We just
2341                  need to parse the command to bytecodes again.  */
2342               loc->cmd_bytecode
2343                 = parse_cmd_to_aexpr (bl->address,
2344                                       loc->owner->extra_string);
2345             }
2346
2347           /* If we have a NULL bytecode expression, it means something
2348              went wrong or we have a null command expression.  */
2349           if (!loc->cmd_bytecode)
2350             {
2351               null_command_or_parse_error = 1;
2352               break;
2353             }
2354         }
2355     }
2356
2357   /* If anything failed, then we're not doing target-side commands,
2358      and so clean up.  */
2359   if (null_command_or_parse_error)
2360     {
2361       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2362         {
2363           loc = (*loc2p);
2364           if (is_breakpoint (loc->owner)
2365               && loc->pspace->num == bl->pspace->num)
2366             {
2367               /* Only go as far as the first NULL bytecode is
2368                  located.  */
2369               if (loc->cmd_bytecode == NULL)
2370                 return;
2371
2372               loc->cmd_bytecode.reset ();
2373             }
2374         }
2375     }
2376
2377   /* No NULL commands or failed bytecode generation.  Build a command list
2378      for this location's address.  */
2379   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2380     {
2381       loc = (*loc2p);
2382       if (loc->owner->extra_string
2383           && is_breakpoint (loc->owner)
2384           && loc->pspace->num == bl->pspace->num
2385           && loc->owner->enable_state == bp_enabled
2386           && loc->enabled)
2387         {
2388           /* Add the command to the vector.  This will be used later
2389              to send the commands to the target.  */
2390           bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2391         }
2392     }
2393
2394   bl->target_info.persist = 0;
2395   /* Maybe flag this location as persistent.  */
2396   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2397     bl->target_info.persist = 1;
2398 }
2399
2400 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2401    of breakpoint according to ADDR except single-step breakpoint.
2402    Get the kind of single-step breakpoint according to the current
2403    registers state.  */
2404
2405 static int
2406 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2407 {
2408   if (bl->owner->type == bp_single_step)
2409     {
2410       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2411       struct regcache *regcache;
2412
2413       regcache = get_thread_regcache (thr);
2414
2415       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2416                                                          regcache, addr);
2417     }
2418   else
2419     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2420 }
2421
2422 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2423    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2424    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2425    Returns 0 for success, 1 if the bp_location type is not supported or
2426    -1 for failure.
2427
2428    NOTE drow/2003-09-09: This routine could be broken down to an
2429    object-style method for each breakpoint or catchpoint type.  */
2430 static int
2431 insert_bp_location (struct bp_location *bl,
2432                     struct ui_file *tmp_error_stream,
2433                     int *disabled_breaks,
2434                     int *hw_breakpoint_error,
2435                     int *hw_bp_error_explained_already)
2436 {
2437   gdb_exception bp_excpt = exception_none;
2438
2439   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2440     return 0;
2441
2442   /* Note we don't initialize bl->target_info, as that wipes out
2443      the breakpoint location's shadow_contents if the breakpoint
2444      is still inserted at that location.  This in turn breaks
2445      target_read_memory which depends on these buffers when
2446      a memory read is requested at the breakpoint location:
2447      Once the target_info has been wiped, we fail to see that
2448      we have a breakpoint inserted at that address and thus
2449      read the breakpoint instead of returning the data saved in
2450      the breakpoint location's shadow contents.  */
2451   bl->target_info.reqstd_address = bl->address;
2452   bl->target_info.placed_address_space = bl->pspace->aspace;
2453   bl->target_info.length = bl->length;
2454
2455   /* When working with target-side conditions, we must pass all the conditions
2456      for the same breakpoint address down to the target since GDB will not
2457      insert those locations.  With a list of breakpoint conditions, the target
2458      can decide when to stop and notify GDB.  */
2459
2460   if (is_breakpoint (bl->owner))
2461     {
2462       build_target_condition_list (bl);
2463       build_target_command_list (bl);
2464       /* Reset the modification marker.  */
2465       bl->needs_update = 0;
2466     }
2467
2468   if (bl->loc_type == bp_loc_software_breakpoint
2469       || bl->loc_type == bp_loc_hardware_breakpoint)
2470     {
2471       if (bl->owner->type != bp_hardware_breakpoint)
2472         {
2473           /* If the explicitly specified breakpoint type
2474              is not hardware breakpoint, check the memory map to see
2475              if the breakpoint address is in read only memory or not.
2476
2477              Two important cases are:
2478              - location type is not hardware breakpoint, memory
2479              is readonly.  We change the type of the location to
2480              hardware breakpoint.
2481              - location type is hardware breakpoint, memory is
2482              read-write.  This means we've previously made the
2483              location hardware one, but then the memory map changed,
2484              so we undo.
2485              
2486              When breakpoints are removed, remove_breakpoints will use
2487              location types we've just set here, the only possible
2488              problem is that memory map has changed during running
2489              program, but it's not going to work anyway with current
2490              gdb.  */
2491           struct mem_region *mr 
2492             = lookup_mem_region (bl->target_info.reqstd_address);
2493           
2494           if (mr)
2495             {
2496               if (automatic_hardware_breakpoints)
2497                 {
2498                   enum bp_loc_type new_type;
2499                   
2500                   if (mr->attrib.mode != MEM_RW)
2501                     new_type = bp_loc_hardware_breakpoint;
2502                   else 
2503                     new_type = bp_loc_software_breakpoint;
2504                   
2505                   if (new_type != bl->loc_type)
2506                     {
2507                       static int said = 0;
2508
2509                       bl->loc_type = new_type;
2510                       if (!said)
2511                         {
2512                           fprintf_filtered (gdb_stdout,
2513                                             _("Note: automatically using "
2514                                               "hardware breakpoints for "
2515                                               "read-only addresses.\n"));
2516                           said = 1;
2517                         }
2518                     }
2519                 }
2520               else if (bl->loc_type == bp_loc_software_breakpoint
2521                        && mr->attrib.mode != MEM_RW)
2522                 {
2523                   fprintf_unfiltered (tmp_error_stream,
2524                                       _("Cannot insert breakpoint %d.\n"
2525                                         "Cannot set software breakpoint "
2526                                         "at read-only address %s\n"),
2527                                       bl->owner->number,
2528                                       paddress (bl->gdbarch, bl->address));
2529                   return 1;
2530                 }
2531             }
2532         }
2533         
2534       /* First check to see if we have to handle an overlay.  */
2535       if (overlay_debugging == ovly_off
2536           || bl->section == NULL
2537           || !(section_is_overlay (bl->section)))
2538         {
2539           /* No overlay handling: just set the breakpoint.  */
2540           TRY
2541             {
2542               int val;
2543
2544               val = bl->owner->ops->insert_location (bl);
2545               if (val)
2546                 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2547             }
2548           CATCH (e, RETURN_MASK_ALL)
2549             {
2550               bp_excpt = e;
2551             }
2552           END_CATCH
2553         }
2554       else
2555         {
2556           /* This breakpoint is in an overlay section.
2557              Shall we set a breakpoint at the LMA?  */
2558           if (!overlay_events_enabled)
2559             {
2560               /* Yes -- overlay event support is not active, 
2561                  so we must try to set a breakpoint at the LMA.
2562                  This will not work for a hardware breakpoint.  */
2563               if (bl->loc_type == bp_loc_hardware_breakpoint)
2564                 warning (_("hardware breakpoint %d not supported in overlay!"),
2565                          bl->owner->number);
2566               else
2567                 {
2568                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2569                                                              bl->section);
2570                   /* Set a software (trap) breakpoint at the LMA.  */
2571                   bl->overlay_target_info = bl->target_info;
2572                   bl->overlay_target_info.reqstd_address = addr;
2573
2574                   /* No overlay handling: just set the breakpoint.  */
2575                   TRY
2576                     {
2577                       int val;
2578
2579                       bl->overlay_target_info.kind
2580                         = breakpoint_kind (bl, &addr);
2581                       bl->overlay_target_info.placed_address = addr;
2582                       val = target_insert_breakpoint (bl->gdbarch,
2583                                                       &bl->overlay_target_info);
2584                       if (val)
2585                         bp_excpt
2586                           = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2587                     }
2588                   CATCH (e, RETURN_MASK_ALL)
2589                     {
2590                       bp_excpt = e;
2591                     }
2592                   END_CATCH
2593
2594                   if (bp_excpt.reason != 0)
2595                     fprintf_unfiltered (tmp_error_stream,
2596                                         "Overlay breakpoint %d "
2597                                         "failed: in ROM?\n",
2598                                         bl->owner->number);
2599                 }
2600             }
2601           /* Shall we set a breakpoint at the VMA? */
2602           if (section_is_mapped (bl->section))
2603             {
2604               /* Yes.  This overlay section is mapped into memory.  */
2605               TRY
2606                 {
2607                   int val;
2608
2609                   val = bl->owner->ops->insert_location (bl);
2610                   if (val)
2611                     bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2612                 }
2613               CATCH (e, RETURN_MASK_ALL)
2614                 {
2615                   bp_excpt = e;
2616                 }
2617               END_CATCH
2618             }
2619           else
2620             {
2621               /* No.  This breakpoint will not be inserted.  
2622                  No error, but do not mark the bp as 'inserted'.  */
2623               return 0;
2624             }
2625         }
2626
2627       if (bp_excpt.reason != 0)
2628         {
2629           /* Can't set the breakpoint.  */
2630
2631           /* In some cases, we might not be able to insert a
2632              breakpoint in a shared library that has already been
2633              removed, but we have not yet processed the shlib unload
2634              event.  Unfortunately, some targets that implement
2635              breakpoint insertion themselves can't tell why the
2636              breakpoint insertion failed (e.g., the remote target
2637              doesn't define error codes), so we must treat generic
2638              errors as memory errors.  */
2639           if (bp_excpt.reason == RETURN_ERROR
2640               && (bp_excpt.error == GENERIC_ERROR
2641                   || bp_excpt.error == MEMORY_ERROR)
2642               && bl->loc_type == bp_loc_software_breakpoint
2643               && (solib_name_from_address (bl->pspace, bl->address)
2644                   || shared_objfile_contains_address_p (bl->pspace,
2645                                                         bl->address)))
2646             {
2647               /* See also: disable_breakpoints_in_shlibs.  */
2648               bl->shlib_disabled = 1;
2649               gdb::observers::breakpoint_modified.notify (bl->owner);
2650               if (!*disabled_breaks)
2651                 {
2652                   fprintf_unfiltered (tmp_error_stream, 
2653                                       "Cannot insert breakpoint %d.\n", 
2654                                       bl->owner->number);
2655                   fprintf_unfiltered (tmp_error_stream, 
2656                                       "Temporarily disabling shared "
2657                                       "library breakpoints:\n");
2658                 }
2659               *disabled_breaks = 1;
2660               fprintf_unfiltered (tmp_error_stream,
2661                                   "breakpoint #%d\n", bl->owner->number);
2662               return 0;
2663             }
2664           else
2665             {
2666               if (bl->loc_type == bp_loc_hardware_breakpoint)
2667                 {
2668                   *hw_breakpoint_error = 1;
2669                   *hw_bp_error_explained_already = bp_excpt.message != NULL;
2670                   fprintf_unfiltered (tmp_error_stream,
2671                                       "Cannot insert hardware breakpoint %d%s",
2672                                       bl->owner->number,
2673                                       bp_excpt.message ? ":" : ".\n");
2674                   if (bp_excpt.message != NULL)
2675                     fprintf_unfiltered (tmp_error_stream, "%s.\n",
2676                                         bp_excpt.message);
2677                 }
2678               else
2679                 {
2680                   if (bp_excpt.message == NULL)
2681                     {
2682                       std::string message
2683                         = memory_error_message (TARGET_XFER_E_IO,
2684                                                 bl->gdbarch, bl->address);
2685
2686                       fprintf_unfiltered (tmp_error_stream,
2687                                           "Cannot insert breakpoint %d.\n"
2688                                           "%s\n",
2689                                           bl->owner->number, message.c_str ());
2690                     }
2691                   else
2692                     {
2693                       fprintf_unfiltered (tmp_error_stream,
2694                                           "Cannot insert breakpoint %d: %s\n",
2695                                           bl->owner->number,
2696                                           bp_excpt.message);
2697                     }
2698                 }
2699               return 1;
2700
2701             }
2702         }
2703       else
2704         bl->inserted = 1;
2705
2706       return 0;
2707     }
2708
2709   else if (bl->loc_type == bp_loc_hardware_watchpoint
2710            /* NOTE drow/2003-09-08: This state only exists for removing
2711               watchpoints.  It's not clear that it's necessary...  */
2712            && bl->owner->disposition != disp_del_at_next_stop)
2713     {
2714       int val;
2715
2716       gdb_assert (bl->owner->ops != NULL
2717                   && bl->owner->ops->insert_location != NULL);
2718
2719       val = bl->owner->ops->insert_location (bl);
2720
2721       /* If trying to set a read-watchpoint, and it turns out it's not
2722          supported, try emulating one with an access watchpoint.  */
2723       if (val == 1 && bl->watchpoint_type == hw_read)
2724         {
2725           struct bp_location *loc, **loc_temp;
2726
2727           /* But don't try to insert it, if there's already another
2728              hw_access location that would be considered a duplicate
2729              of this one.  */
2730           ALL_BP_LOCATIONS (loc, loc_temp)
2731             if (loc != bl
2732                 && loc->watchpoint_type == hw_access
2733                 && watchpoint_locations_match (bl, loc))
2734               {
2735                 bl->duplicate = 1;
2736                 bl->inserted = 1;
2737                 bl->target_info = loc->target_info;
2738                 bl->watchpoint_type = hw_access;
2739                 val = 0;
2740                 break;
2741               }
2742
2743           if (val == 1)
2744             {
2745               bl->watchpoint_type = hw_access;
2746               val = bl->owner->ops->insert_location (bl);
2747
2748               if (val)
2749                 /* Back to the original value.  */
2750                 bl->watchpoint_type = hw_read;
2751             }
2752         }
2753
2754       bl->inserted = (val == 0);
2755     }
2756
2757   else if (bl->owner->type == bp_catchpoint)
2758     {
2759       int val;
2760
2761       gdb_assert (bl->owner->ops != NULL
2762                   && bl->owner->ops->insert_location != NULL);
2763
2764       val = bl->owner->ops->insert_location (bl);
2765       if (val)
2766         {
2767           bl->owner->enable_state = bp_disabled;
2768
2769           if (val == 1)
2770             warning (_("\
2771 Error inserting catchpoint %d: Your system does not support this type\n\
2772 of catchpoint."), bl->owner->number);
2773           else
2774             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2775         }
2776
2777       bl->inserted = (val == 0);
2778
2779       /* We've already printed an error message if there was a problem
2780          inserting this catchpoint, and we've disabled the catchpoint,
2781          so just return success.  */
2782       return 0;
2783     }
2784
2785   return 0;
2786 }
2787
2788 /* This function is called when program space PSPACE is about to be
2789    deleted.  It takes care of updating breakpoints to not reference
2790    PSPACE anymore.  */
2791
2792 void
2793 breakpoint_program_space_exit (struct program_space *pspace)
2794 {
2795   struct breakpoint *b, *b_temp;
2796   struct bp_location *loc, **loc_temp;
2797
2798   /* Remove any breakpoint that was set through this program space.  */
2799   ALL_BREAKPOINTS_SAFE (b, b_temp)
2800     {
2801       if (b->pspace == pspace)
2802         delete_breakpoint (b);
2803     }
2804
2805   /* Breakpoints set through other program spaces could have locations
2806      bound to PSPACE as well.  Remove those.  */
2807   ALL_BP_LOCATIONS (loc, loc_temp)
2808     {
2809       struct bp_location *tmp;
2810
2811       if (loc->pspace == pspace)
2812         {
2813           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2814           if (loc->owner->loc == loc)
2815             loc->owner->loc = loc->next;
2816           else
2817             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2818               if (tmp->next == loc)
2819                 {
2820                   tmp->next = loc->next;
2821                   break;
2822                 }
2823         }
2824     }
2825
2826   /* Now update the global location list to permanently delete the
2827      removed locations above.  */
2828   update_global_location_list (UGLL_DONT_INSERT);
2829 }
2830
2831 /* Make sure all breakpoints are inserted in inferior.
2832    Throws exception on any error.
2833    A breakpoint that is already inserted won't be inserted
2834    again, so calling this function twice is safe.  */
2835 void
2836 insert_breakpoints (void)
2837 {
2838   struct breakpoint *bpt;
2839
2840   ALL_BREAKPOINTS (bpt)
2841     if (is_hardware_watchpoint (bpt))
2842       {
2843         struct watchpoint *w = (struct watchpoint *) bpt;
2844
2845         update_watchpoint (w, 0 /* don't reparse.  */);
2846       }
2847
2848   /* Updating watchpoints creates new locations, so update the global
2849      location list.  Explicitly tell ugll to insert locations and
2850      ignore breakpoints_always_inserted_mode.  */
2851   update_global_location_list (UGLL_INSERT);
2852 }
2853
2854 /* Invoke CALLBACK for each of bp_location.  */
2855
2856 void
2857 iterate_over_bp_locations (walk_bp_location_callback callback)
2858 {
2859   struct bp_location *loc, **loc_tmp;
2860
2861   ALL_BP_LOCATIONS (loc, loc_tmp)
2862     {
2863       callback (loc, NULL);
2864     }
2865 }
2866
2867 /* This is used when we need to synch breakpoint conditions between GDB and the
2868    target.  It is the case with deleting and disabling of breakpoints when using
2869    always-inserted mode.  */
2870
2871 static void
2872 update_inserted_breakpoint_locations (void)
2873 {
2874   struct bp_location *bl, **blp_tmp;
2875   int error_flag = 0;
2876   int val = 0;
2877   int disabled_breaks = 0;
2878   int hw_breakpoint_error = 0;
2879   int hw_bp_details_reported = 0;
2880
2881   string_file tmp_error_stream;
2882
2883   /* Explicitly mark the warning -- this will only be printed if
2884      there was an error.  */
2885   tmp_error_stream.puts ("Warning:\n");
2886
2887   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2888
2889   ALL_BP_LOCATIONS (bl, blp_tmp)
2890     {
2891       /* We only want to update software breakpoints and hardware
2892          breakpoints.  */
2893       if (!is_breakpoint (bl->owner))
2894         continue;
2895
2896       /* We only want to update locations that are already inserted
2897          and need updating.  This is to avoid unwanted insertion during
2898          deletion of breakpoints.  */
2899       if (!bl->inserted || !bl->needs_update)
2900         continue;
2901
2902       switch_to_program_space_and_thread (bl->pspace);
2903
2904       /* For targets that support global breakpoints, there's no need
2905          to select an inferior to insert breakpoint to.  In fact, even
2906          if we aren't attached to any process yet, we should still
2907          insert breakpoints.  */
2908       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2909           && inferior_ptid == null_ptid)
2910         continue;
2911
2912       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2913                                     &hw_breakpoint_error, &hw_bp_details_reported);
2914       if (val)
2915         error_flag = val;
2916     }
2917
2918   if (error_flag)
2919     {
2920       target_terminal::ours_for_output ();
2921       error_stream (tmp_error_stream);
2922     }
2923 }
2924
2925 /* Used when starting or continuing the program.  */
2926
2927 static void
2928 insert_breakpoint_locations (void)
2929 {
2930   struct breakpoint *bpt;
2931   struct bp_location *bl, **blp_tmp;
2932   int error_flag = 0;
2933   int val = 0;
2934   int disabled_breaks = 0;
2935   int hw_breakpoint_error = 0;
2936   int hw_bp_error_explained_already = 0;
2937
2938   string_file tmp_error_stream;
2939
2940   /* Explicitly mark the warning -- this will only be printed if
2941      there was an error.  */
2942   tmp_error_stream.puts ("Warning:\n");
2943
2944   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2945
2946   ALL_BP_LOCATIONS (bl, blp_tmp)
2947     {
2948       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2949         continue;
2950
2951       /* There is no point inserting thread-specific breakpoints if
2952          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2953          has BL->OWNER always non-NULL.  */
2954       if (bl->owner->thread != -1
2955           && !valid_global_thread_id (bl->owner->thread))
2956         continue;
2957
2958       switch_to_program_space_and_thread (bl->pspace);
2959
2960       /* For targets that support global breakpoints, there's no need
2961          to select an inferior to insert breakpoint to.  In fact, even
2962          if we aren't attached to any process yet, we should still
2963          insert breakpoints.  */
2964       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2965           && inferior_ptid == null_ptid)
2966         continue;
2967
2968       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2969                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
2970       if (val)
2971         error_flag = val;
2972     }
2973
2974   /* If we failed to insert all locations of a watchpoint, remove
2975      them, as half-inserted watchpoint is of limited use.  */
2976   ALL_BREAKPOINTS (bpt)  
2977     {
2978       int some_failed = 0;
2979       struct bp_location *loc;
2980
2981       if (!is_hardware_watchpoint (bpt))
2982         continue;
2983
2984       if (!breakpoint_enabled (bpt))
2985         continue;
2986
2987       if (bpt->disposition == disp_del_at_next_stop)
2988         continue;
2989       
2990       for (loc = bpt->loc; loc; loc = loc->next)
2991         if (!loc->inserted && should_be_inserted (loc))
2992           {
2993             some_failed = 1;
2994             break;
2995           }
2996       if (some_failed)
2997         {
2998           for (loc = bpt->loc; loc; loc = loc->next)
2999             if (loc->inserted)
3000               remove_breakpoint (loc);
3001
3002           hw_breakpoint_error = 1;
3003           tmp_error_stream.printf ("Could not insert "
3004                                    "hardware watchpoint %d.\n",
3005                                    bpt->number);
3006           error_flag = -1;
3007         }
3008     }
3009
3010   if (error_flag)
3011     {
3012       /* If a hardware breakpoint or watchpoint was inserted, add a
3013          message about possibly exhausted resources.  */
3014       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3015         {
3016           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3017 You may have requested too many hardware breakpoints/watchpoints.\n");
3018         }
3019       target_terminal::ours_for_output ();
3020       error_stream (tmp_error_stream);
3021     }
3022 }
3023
3024 /* Used when the program stops.
3025    Returns zero if successful, or non-zero if there was a problem
3026    removing a breakpoint location.  */
3027
3028 int
3029 remove_breakpoints (void)
3030 {
3031   struct bp_location *bl, **blp_tmp;
3032   int val = 0;
3033
3034   ALL_BP_LOCATIONS (bl, blp_tmp)
3035   {
3036     if (bl->inserted && !is_tracepoint (bl->owner))
3037       val |= remove_breakpoint (bl);
3038   }
3039   return val;
3040 }
3041
3042 /* When a thread exits, remove breakpoints that are related to
3043    that thread.  */
3044
3045 static void
3046 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3047 {
3048   struct breakpoint *b, *b_tmp;
3049
3050   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3051     {
3052       if (b->thread == tp->global_num && user_breakpoint_p (b))
3053         {
3054           b->disposition = disp_del_at_next_stop;
3055
3056           printf_filtered (_("\
3057 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3058                            b->number, print_thread_id (tp));
3059
3060           /* Hide it from the user.  */
3061           b->number = 0;
3062        }
3063     }
3064 }
3065
3066 /* Remove breakpoints of inferior INF.  */
3067
3068 int
3069 remove_breakpoints_inf (inferior *inf)
3070 {
3071   struct bp_location *bl, **blp_tmp;
3072   int val;
3073
3074   ALL_BP_LOCATIONS (bl, blp_tmp)
3075   {
3076     if (bl->pspace != inf->pspace)
3077       continue;
3078
3079     if (bl->inserted && !bl->target_info.persist)
3080       {
3081         val = remove_breakpoint (bl);
3082         if (val != 0)
3083           return val;
3084       }
3085   }
3086   return 0;
3087 }
3088
3089 static int internal_breakpoint_number = -1;
3090
3091 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3092    If INTERNAL is non-zero, the breakpoint number will be populated
3093    from internal_breakpoint_number and that variable decremented.
3094    Otherwise the breakpoint number will be populated from
3095    breakpoint_count and that value incremented.  Internal breakpoints
3096    do not set the internal var bpnum.  */
3097 static void
3098 set_breakpoint_number (int internal, struct breakpoint *b)
3099 {
3100   if (internal)
3101     b->number = internal_breakpoint_number--;
3102   else
3103     {
3104       set_breakpoint_count (breakpoint_count + 1);
3105       b->number = breakpoint_count;
3106     }
3107 }
3108
3109 static struct breakpoint *
3110 create_internal_breakpoint (struct gdbarch *gdbarch,
3111                             CORE_ADDR address, enum bptype type,
3112                             const struct breakpoint_ops *ops)
3113 {
3114   symtab_and_line sal;
3115   sal.pc = address;
3116   sal.section = find_pc_overlay (sal.pc);
3117   sal.pspace = current_program_space;
3118
3119   breakpoint *b = set_raw_breakpoint (gdbarch, sal, type, ops);
3120   b->number = internal_breakpoint_number--;
3121   b->disposition = disp_donttouch;
3122
3123   return b;
3124 }
3125
3126 static const char *const longjmp_names[] =
3127   {
3128     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3129   };
3130 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3131
3132 /* Per-objfile data private to breakpoint.c.  */
3133 struct breakpoint_objfile_data
3134 {
3135   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3136   struct bound_minimal_symbol overlay_msym {};
3137
3138   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3139   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES] {};
3140
3141   /* True if we have looked for longjmp probes.  */
3142   int longjmp_searched = 0;
3143
3144   /* SystemTap probe points for longjmp (if any).  These are non-owning
3145      references.  */
3146   std::vector<probe *> longjmp_probes;
3147
3148   /* Minimal symbol for "std::terminate()" (if any).  */
3149   struct bound_minimal_symbol terminate_msym {};
3150
3151   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3152   struct bound_minimal_symbol exception_msym {};
3153
3154   /* True if we have looked for exception probes.  */
3155   int exception_searched = 0;
3156
3157   /* SystemTap probe points for unwinding (if any).  These are non-owning
3158      references.  */
3159   std::vector<probe *> exception_probes;
3160 };
3161
3162 static const struct objfile_data *breakpoint_objfile_key;
3163
3164 /* Minimal symbol not found sentinel.  */
3165 static struct minimal_symbol msym_not_found;
3166
3167 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3168
3169 static int
3170 msym_not_found_p (const struct minimal_symbol *msym)
3171 {
3172   return msym == &msym_not_found;
3173 }
3174
3175 /* Return per-objfile data needed by breakpoint.c.
3176    Allocate the data if necessary.  */
3177
3178 static struct breakpoint_objfile_data *
3179 get_breakpoint_objfile_data (struct objfile *objfile)
3180 {
3181   struct breakpoint_objfile_data *bp_objfile_data;
3182
3183   bp_objfile_data = ((struct breakpoint_objfile_data *)
3184                      objfile_data (objfile, breakpoint_objfile_key));
3185   if (bp_objfile_data == NULL)
3186     {
3187       bp_objfile_data = new breakpoint_objfile_data ();
3188       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3189     }
3190   return bp_objfile_data;
3191 }
3192
3193 static void
3194 free_breakpoint_objfile_data (struct objfile *obj, void *data)
3195 {
3196   struct breakpoint_objfile_data *bp_objfile_data
3197     = (struct breakpoint_objfile_data *) data;
3198
3199   delete bp_objfile_data;
3200 }
3201
3202 static void
3203 create_overlay_event_breakpoint (void)
3204 {
3205   struct objfile *objfile;
3206   const char *const func_name = "_ovly_debug_event";
3207
3208   ALL_OBJFILES (objfile)
3209     {
3210       struct breakpoint *b;
3211       struct breakpoint_objfile_data *bp_objfile_data;
3212       CORE_ADDR addr;
3213       struct explicit_location explicit_loc;
3214
3215       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3216
3217       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3218         continue;
3219
3220       if (bp_objfile_data->overlay_msym.minsym == NULL)
3221         {
3222           struct bound_minimal_symbol m;
3223
3224           m = lookup_minimal_symbol_text (func_name, objfile);
3225           if (m.minsym == NULL)
3226             {
3227               /* Avoid future lookups in this objfile.  */
3228               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3229               continue;
3230             }
3231           bp_objfile_data->overlay_msym = m;
3232         }
3233
3234       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3235       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3236                                       bp_overlay_event,
3237                                       &internal_breakpoint_ops);
3238       initialize_explicit_location (&explicit_loc);
3239       explicit_loc.function_name = ASTRDUP (func_name);
3240       b->location = new_explicit_location (&explicit_loc);
3241
3242       if (overlay_debugging == ovly_auto)
3243         {
3244           b->enable_state = bp_enabled;
3245           overlay_events_enabled = 1;
3246         }
3247       else
3248        {
3249          b->enable_state = bp_disabled;
3250          overlay_events_enabled = 0;
3251        }
3252     }
3253 }
3254
3255 static void
3256 create_longjmp_master_breakpoint (void)
3257 {
3258   struct program_space *pspace;
3259
3260   scoped_restore_current_program_space restore_pspace;
3261
3262   ALL_PSPACES (pspace)
3263   {
3264     struct objfile *objfile;
3265
3266     set_current_program_space (pspace);
3267
3268     ALL_OBJFILES (objfile)
3269     {
3270       int i;
3271       struct gdbarch *gdbarch;
3272       struct breakpoint_objfile_data *bp_objfile_data;
3273
3274       gdbarch = get_objfile_arch (objfile);
3275
3276       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3277
3278       if (!bp_objfile_data->longjmp_searched)
3279         {
3280           std::vector<probe *> ret
3281             = find_probes_in_objfile (objfile, "libc", "longjmp");
3282
3283           if (!ret.empty ())
3284             {
3285               /* We are only interested in checking one element.  */
3286               probe *p = ret[0];
3287
3288               if (!p->can_evaluate_arguments ())
3289                 {
3290                   /* We cannot use the probe interface here, because it does
3291                      not know how to evaluate arguments.  */
3292                   ret.clear ();
3293                 }
3294             }
3295           bp_objfile_data->longjmp_probes = ret;
3296           bp_objfile_data->longjmp_searched = 1;
3297         }
3298
3299       if (!bp_objfile_data->longjmp_probes.empty ())
3300         {
3301           for (probe *p : bp_objfile_data->longjmp_probes)
3302             {
3303               struct breakpoint *b;
3304
3305               b = create_internal_breakpoint (gdbarch,
3306                                               p->get_relocated_address (objfile),
3307                                               bp_longjmp_master,
3308                                               &internal_breakpoint_ops);
3309               b->location = new_probe_location ("-probe-stap libc:longjmp");
3310               b->enable_state = bp_disabled;
3311             }
3312
3313           continue;
3314         }
3315
3316       if (!gdbarch_get_longjmp_target_p (gdbarch))
3317         continue;
3318
3319       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3320         {
3321           struct breakpoint *b;
3322           const char *func_name;
3323           CORE_ADDR addr;
3324           struct explicit_location explicit_loc;
3325
3326           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3327             continue;
3328
3329           func_name = longjmp_names[i];
3330           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3331             {
3332               struct bound_minimal_symbol m;
3333
3334               m = lookup_minimal_symbol_text (func_name, objfile);
3335               if (m.minsym == NULL)
3336                 {
3337                   /* Prevent future lookups in this objfile.  */
3338                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3339                   continue;
3340                 }
3341               bp_objfile_data->longjmp_msym[i] = m;
3342             }
3343
3344           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3345           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3346                                           &internal_breakpoint_ops);
3347           initialize_explicit_location (&explicit_loc);
3348           explicit_loc.function_name = ASTRDUP (func_name);
3349           b->location = new_explicit_location (&explicit_loc);
3350           b->enable_state = bp_disabled;
3351         }
3352     }
3353   }
3354 }
3355
3356 /* Create a master std::terminate breakpoint.  */
3357 static void
3358 create_std_terminate_master_breakpoint (void)
3359 {
3360   struct program_space *pspace;
3361   const char *const func_name = "std::terminate()";
3362
3363   scoped_restore_current_program_space restore_pspace;
3364
3365   ALL_PSPACES (pspace)
3366   {
3367     struct objfile *objfile;
3368     CORE_ADDR addr;
3369
3370     set_current_program_space (pspace);
3371
3372     ALL_OBJFILES (objfile)
3373     {
3374       struct breakpoint *b;
3375       struct breakpoint_objfile_data *bp_objfile_data;
3376       struct explicit_location explicit_loc;
3377
3378       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3379
3380       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3381         continue;
3382
3383       if (bp_objfile_data->terminate_msym.minsym == NULL)
3384         {
3385           struct bound_minimal_symbol m;
3386
3387           m = lookup_minimal_symbol (func_name, NULL, objfile);
3388           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3389                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3390             {
3391               /* Prevent future lookups in this objfile.  */
3392               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3393               continue;
3394             }
3395           bp_objfile_data->terminate_msym = m;
3396         }
3397
3398       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3399       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3400                                       bp_std_terminate_master,
3401                                       &internal_breakpoint_ops);
3402       initialize_explicit_location (&explicit_loc);
3403       explicit_loc.function_name = ASTRDUP (func_name);
3404       b->location = new_explicit_location (&explicit_loc);
3405       b->enable_state = bp_disabled;
3406     }
3407   }
3408 }
3409
3410 /* Install a master breakpoint on the unwinder's debug hook.  */
3411
3412 static void
3413 create_exception_master_breakpoint (void)
3414 {
3415   struct objfile *objfile;
3416   const char *const func_name = "_Unwind_DebugHook";
3417
3418   ALL_OBJFILES (objfile)
3419     {
3420       struct breakpoint *b;
3421       struct gdbarch *gdbarch;
3422       struct breakpoint_objfile_data *bp_objfile_data;
3423       CORE_ADDR addr;
3424       struct explicit_location explicit_loc;
3425
3426       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3427
3428       /* We prefer the SystemTap probe point if it exists.  */
3429       if (!bp_objfile_data->exception_searched)
3430         {
3431           std::vector<probe *> ret
3432             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3433
3434           if (!ret.empty ())
3435             {
3436               /* We are only interested in checking one element.  */
3437               probe *p = ret[0];
3438
3439               if (!p->can_evaluate_arguments ())
3440                 {
3441                   /* We cannot use the probe interface here, because it does
3442                      not know how to evaluate arguments.  */
3443                   ret.clear ();
3444                 }
3445             }
3446           bp_objfile_data->exception_probes = ret;
3447           bp_objfile_data->exception_searched = 1;
3448         }
3449
3450       if (!bp_objfile_data->exception_probes.empty ())
3451         {
3452           gdbarch = get_objfile_arch (objfile);
3453
3454           for (probe *p : bp_objfile_data->exception_probes)
3455             {
3456               b = create_internal_breakpoint (gdbarch,
3457                                               p->get_relocated_address (objfile),
3458                                               bp_exception_master,
3459                                               &internal_breakpoint_ops);
3460               b->location = new_probe_location ("-probe-stap libgcc:unwind");
3461               b->enable_state = bp_disabled;
3462             }
3463
3464           continue;
3465         }
3466
3467       /* Otherwise, try the hook function.  */
3468
3469       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3470         continue;
3471
3472       gdbarch = get_objfile_arch (objfile);
3473
3474       if (bp_objfile_data->exception_msym.minsym == NULL)
3475         {
3476           struct bound_minimal_symbol debug_hook;
3477
3478           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3479           if (debug_hook.minsym == NULL)
3480             {
3481               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3482               continue;
3483             }
3484
3485           bp_objfile_data->exception_msym = debug_hook;
3486         }
3487
3488       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3489       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3490                                                  current_top_target ());
3491       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3492                                       &internal_breakpoint_ops);
3493       initialize_explicit_location (&explicit_loc);
3494       explicit_loc.function_name = ASTRDUP (func_name);
3495       b->location = new_explicit_location (&explicit_loc);
3496       b->enable_state = bp_disabled;
3497     }
3498 }
3499
3500 /* Does B have a location spec?  */
3501
3502 static int
3503 breakpoint_event_location_empty_p (const struct breakpoint *b)
3504 {
3505   return b->location != NULL && event_location_empty_p (b->location.get ());
3506 }
3507
3508 void
3509 update_breakpoints_after_exec (void)
3510 {
3511   struct breakpoint *b, *b_tmp;
3512   struct bp_location *bploc, **bplocp_tmp;
3513
3514   /* We're about to delete breakpoints from GDB's lists.  If the
3515      INSERTED flag is true, GDB will try to lift the breakpoints by
3516      writing the breakpoints' "shadow contents" back into memory.  The
3517      "shadow contents" are NOT valid after an exec, so GDB should not
3518      do that.  Instead, the target is responsible from marking
3519      breakpoints out as soon as it detects an exec.  We don't do that
3520      here instead, because there may be other attempts to delete
3521      breakpoints after detecting an exec and before reaching here.  */
3522   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3523     if (bploc->pspace == current_program_space)
3524       gdb_assert (!bploc->inserted);
3525
3526   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3527   {
3528     if (b->pspace != current_program_space)
3529       continue;
3530
3531     /* Solib breakpoints must be explicitly reset after an exec().  */
3532     if (b->type == bp_shlib_event)
3533       {
3534         delete_breakpoint (b);
3535         continue;
3536       }
3537
3538     /* JIT breakpoints must be explicitly reset after an exec().  */
3539     if (b->type == bp_jit_event)
3540       {
3541         delete_breakpoint (b);
3542         continue;
3543       }
3544
3545     /* Thread event breakpoints must be set anew after an exec(),
3546        as must overlay event and longjmp master breakpoints.  */
3547     if (b->type == bp_thread_event || b->type == bp_overlay_event
3548         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3549         || b->type == bp_exception_master)
3550       {
3551         delete_breakpoint (b);
3552         continue;
3553       }
3554
3555     /* Step-resume breakpoints are meaningless after an exec().  */
3556     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3557       {
3558         delete_breakpoint (b);
3559         continue;
3560       }
3561
3562     /* Just like single-step breakpoints.  */
3563     if (b->type == bp_single_step)
3564       {
3565         delete_breakpoint (b);
3566         continue;
3567       }
3568
3569     /* Longjmp and longjmp-resume breakpoints are also meaningless
3570        after an exec.  */
3571     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3572         || b->type == bp_longjmp_call_dummy
3573         || b->type == bp_exception || b->type == bp_exception_resume)
3574       {
3575         delete_breakpoint (b);
3576         continue;
3577       }
3578
3579     if (b->type == bp_catchpoint)
3580       {
3581         /* For now, none of the bp_catchpoint breakpoints need to
3582            do anything at this point.  In the future, if some of
3583            the catchpoints need to something, we will need to add
3584            a new method, and call this method from here.  */
3585         continue;
3586       }
3587
3588     /* bp_finish is a special case.  The only way we ought to be able
3589        to see one of these when an exec() has happened, is if the user
3590        caught a vfork, and then said "finish".  Ordinarily a finish just
3591        carries them to the call-site of the current callee, by setting
3592        a temporary bp there and resuming.  But in this case, the finish
3593        will carry them entirely through the vfork & exec.
3594
3595        We don't want to allow a bp_finish to remain inserted now.  But
3596        we can't safely delete it, 'cause finish_command has a handle to
3597        the bp on a bpstat, and will later want to delete it.  There's a
3598        chance (and I've seen it happen) that if we delete the bp_finish
3599        here, that its storage will get reused by the time finish_command
3600        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3601        We really must allow finish_command to delete a bp_finish.
3602
3603        In the absence of a general solution for the "how do we know
3604        it's safe to delete something others may have handles to?"
3605        problem, what we'll do here is just uninsert the bp_finish, and
3606        let finish_command delete it.
3607
3608        (We know the bp_finish is "doomed" in the sense that it's
3609        momentary, and will be deleted as soon as finish_command sees
3610        the inferior stopped.  So it doesn't matter that the bp's
3611        address is probably bogus in the new a.out, unlike e.g., the
3612        solib breakpoints.)  */
3613
3614     if (b->type == bp_finish)
3615       {
3616         continue;
3617       }
3618
3619     /* Without a symbolic address, we have little hope of the
3620        pre-exec() address meaning the same thing in the post-exec()
3621        a.out.  */
3622     if (breakpoint_event_location_empty_p (b))
3623       {
3624         delete_breakpoint (b);
3625         continue;
3626       }
3627   }
3628 }
3629
3630 int
3631 detach_breakpoints (ptid_t ptid)
3632 {
3633   struct bp_location *bl, **blp_tmp;
3634   int val = 0;
3635   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3636   struct inferior *inf = current_inferior ();
3637
3638   if (ptid.pid () == inferior_ptid.pid ())
3639     error (_("Cannot detach breakpoints of inferior_ptid"));
3640
3641   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3642   inferior_ptid = ptid;
3643   ALL_BP_LOCATIONS (bl, blp_tmp)
3644   {
3645     if (bl->pspace != inf->pspace)
3646       continue;
3647
3648     /* This function must physically remove breakpoints locations
3649        from the specified ptid, without modifying the breakpoint
3650        package's state.  Locations of type bp_loc_other are only
3651        maintained at GDB side.  So, there is no need to remove
3652        these bp_loc_other locations.  Moreover, removing these
3653        would modify the breakpoint package's state.  */
3654     if (bl->loc_type == bp_loc_other)
3655       continue;
3656
3657     if (bl->inserted)
3658       val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3659   }
3660
3661   return val;
3662 }
3663
3664 /* Remove the breakpoint location BL from the current address space.
3665    Note that this is used to detach breakpoints from a child fork.
3666    When we get here, the child isn't in the inferior list, and neither
3667    do we have objects to represent its address space --- we should
3668    *not* look at bl->pspace->aspace here.  */
3669
3670 static int
3671 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3672 {
3673   int val;
3674
3675   /* BL is never in moribund_locations by our callers.  */
3676   gdb_assert (bl->owner != NULL);
3677
3678   /* The type of none suggests that owner is actually deleted.
3679      This should not ever happen.  */
3680   gdb_assert (bl->owner->type != bp_none);
3681
3682   if (bl->loc_type == bp_loc_software_breakpoint
3683       || bl->loc_type == bp_loc_hardware_breakpoint)
3684     {
3685       /* "Normal" instruction breakpoint: either the standard
3686          trap-instruction bp (bp_breakpoint), or a
3687          bp_hardware_breakpoint.  */
3688
3689       /* First check to see if we have to handle an overlay.  */
3690       if (overlay_debugging == ovly_off
3691           || bl->section == NULL
3692           || !(section_is_overlay (bl->section)))
3693         {
3694           /* No overlay handling: just remove the breakpoint.  */
3695
3696           /* If we're trying to uninsert a memory breakpoint that we
3697              know is set in a dynamic object that is marked
3698              shlib_disabled, then either the dynamic object was
3699              removed with "remove-symbol-file" or with
3700              "nosharedlibrary".  In the former case, we don't know
3701              whether another dynamic object might have loaded over the
3702              breakpoint's address -- the user might well let us know
3703              about it next with add-symbol-file (the whole point of
3704              add-symbol-file is letting the user manually maintain a
3705              list of dynamically loaded objects).  If we have the
3706              breakpoint's shadow memory, that is, this is a software
3707              breakpoint managed by GDB, check whether the breakpoint
3708              is still inserted in memory, to avoid overwriting wrong
3709              code with stale saved shadow contents.  Note that HW
3710              breakpoints don't have shadow memory, as they're
3711              implemented using a mechanism that is not dependent on
3712              being able to modify the target's memory, and as such
3713              they should always be removed.  */
3714           if (bl->shlib_disabled
3715               && bl->target_info.shadow_len != 0
3716               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3717             val = 0;
3718           else
3719             val = bl->owner->ops->remove_location (bl, reason);
3720         }
3721       else
3722         {
3723           /* This breakpoint is in an overlay section.
3724              Did we set a breakpoint at the LMA?  */
3725           if (!overlay_events_enabled)
3726               {
3727                 /* Yes -- overlay event support is not active, so we
3728                    should have set a breakpoint at the LMA.  Remove it.  
3729                 */
3730                 /* Ignore any failures: if the LMA is in ROM, we will
3731                    have already warned when we failed to insert it.  */
3732                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3733                   target_remove_hw_breakpoint (bl->gdbarch,
3734                                                &bl->overlay_target_info);
3735                 else
3736                   target_remove_breakpoint (bl->gdbarch,
3737                                             &bl->overlay_target_info,
3738                                             reason);
3739               }
3740           /* Did we set a breakpoint at the VMA? 
3741              If so, we will have marked the breakpoint 'inserted'.  */
3742           if (bl->inserted)
3743             {
3744               /* Yes -- remove it.  Previously we did not bother to
3745                  remove the breakpoint if the section had been
3746                  unmapped, but let's not rely on that being safe.  We
3747                  don't know what the overlay manager might do.  */
3748
3749               /* However, we should remove *software* breakpoints only
3750                  if the section is still mapped, or else we overwrite
3751                  wrong code with the saved shadow contents.  */
3752               if (bl->loc_type == bp_loc_hardware_breakpoint
3753                   || section_is_mapped (bl->section))
3754                 val = bl->owner->ops->remove_location (bl, reason);
3755               else
3756                 val = 0;
3757             }
3758           else
3759             {
3760               /* No -- not inserted, so no need to remove.  No error.  */
3761               val = 0;
3762             }
3763         }
3764
3765       /* In some cases, we might not be able to remove a breakpoint in
3766          a shared library that has already been removed, but we have
3767          not yet processed the shlib unload event.  Similarly for an
3768          unloaded add-symbol-file object - the user might not yet have
3769          had the chance to remove-symbol-file it.  shlib_disabled will
3770          be set if the library/object has already been removed, but
3771          the breakpoint hasn't been uninserted yet, e.g., after
3772          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3773          always-inserted mode.  */
3774       if (val
3775           && (bl->loc_type == bp_loc_software_breakpoint
3776               && (bl->shlib_disabled
3777                   || solib_name_from_address (bl->pspace, bl->address)
3778                   || shared_objfile_contains_address_p (bl->pspace,
3779                                                         bl->address))))
3780         val = 0;
3781
3782       if (val)
3783         return val;
3784       bl->inserted = (reason == DETACH_BREAKPOINT);
3785     }
3786   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3787     {
3788       gdb_assert (bl->owner->ops != NULL
3789                   && bl->owner->ops->remove_location != NULL);
3790
3791       bl->inserted = (reason == DETACH_BREAKPOINT);
3792       bl->owner->ops->remove_location (bl, reason);
3793
3794       /* Failure to remove any of the hardware watchpoints comes here.  */
3795       if (reason == REMOVE_BREAKPOINT && bl->inserted)
3796         warning (_("Could not remove hardware watchpoint %d."),
3797                  bl->owner->number);
3798     }
3799   else if (bl->owner->type == bp_catchpoint
3800            && breakpoint_enabled (bl->owner)
3801            && !bl->duplicate)
3802     {
3803       gdb_assert (bl->owner->ops != NULL
3804                   && bl->owner->ops->remove_location != NULL);
3805
3806       val = bl->owner->ops->remove_location (bl, reason);
3807       if (val)
3808         return val;
3809
3810       bl->inserted = (reason == DETACH_BREAKPOINT);
3811     }
3812
3813   return 0;
3814 }
3815
3816 static int
3817 remove_breakpoint (struct bp_location *bl)
3818 {
3819   /* BL is never in moribund_locations by our callers.  */
3820   gdb_assert (bl->owner != NULL);
3821
3822   /* The type of none suggests that owner is actually deleted.
3823      This should not ever happen.  */
3824   gdb_assert (bl->owner->type != bp_none);
3825
3826   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3827
3828   switch_to_program_space_and_thread (bl->pspace);
3829
3830   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
3831 }
3832
3833 /* Clear the "inserted" flag in all breakpoints.  */
3834
3835 void
3836 mark_breakpoints_out (void)
3837 {
3838   struct bp_location *bl, **blp_tmp;
3839
3840   ALL_BP_LOCATIONS (bl, blp_tmp)
3841     if (bl->pspace == current_program_space)
3842       bl->inserted = 0;
3843 }
3844
3845 /* Clear the "inserted" flag in all breakpoints and delete any
3846    breakpoints which should go away between runs of the program.
3847
3848    Plus other such housekeeping that has to be done for breakpoints
3849    between runs.
3850
3851    Note: this function gets called at the end of a run (by
3852    generic_mourn_inferior) and when a run begins (by
3853    init_wait_for_inferior).  */
3854
3855
3856
3857 void
3858 breakpoint_init_inferior (enum inf_context context)
3859 {
3860   struct breakpoint *b, *b_tmp;
3861   struct program_space *pspace = current_program_space;
3862
3863   /* If breakpoint locations are shared across processes, then there's
3864      nothing to do.  */
3865   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3866     return;
3867
3868   mark_breakpoints_out ();
3869
3870   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3871   {
3872     if (b->loc && b->loc->pspace != pspace)
3873       continue;
3874
3875     switch (b->type)
3876       {
3877       case bp_call_dummy:
3878       case bp_longjmp_call_dummy:
3879
3880         /* If the call dummy breakpoint is at the entry point it will
3881            cause problems when the inferior is rerun, so we better get
3882            rid of it.  */
3883
3884       case bp_watchpoint_scope:
3885
3886         /* Also get rid of scope breakpoints.  */
3887
3888       case bp_shlib_event:
3889
3890         /* Also remove solib event breakpoints.  Their addresses may
3891            have changed since the last time we ran the program.
3892            Actually we may now be debugging against different target;
3893            and so the solib backend that installed this breakpoint may
3894            not be used in by the target.  E.g.,
3895
3896            (gdb) file prog-linux
3897            (gdb) run               # native linux target
3898            ...
3899            (gdb) kill
3900            (gdb) file prog-win.exe
3901            (gdb) tar rem :9999     # remote Windows gdbserver.
3902         */
3903
3904       case bp_step_resume:
3905
3906         /* Also remove step-resume breakpoints.  */
3907
3908       case bp_single_step:
3909
3910         /* Also remove single-step breakpoints.  */
3911
3912         delete_breakpoint (b);
3913         break;
3914
3915       case bp_watchpoint:
3916       case bp_hardware_watchpoint:
3917       case bp_read_watchpoint:
3918       case bp_access_watchpoint:
3919         {
3920           struct watchpoint *w = (struct watchpoint *) b;
3921
3922           /* Likewise for watchpoints on local expressions.  */
3923           if (w->exp_valid_block != NULL)
3924             delete_breakpoint (b);
3925           else
3926             {
3927               /* Get rid of existing locations, which are no longer
3928                  valid.  New ones will be created in
3929                  update_watchpoint, when the inferior is restarted.
3930                  The next update_global_location_list call will
3931                  garbage collect them.  */
3932               b->loc = NULL;
3933
3934               if (context == inf_starting)
3935                 {
3936                   /* Reset val field to force reread of starting value in
3937                      insert_breakpoints.  */
3938                   w->val.reset (nullptr);
3939                   w->val_valid = 0;
3940                 }
3941             }
3942         }
3943         break;
3944       default:
3945         break;
3946       }
3947   }
3948
3949   /* Get rid of the moribund locations.  */
3950   for (bp_location *bl : moribund_locations)
3951     decref_bp_location (&bl);
3952   moribund_locations.clear ();
3953 }
3954
3955 /* These functions concern about actual breakpoints inserted in the
3956    target --- to e.g. check if we need to do decr_pc adjustment or if
3957    we need to hop over the bkpt --- so we check for address space
3958    match, not program space.  */
3959
3960 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3961    exists at PC.  It returns ordinary_breakpoint_here if it's an
3962    ordinary breakpoint, or permanent_breakpoint_here if it's a
3963    permanent breakpoint.
3964    - When continuing from a location with an ordinary breakpoint, we
3965      actually single step once before calling insert_breakpoints.
3966    - When continuing from a location with a permanent breakpoint, we
3967      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3968      the target, to advance the PC past the breakpoint.  */
3969
3970 enum breakpoint_here
3971 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
3972 {
3973   struct bp_location *bl, **blp_tmp;
3974   int any_breakpoint_here = 0;
3975
3976   ALL_BP_LOCATIONS (bl, blp_tmp)
3977     {
3978       if (bl->loc_type != bp_loc_software_breakpoint
3979           && bl->loc_type != bp_loc_hardware_breakpoint)
3980         continue;
3981
3982       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3983       if ((breakpoint_enabled (bl->owner)
3984            || bl->permanent)
3985           && breakpoint_location_address_match (bl, aspace, pc))
3986         {
3987           if (overlay_debugging 
3988               && section_is_overlay (bl->section)
3989               && !section_is_mapped (bl->section))
3990             continue;           /* unmapped overlay -- can't be a match */
3991           else if (bl->permanent)
3992             return permanent_breakpoint_here;
3993           else
3994             any_breakpoint_here = 1;
3995         }
3996     }
3997
3998   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
3999 }
4000
4001 /* See breakpoint.h.  */
4002
4003 int
4004 breakpoint_in_range_p (const address_space *aspace,
4005                        CORE_ADDR addr, ULONGEST len)
4006 {
4007   struct bp_location *bl, **blp_tmp;
4008
4009   ALL_BP_LOCATIONS (bl, blp_tmp)
4010     {
4011       if (bl->loc_type != bp_loc_software_breakpoint
4012           && bl->loc_type != bp_loc_hardware_breakpoint)
4013         continue;
4014
4015       if ((breakpoint_enabled (bl->owner)
4016            || bl->permanent)
4017           && breakpoint_location_address_range_overlap (bl, aspace,
4018                                                         addr, len))
4019         {
4020           if (overlay_debugging
4021               && section_is_overlay (bl->section)
4022               && !section_is_mapped (bl->section))
4023             {
4024               /* Unmapped overlay -- can't be a match.  */
4025               continue;
4026             }
4027
4028           return 1;
4029         }
4030     }
4031
4032   return 0;
4033 }
4034
4035 /* Return true if there's a moribund breakpoint at PC.  */
4036
4037 int
4038 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4039 {
4040   for (bp_location *loc : moribund_locations)
4041     if (breakpoint_location_address_match (loc, aspace, pc))
4042       return 1;
4043
4044   return 0;
4045 }
4046
4047 /* Returns non-zero iff BL is inserted at PC, in address space
4048    ASPACE.  */
4049
4050 static int
4051 bp_location_inserted_here_p (struct bp_location *bl,
4052                              const address_space *aspace, CORE_ADDR pc)
4053 {
4054   if (bl->inserted
4055       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4056                                    aspace, pc))
4057     {
4058       if (overlay_debugging
4059           && section_is_overlay (bl->section)
4060           && !section_is_mapped (bl->section))
4061         return 0;               /* unmapped overlay -- can't be a match */
4062       else
4063         return 1;
4064     }
4065   return 0;
4066 }
4067
4068 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4069
4070 int
4071 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4072 {
4073   struct bp_location **blp, **blp_tmp = NULL;
4074
4075   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4076     {
4077       struct bp_location *bl = *blp;
4078
4079       if (bl->loc_type != bp_loc_software_breakpoint
4080           && bl->loc_type != bp_loc_hardware_breakpoint)
4081         continue;
4082
4083       if (bp_location_inserted_here_p (bl, aspace, pc))
4084         return 1;
4085     }
4086   return 0;
4087 }
4088
4089 /* This function returns non-zero iff there is a software breakpoint
4090    inserted at PC.  */
4091
4092 int
4093 software_breakpoint_inserted_here_p (const address_space *aspace,
4094                                      CORE_ADDR pc)
4095 {
4096   struct bp_location **blp, **blp_tmp = NULL;
4097
4098   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4099     {
4100       struct bp_location *bl = *blp;
4101
4102       if (bl->loc_type != bp_loc_software_breakpoint)
4103         continue;
4104
4105       if (bp_location_inserted_here_p (bl, aspace, pc))
4106         return 1;
4107     }
4108
4109   return 0;
4110 }
4111
4112 /* See breakpoint.h.  */
4113
4114 int
4115 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4116                                      CORE_ADDR pc)
4117 {
4118   struct bp_location **blp, **blp_tmp = NULL;
4119
4120   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4121     {
4122       struct bp_location *bl = *blp;
4123
4124       if (bl->loc_type != bp_loc_hardware_breakpoint)
4125         continue;
4126
4127       if (bp_location_inserted_here_p (bl, aspace, pc))
4128         return 1;
4129     }
4130
4131   return 0;
4132 }
4133
4134 int
4135 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4136                                        CORE_ADDR addr, ULONGEST len)
4137 {
4138   struct breakpoint *bpt;
4139
4140   ALL_BREAKPOINTS (bpt)
4141     {
4142       struct bp_location *loc;
4143
4144       if (bpt->type != bp_hardware_watchpoint
4145           && bpt->type != bp_access_watchpoint)
4146         continue;
4147
4148       if (!breakpoint_enabled (bpt))
4149         continue;
4150
4151       for (loc = bpt->loc; loc; loc = loc->next)
4152         if (loc->pspace->aspace == aspace && loc->inserted)
4153           {
4154             CORE_ADDR l, h;
4155
4156             /* Check for intersection.  */
4157             l = std::max<CORE_ADDR> (loc->address, addr);
4158             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4159             if (l < h)
4160               return 1;
4161           }
4162     }
4163   return 0;
4164 }
4165 \f
4166
4167 /* bpstat stuff.  External routines' interfaces are documented
4168    in breakpoint.h.  */
4169
4170 int
4171 is_catchpoint (struct breakpoint *ep)
4172 {
4173   return (ep->type == bp_catchpoint);
4174 }
4175
4176 /* Frees any storage that is part of a bpstat.  Does not walk the
4177    'next' chain.  */
4178
4179 bpstats::~bpstats ()
4180 {
4181   if (bp_location_at != NULL)
4182     decref_bp_location (&bp_location_at);
4183 }
4184
4185 /* Clear a bpstat so that it says we are not at any breakpoint.
4186    Also free any storage that is part of a bpstat.  */
4187
4188 void
4189 bpstat_clear (bpstat *bsp)
4190 {
4191   bpstat p;
4192   bpstat q;
4193
4194   if (bsp == 0)
4195     return;
4196   p = *bsp;
4197   while (p != NULL)
4198     {
4199       q = p->next;
4200       delete p;
4201       p = q;
4202     }
4203   *bsp = NULL;
4204 }
4205
4206 bpstats::bpstats (const bpstats &other)
4207   : next (NULL),
4208     bp_location_at (other.bp_location_at),
4209     breakpoint_at (other.breakpoint_at),
4210     commands (other.commands),
4211     print (other.print),
4212     stop (other.stop),
4213     print_it (other.print_it)
4214 {
4215   if (other.old_val != NULL)
4216     old_val = release_value (value_copy (other.old_val.get ()));
4217   incref_bp_location (bp_location_at);
4218 }
4219
4220 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4221    is part of the bpstat is copied as well.  */
4222
4223 bpstat
4224 bpstat_copy (bpstat bs)
4225 {
4226   bpstat p = NULL;
4227   bpstat tmp;
4228   bpstat retval = NULL;
4229
4230   if (bs == NULL)
4231     return bs;
4232
4233   for (; bs != NULL; bs = bs->next)
4234     {
4235       tmp = new bpstats (*bs);
4236
4237       if (p == NULL)
4238         /* This is the first thing in the chain.  */
4239         retval = tmp;
4240       else
4241         p->next = tmp;
4242       p = tmp;
4243     }
4244   p->next = NULL;
4245   return retval;
4246 }
4247
4248 /* Find the bpstat associated with this breakpoint.  */
4249
4250 bpstat
4251 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4252 {
4253   if (bsp == NULL)
4254     return NULL;
4255
4256   for (; bsp != NULL; bsp = bsp->next)
4257     {
4258       if (bsp->breakpoint_at == breakpoint)
4259         return bsp;
4260     }
4261   return NULL;
4262 }
4263
4264 /* See breakpoint.h.  */
4265
4266 int
4267 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4268 {
4269   for (; bsp != NULL; bsp = bsp->next)
4270     {
4271       if (bsp->breakpoint_at == NULL)
4272         {
4273           /* A moribund location can never explain a signal other than
4274              GDB_SIGNAL_TRAP.  */
4275           if (sig == GDB_SIGNAL_TRAP)
4276             return 1;
4277         }
4278       else
4279         {
4280           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4281                                                         sig))
4282             return 1;
4283         }
4284     }
4285
4286   return 0;
4287 }
4288
4289 /* Put in *NUM the breakpoint number of the first breakpoint we are
4290    stopped at.  *BSP upon return is a bpstat which points to the
4291    remaining breakpoints stopped at (but which is not guaranteed to be
4292    good for anything but further calls to bpstat_num).
4293
4294    Return 0 if passed a bpstat which does not indicate any breakpoints.
4295    Return -1 if stopped at a breakpoint that has been deleted since
4296    we set it.
4297    Return 1 otherwise.  */
4298
4299 int
4300 bpstat_num (bpstat *bsp, int *num)
4301 {
4302   struct breakpoint *b;
4303
4304   if ((*bsp) == NULL)
4305     return 0;                   /* No more breakpoint values */
4306
4307   /* We assume we'll never have several bpstats that correspond to a
4308      single breakpoint -- otherwise, this function might return the
4309      same number more than once and this will look ugly.  */
4310   b = (*bsp)->breakpoint_at;
4311   *bsp = (*bsp)->next;
4312   if (b == NULL)
4313     return -1;                  /* breakpoint that's been deleted since */
4314
4315   *num = b->number;             /* We have its number */
4316   return 1;
4317 }
4318
4319 /* See breakpoint.h.  */
4320
4321 void
4322 bpstat_clear_actions (void)
4323 {
4324   bpstat bs;
4325
4326   if (inferior_ptid == null_ptid)
4327     return;
4328
4329   thread_info *tp = inferior_thread ();
4330   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4331     {
4332       bs->commands = NULL;
4333       bs->old_val.reset (nullptr);
4334     }
4335 }
4336
4337 /* Called when a command is about to proceed the inferior.  */
4338
4339 static void
4340 breakpoint_about_to_proceed (void)
4341 {
4342   if (inferior_ptid != null_ptid)
4343     {
4344       struct thread_info *tp = inferior_thread ();
4345
4346       /* Allow inferior function calls in breakpoint commands to not
4347          interrupt the command list.  When the call finishes
4348          successfully, the inferior will be standing at the same
4349          breakpoint as if nothing happened.  */
4350       if (tp->control.in_infcall)
4351         return;
4352     }
4353
4354   breakpoint_proceeded = 1;
4355 }
4356
4357 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4358    or its equivalent.  */
4359
4360 static int
4361 command_line_is_silent (struct command_line *cmd)
4362 {
4363   return cmd && (strcmp ("silent", cmd->line) == 0);
4364 }
4365
4366 /* Execute all the commands associated with all the breakpoints at
4367    this location.  Any of these commands could cause the process to
4368    proceed beyond this point, etc.  We look out for such changes by
4369    checking the global "breakpoint_proceeded" after each command.
4370
4371    Returns true if a breakpoint command resumed the inferior.  In that
4372    case, it is the caller's responsibility to recall it again with the
4373    bpstat of the current thread.  */
4374
4375 static int
4376 bpstat_do_actions_1 (bpstat *bsp)
4377 {
4378   bpstat bs;
4379   int again = 0;
4380
4381   /* Avoid endless recursion if a `source' command is contained
4382      in bs->commands.  */
4383   if (executing_breakpoint_commands)
4384     return 0;
4385
4386   scoped_restore save_executing
4387     = make_scoped_restore (&executing_breakpoint_commands, 1);
4388
4389   scoped_restore preventer = prevent_dont_repeat ();
4390
4391   /* This pointer will iterate over the list of bpstat's.  */
4392   bs = *bsp;
4393
4394   breakpoint_proceeded = 0;
4395   for (; bs != NULL; bs = bs->next)
4396     {
4397       struct command_line *cmd = NULL;
4398
4399       /* Take ownership of the BSP's command tree, if it has one.
4400
4401          The command tree could legitimately contain commands like
4402          'step' and 'next', which call clear_proceed_status, which
4403          frees stop_bpstat's command tree.  To make sure this doesn't
4404          free the tree we're executing out from under us, we need to
4405          take ownership of the tree ourselves.  Since a given bpstat's
4406          commands are only executed once, we don't need to copy it; we
4407          can clear the pointer in the bpstat, and make sure we free
4408          the tree when we're done.  */
4409       counted_command_line ccmd = bs->commands;
4410       bs->commands = NULL;
4411       if (ccmd != NULL)
4412         cmd = ccmd.get ();
4413       if (command_line_is_silent (cmd))
4414         {
4415           /* The action has been already done by bpstat_stop_status.  */
4416           cmd = cmd->next;
4417         }
4418
4419       while (cmd != NULL)
4420         {
4421           execute_control_command (cmd);
4422
4423           if (breakpoint_proceeded)
4424             break;
4425           else
4426             cmd = cmd->next;
4427         }
4428
4429       if (breakpoint_proceeded)
4430         {
4431           if (current_ui->async)
4432             /* If we are in async mode, then the target might be still
4433                running, not stopped at any breakpoint, so nothing for
4434                us to do here -- just return to the event loop.  */
4435             ;
4436           else
4437             /* In sync mode, when execute_control_command returns
4438                we're already standing on the next breakpoint.
4439                Breakpoint commands for that stop were not run, since
4440                execute_command does not run breakpoint commands --
4441                only command_line_handler does, but that one is not
4442                involved in execution of breakpoint commands.  So, we
4443                can now execute breakpoint commands.  It should be
4444                noted that making execute_command do bpstat actions is
4445                not an option -- in this case we'll have recursive
4446                invocation of bpstat for each breakpoint with a
4447                command, and can easily blow up GDB stack.  Instead, we
4448                return true, which will trigger the caller to recall us
4449                with the new stop_bpstat.  */
4450             again = 1;
4451           break;
4452         }
4453     }
4454   return again;
4455 }
4456
4457 /* Helper for bpstat_do_actions.  Get the current thread, if there's
4458    one, is alive and has execution.  Return NULL otherwise.  */
4459
4460 static thread_info *
4461 get_bpstat_thread ()
4462 {
4463   if (inferior_ptid == null_ptid || !target_has_execution)
4464     return NULL;
4465
4466   thread_info *tp = inferior_thread ();
4467   if (tp->state == THREAD_EXITED || tp->executing)
4468     return NULL;
4469   return tp;
4470 }
4471
4472 void
4473 bpstat_do_actions (void)
4474 {
4475   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4476   thread_info *tp;
4477
4478   /* Do any commands attached to breakpoint we are stopped at.  */
4479   while ((tp = get_bpstat_thread ()) != NULL)
4480     {
4481       /* Since in sync mode, bpstat_do_actions may resume the
4482          inferior, and only return when it is stopped at the next
4483          breakpoint, we keep doing breakpoint actions until it returns
4484          false to indicate the inferior was not resumed.  */
4485       if (!bpstat_do_actions_1 (&tp->control.stop_bpstat))
4486         break;
4487     }
4488
4489   discard_cleanups (cleanup_if_error);
4490 }
4491
4492 /* Print out the (old or new) value associated with a watchpoint.  */
4493
4494 static void
4495 watchpoint_value_print (struct value *val, struct ui_file *stream)
4496 {
4497   if (val == NULL)
4498     fprintf_unfiltered (stream, _("<unreadable>"));
4499   else
4500     {
4501       struct value_print_options opts;
4502       get_user_print_options (&opts);
4503       value_print (val, stream, &opts);
4504     }
4505 }
4506
4507 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4508    debugging multiple threads.  */
4509
4510 void
4511 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4512 {
4513   if (uiout->is_mi_like_p ())
4514     return;
4515
4516   uiout->text ("\n");
4517
4518   if (show_thread_that_caused_stop ())
4519     {
4520       const char *name;
4521       struct thread_info *thr = inferior_thread ();
4522
4523       uiout->text ("Thread ");
4524       uiout->field_fmt ("thread-id", "%s", print_thread_id (thr));
4525
4526       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4527       if (name != NULL)
4528         {
4529           uiout->text (" \"");
4530           uiout->field_fmt ("name", "%s", name);
4531           uiout->text ("\"");
4532         }
4533
4534       uiout->text (" hit ");
4535     }
4536 }
4537
4538 /* Generic routine for printing messages indicating why we
4539    stopped.  The behavior of this function depends on the value
4540    'print_it' in the bpstat structure.  Under some circumstances we
4541    may decide not to print anything here and delegate the task to
4542    normal_stop().  */
4543
4544 static enum print_stop_action
4545 print_bp_stop_message (bpstat bs)
4546 {
4547   switch (bs->print_it)
4548     {
4549     case print_it_noop:
4550       /* Nothing should be printed for this bpstat entry.  */
4551       return PRINT_UNKNOWN;
4552       break;
4553
4554     case print_it_done:
4555       /* We still want to print the frame, but we already printed the
4556          relevant messages.  */
4557       return PRINT_SRC_AND_LOC;
4558       break;
4559
4560     case print_it_normal:
4561       {
4562         struct breakpoint *b = bs->breakpoint_at;
4563
4564         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4565            which has since been deleted.  */
4566         if (b == NULL)
4567           return PRINT_UNKNOWN;
4568
4569         /* Normal case.  Call the breakpoint's print_it method.  */
4570         return b->ops->print_it (bs);
4571       }
4572       break;
4573
4574     default:
4575       internal_error (__FILE__, __LINE__,
4576                       _("print_bp_stop_message: unrecognized enum value"));
4577       break;
4578     }
4579 }
4580
4581 /* A helper function that prints a shared library stopped event.  */
4582
4583 static void
4584 print_solib_event (int is_catchpoint)
4585 {
4586   bool any_deleted = !current_program_space->deleted_solibs.empty ();
4587   bool any_added = !current_program_space->added_solibs.empty ();
4588
4589   if (!is_catchpoint)
4590     {
4591       if (any_added || any_deleted)
4592         current_uiout->text (_("Stopped due to shared library event:\n"));
4593       else
4594         current_uiout->text (_("Stopped due to shared library event (no "
4595                                "libraries added or removed)\n"));
4596     }
4597
4598   if (current_uiout->is_mi_like_p ())
4599     current_uiout->field_string ("reason",
4600                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4601
4602   if (any_deleted)
4603     {
4604       current_uiout->text (_("  Inferior unloaded "));
4605       ui_out_emit_list list_emitter (current_uiout, "removed");
4606       for (int ix = 0; ix < current_program_space->deleted_solibs.size (); ix++)
4607         {
4608           const std::string &name = current_program_space->deleted_solibs[ix];
4609
4610           if (ix > 0)
4611             current_uiout->text ("    ");
4612           current_uiout->field_string ("library", name);
4613           current_uiout->text ("\n");
4614         }
4615     }
4616
4617   if (any_added)
4618     {
4619       current_uiout->text (_("  Inferior loaded "));
4620       ui_out_emit_list list_emitter (current_uiout, "added");
4621       bool first = true;
4622       for (so_list *iter : current_program_space->added_solibs)
4623         {
4624           if (!first)
4625             current_uiout->text ("    ");
4626           first = false;
4627           current_uiout->field_string ("library", iter->so_name);
4628           current_uiout->text ("\n");
4629         }
4630     }
4631 }
4632
4633 /* Print a message indicating what happened.  This is called from
4634    normal_stop().  The input to this routine is the head of the bpstat
4635    list - a list of the eventpoints that caused this stop.  KIND is
4636    the target_waitkind for the stopping event.  This
4637    routine calls the generic print routine for printing a message
4638    about reasons for stopping.  This will print (for example) the
4639    "Breakpoint n," part of the output.  The return value of this
4640    routine is one of:
4641
4642    PRINT_UNKNOWN: Means we printed nothing.
4643    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4644    code to print the location.  An example is 
4645    "Breakpoint 1, " which should be followed by
4646    the location.
4647    PRINT_SRC_ONLY: Means we printed something, but there is no need
4648    to also print the location part of the message.
4649    An example is the catch/throw messages, which
4650    don't require a location appended to the end.
4651    PRINT_NOTHING: We have done some printing and we don't need any 
4652    further info to be printed.  */
4653
4654 enum print_stop_action
4655 bpstat_print (bpstat bs, int kind)
4656 {
4657   enum print_stop_action val;
4658
4659   /* Maybe another breakpoint in the chain caused us to stop.
4660      (Currently all watchpoints go on the bpstat whether hit or not.
4661      That probably could (should) be changed, provided care is taken
4662      with respect to bpstat_explains_signal).  */
4663   for (; bs; bs = bs->next)
4664     {
4665       val = print_bp_stop_message (bs);
4666       if (val == PRINT_SRC_ONLY 
4667           || val == PRINT_SRC_AND_LOC 
4668           || val == PRINT_NOTHING)
4669         return val;
4670     }
4671
4672   /* If we had hit a shared library event breakpoint,
4673      print_bp_stop_message would print out this message.  If we hit an
4674      OS-level shared library event, do the same thing.  */
4675   if (kind == TARGET_WAITKIND_LOADED)
4676     {
4677       print_solib_event (0);
4678       return PRINT_NOTHING;
4679     }
4680
4681   /* We reached the end of the chain, or we got a null BS to start
4682      with and nothing was printed.  */
4683   return PRINT_UNKNOWN;
4684 }
4685
4686 /* Evaluate the boolean expression EXP and return the result.  */
4687
4688 static bool
4689 breakpoint_cond_eval (expression *exp)
4690 {
4691   struct value *mark = value_mark ();
4692   bool res = value_true (evaluate_expression (exp));
4693
4694   value_free_to_mark (mark);
4695   return res;
4696 }
4697
4698 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4699
4700 bpstats::bpstats (struct bp_location *bl, bpstat **bs_link_pointer)
4701   : next (NULL),
4702     bp_location_at (bl),
4703     breakpoint_at (bl->owner),
4704     commands (NULL),
4705     print (0),
4706     stop (0),
4707     print_it (print_it_normal)
4708 {
4709   incref_bp_location (bl);
4710   **bs_link_pointer = this;
4711   *bs_link_pointer = &next;
4712 }
4713
4714 bpstats::bpstats ()
4715   : next (NULL),
4716     bp_location_at (NULL),
4717     breakpoint_at (NULL),
4718     commands (NULL),
4719     print (0),
4720     stop (0),
4721     print_it (print_it_normal)
4722 {
4723 }
4724 \f
4725 /* The target has stopped with waitstatus WS.  Check if any hardware
4726    watchpoints have triggered, according to the target.  */
4727
4728 int
4729 watchpoints_triggered (struct target_waitstatus *ws)
4730 {
4731   bool stopped_by_watchpoint = target_stopped_by_watchpoint ();
4732   CORE_ADDR addr;
4733   struct breakpoint *b;
4734
4735   if (!stopped_by_watchpoint)
4736     {
4737       /* We were not stopped by a watchpoint.  Mark all watchpoints
4738          as not triggered.  */
4739       ALL_BREAKPOINTS (b)
4740         if (is_hardware_watchpoint (b))
4741           {
4742             struct watchpoint *w = (struct watchpoint *) b;
4743
4744             w->watchpoint_triggered = watch_triggered_no;
4745           }
4746
4747       return 0;
4748     }
4749
4750   if (!target_stopped_data_address (current_top_target (), &addr))
4751     {
4752       /* We were stopped by a watchpoint, but we don't know where.
4753          Mark all watchpoints as unknown.  */
4754       ALL_BREAKPOINTS (b)
4755         if (is_hardware_watchpoint (b))
4756           {
4757             struct watchpoint *w = (struct watchpoint *) b;
4758
4759             w->watchpoint_triggered = watch_triggered_unknown;
4760           }
4761
4762       return 1;
4763     }
4764
4765   /* The target could report the data address.  Mark watchpoints
4766      affected by this data address as triggered, and all others as not
4767      triggered.  */
4768
4769   ALL_BREAKPOINTS (b)
4770     if (is_hardware_watchpoint (b))
4771       {
4772         struct watchpoint *w = (struct watchpoint *) b;
4773         struct bp_location *loc;
4774
4775         w->watchpoint_triggered = watch_triggered_no;
4776         for (loc = b->loc; loc; loc = loc->next)
4777           {
4778             if (is_masked_watchpoint (b))
4779               {
4780                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4781                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4782
4783                 if (newaddr == start)
4784                   {
4785                     w->watchpoint_triggered = watch_triggered_yes;
4786                     break;
4787                   }
4788               }
4789             /* Exact match not required.  Within range is sufficient.  */
4790             else if (target_watchpoint_addr_within_range (current_top_target (),
4791                                                          addr, loc->address,
4792                                                          loc->length))
4793               {
4794                 w->watchpoint_triggered = watch_triggered_yes;
4795                 break;
4796               }
4797           }
4798       }
4799
4800   return 1;
4801 }
4802
4803 /* Possible return values for watchpoint_check.  */
4804 enum wp_check_result
4805   {
4806     /* The watchpoint has been deleted.  */
4807     WP_DELETED = 1,
4808
4809     /* The value has changed.  */
4810     WP_VALUE_CHANGED = 2,
4811
4812     /* The value has not changed.  */
4813     WP_VALUE_NOT_CHANGED = 3,
4814
4815     /* Ignore this watchpoint, no matter if the value changed or not.  */
4816     WP_IGNORE = 4,
4817   };
4818
4819 #define BP_TEMPFLAG 1
4820 #define BP_HARDWAREFLAG 2
4821
4822 /* Evaluate watchpoint condition expression and check if its value
4823    changed.  */
4824
4825 static wp_check_result
4826 watchpoint_check (bpstat bs)
4827 {
4828   struct watchpoint *b;
4829   struct frame_info *fr;
4830   int within_current_scope;
4831
4832   /* BS is built from an existing struct breakpoint.  */
4833   gdb_assert (bs->breakpoint_at != NULL);
4834   b = (struct watchpoint *) bs->breakpoint_at;
4835
4836   /* If this is a local watchpoint, we only want to check if the
4837      watchpoint frame is in scope if the current thread is the thread
4838      that was used to create the watchpoint.  */
4839   if (!watchpoint_in_thread_scope (b))
4840     return WP_IGNORE;
4841
4842   if (b->exp_valid_block == NULL)
4843     within_current_scope = 1;
4844   else
4845     {
4846       struct frame_info *frame = get_current_frame ();
4847       struct gdbarch *frame_arch = get_frame_arch (frame);
4848       CORE_ADDR frame_pc = get_frame_pc (frame);
4849
4850       /* stack_frame_destroyed_p() returns a non-zero value if we're
4851          still in the function but the stack frame has already been
4852          invalidated.  Since we can't rely on the values of local
4853          variables after the stack has been destroyed, we are treating
4854          the watchpoint in that state as `not changed' without further
4855          checking.  Don't mark watchpoints as changed if the current
4856          frame is in an epilogue - even if they are in some other
4857          frame, our view of the stack is likely to be wrong and
4858          frame_find_by_id could error out.  */
4859       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
4860         return WP_IGNORE;
4861
4862       fr = frame_find_by_id (b->watchpoint_frame);
4863       within_current_scope = (fr != NULL);
4864
4865       /* If we've gotten confused in the unwinder, we might have
4866          returned a frame that can't describe this variable.  */
4867       if (within_current_scope)
4868         {
4869           struct symbol *function;
4870
4871           function = get_frame_function (fr);
4872           if (function == NULL
4873               || !contained_in (b->exp_valid_block,
4874                                 SYMBOL_BLOCK_VALUE (function)))
4875             within_current_scope = 0;
4876         }
4877
4878       if (within_current_scope)
4879         /* If we end up stopping, the current frame will get selected
4880            in normal_stop.  So this call to select_frame won't affect
4881            the user.  */
4882         select_frame (fr);
4883     }
4884
4885   if (within_current_scope)
4886     {
4887       /* We use value_{,free_to_}mark because it could be a *long*
4888          time before we return to the command level and call
4889          free_all_values.  We can't call free_all_values because we
4890          might be in the middle of evaluating a function call.  */
4891
4892       int pc = 0;
4893       struct value *mark;
4894       struct value *new_val;
4895
4896       if (is_masked_watchpoint (b))
4897         /* Since we don't know the exact trigger address (from
4898            stopped_data_address), just tell the user we've triggered
4899            a mask watchpoint.  */
4900         return WP_VALUE_CHANGED;
4901
4902       mark = value_mark ();
4903       fetch_subexp_value (b->exp.get (), &pc, &new_val, NULL, NULL, 0);
4904
4905       if (b->val_bitsize != 0)
4906         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
4907
4908       /* We use value_equal_contents instead of value_equal because
4909          the latter coerces an array to a pointer, thus comparing just
4910          the address of the array instead of its contents.  This is
4911          not what we want.  */
4912       if ((b->val != NULL) != (new_val != NULL)
4913           || (b->val != NULL && !value_equal_contents (b->val.get (),
4914                                                        new_val)))
4915         {
4916           bs->old_val = b->val;
4917           b->val = release_value (new_val);
4918           b->val_valid = 1;
4919           if (new_val != NULL)
4920             value_free_to_mark (mark);
4921           return WP_VALUE_CHANGED;
4922         }
4923       else
4924         {
4925           /* Nothing changed.  */
4926           value_free_to_mark (mark);
4927           return WP_VALUE_NOT_CHANGED;
4928         }
4929     }
4930   else
4931     {
4932       /* This seems like the only logical thing to do because
4933          if we temporarily ignored the watchpoint, then when
4934          we reenter the block in which it is valid it contains
4935          garbage (in the case of a function, it may have two
4936          garbage values, one before and one after the prologue).
4937          So we can't even detect the first assignment to it and
4938          watch after that (since the garbage may or may not equal
4939          the first value assigned).  */
4940       /* We print all the stop information in
4941          breakpoint_ops->print_it, but in this case, by the time we
4942          call breakpoint_ops->print_it this bp will be deleted
4943          already.  So we have no choice but print the information
4944          here.  */
4945
4946       SWITCH_THRU_ALL_UIS ()
4947         {
4948           struct ui_out *uiout = current_uiout;
4949
4950           if (uiout->is_mi_like_p ())
4951             uiout->field_string
4952               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4953           uiout->text ("\nWatchpoint ");
4954           uiout->field_int ("wpnum", b->number);
4955           uiout->text (" deleted because the program has left the block in\n"
4956                        "which its expression is valid.\n");
4957         }
4958
4959       /* Make sure the watchpoint's commands aren't executed.  */
4960       b->commands = NULL;
4961       watchpoint_del_at_next_stop (b);
4962
4963       return WP_DELETED;
4964     }
4965 }
4966
4967 /* Return true if it looks like target has stopped due to hitting
4968    breakpoint location BL.  This function does not check if we should
4969    stop, only if BL explains the stop.  */
4970
4971 static int
4972 bpstat_check_location (const struct bp_location *bl,
4973                        const address_space *aspace, CORE_ADDR bp_addr,
4974                        const struct target_waitstatus *ws)
4975 {
4976   struct breakpoint *b = bl->owner;
4977
4978   /* BL is from an existing breakpoint.  */
4979   gdb_assert (b != NULL);
4980
4981   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4982 }
4983
4984 /* Determine if the watched values have actually changed, and we
4985    should stop.  If not, set BS->stop to 0.  */
4986
4987 static void
4988 bpstat_check_watchpoint (bpstat bs)
4989 {
4990   const struct bp_location *bl;
4991   struct watchpoint *b;
4992
4993   /* BS is built for existing struct breakpoint.  */
4994   bl = bs->bp_location_at;
4995   gdb_assert (bl != NULL);
4996   b = (struct watchpoint *) bs->breakpoint_at;
4997   gdb_assert (b != NULL);
4998
4999     {
5000       int must_check_value = 0;
5001       
5002       if (b->type == bp_watchpoint)
5003         /* For a software watchpoint, we must always check the
5004            watched value.  */
5005         must_check_value = 1;
5006       else if (b->watchpoint_triggered == watch_triggered_yes)
5007         /* We have a hardware watchpoint (read, write, or access)
5008            and the target earlier reported an address watched by
5009            this watchpoint.  */
5010         must_check_value = 1;
5011       else if (b->watchpoint_triggered == watch_triggered_unknown
5012                && b->type == bp_hardware_watchpoint)
5013         /* We were stopped by a hardware watchpoint, but the target could
5014            not report the data address.  We must check the watchpoint's
5015            value.  Access and read watchpoints are out of luck; without
5016            a data address, we can't figure it out.  */
5017         must_check_value = 1;
5018
5019       if (must_check_value)
5020         {
5021           wp_check_result e;
5022
5023           TRY
5024             {
5025               e = watchpoint_check (bs);
5026             }
5027           CATCH (ex, RETURN_MASK_ALL)
5028             {
5029               exception_fprintf (gdb_stderr, ex,
5030                                  "Error evaluating expression "
5031                                  "for watchpoint %d\n",
5032                                  b->number);
5033
5034               SWITCH_THRU_ALL_UIS ()
5035                 {
5036                   printf_filtered (_("Watchpoint %d deleted.\n"),
5037                                    b->number);
5038                 }
5039               watchpoint_del_at_next_stop (b);
5040               e = WP_DELETED;
5041             }
5042           END_CATCH
5043
5044           switch (e)
5045             {
5046             case WP_DELETED:
5047               /* We've already printed what needs to be printed.  */
5048               bs->print_it = print_it_done;
5049               /* Stop.  */
5050               break;
5051             case WP_IGNORE:
5052               bs->print_it = print_it_noop;
5053               bs->stop = 0;
5054               break;
5055             case WP_VALUE_CHANGED:
5056               if (b->type == bp_read_watchpoint)
5057                 {
5058                   /* There are two cases to consider here:
5059
5060                      1. We're watching the triggered memory for reads.
5061                      In that case, trust the target, and always report
5062                      the watchpoint hit to the user.  Even though
5063                      reads don't cause value changes, the value may
5064                      have changed since the last time it was read, and
5065                      since we're not trapping writes, we will not see
5066                      those, and as such we should ignore our notion of
5067                      old value.
5068
5069                      2. We're watching the triggered memory for both
5070                      reads and writes.  There are two ways this may
5071                      happen:
5072
5073                      2.1. This is a target that can't break on data
5074                      reads only, but can break on accesses (reads or
5075                      writes), such as e.g., x86.  We detect this case
5076                      at the time we try to insert read watchpoints.
5077
5078                      2.2. Otherwise, the target supports read
5079                      watchpoints, but, the user set an access or write
5080                      watchpoint watching the same memory as this read
5081                      watchpoint.
5082
5083                      If we're watching memory writes as well as reads,
5084                      ignore watchpoint hits when we find that the
5085                      value hasn't changed, as reads don't cause
5086                      changes.  This still gives false positives when
5087                      the program writes the same value to memory as
5088                      what there was already in memory (we will confuse
5089                      it for a read), but it's much better than
5090                      nothing.  */
5091
5092                   int other_write_watchpoint = 0;
5093
5094                   if (bl->watchpoint_type == hw_read)
5095                     {
5096                       struct breakpoint *other_b;
5097
5098                       ALL_BREAKPOINTS (other_b)
5099                         if (other_b->type == bp_hardware_watchpoint
5100                             || other_b->type == bp_access_watchpoint)
5101                           {
5102                             struct watchpoint *other_w =
5103                               (struct watchpoint *) other_b;
5104
5105                             if (other_w->watchpoint_triggered
5106                                 == watch_triggered_yes)
5107                               {
5108                                 other_write_watchpoint = 1;
5109                                 break;
5110                               }
5111                           }
5112                     }
5113
5114                   if (other_write_watchpoint
5115                       || bl->watchpoint_type == hw_access)
5116                     {
5117                       /* We're watching the same memory for writes,
5118                          and the value changed since the last time we
5119                          updated it, so this trap must be for a write.
5120                          Ignore it.  */
5121                       bs->print_it = print_it_noop;
5122                       bs->stop = 0;
5123                     }
5124                 }
5125               break;
5126             case WP_VALUE_NOT_CHANGED:
5127               if (b->type == bp_hardware_watchpoint
5128                   || b->type == bp_watchpoint)
5129                 {
5130                   /* Don't stop: write watchpoints shouldn't fire if
5131                      the value hasn't changed.  */
5132                   bs->print_it = print_it_noop;
5133                   bs->stop = 0;
5134                 }
5135               /* Stop.  */
5136               break;
5137             default:
5138               /* Can't happen.  */
5139               break;
5140             }
5141         }
5142       else      /* must_check_value == 0 */
5143         {
5144           /* This is a case where some watchpoint(s) triggered, but
5145              not at the address of this watchpoint, or else no
5146              watchpoint triggered after all.  So don't print
5147              anything for this watchpoint.  */
5148           bs->print_it = print_it_noop;
5149           bs->stop = 0;
5150         }
5151     }
5152 }
5153
5154 /* For breakpoints that are currently marked as telling gdb to stop,
5155    check conditions (condition proper, frame, thread and ignore count)
5156    of breakpoint referred to by BS.  If we should not stop for this
5157    breakpoint, set BS->stop to 0.  */
5158
5159 static void
5160 bpstat_check_breakpoint_conditions (bpstat bs, thread_info *thread)
5161 {
5162   const struct bp_location *bl;
5163   struct breakpoint *b;
5164   /* Assume stop.  */
5165   bool condition_result = true;
5166   struct expression *cond;
5167
5168   gdb_assert (bs->stop);
5169
5170   /* BS is built for existing struct breakpoint.  */
5171   bl = bs->bp_location_at;
5172   gdb_assert (bl != NULL);
5173   b = bs->breakpoint_at;
5174   gdb_assert (b != NULL);
5175
5176   /* Even if the target evaluated the condition on its end and notified GDB, we
5177      need to do so again since GDB does not know if we stopped due to a
5178      breakpoint or a single step breakpoint.  */
5179
5180   if (frame_id_p (b->frame_id)
5181       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5182     {
5183       bs->stop = 0;
5184       return;
5185     }
5186
5187   /* If this is a thread/task-specific breakpoint, don't waste cpu
5188      evaluating the condition if this isn't the specified
5189      thread/task.  */
5190   if ((b->thread != -1 && b->thread != thread->global_num)
5191       || (b->task != 0 && b->task != ada_get_task_number (thread)))
5192     {
5193       bs->stop = 0;
5194       return;
5195     }
5196
5197   /* Evaluate extension language breakpoints that have a "stop" method
5198      implemented.  */
5199   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5200
5201   if (is_watchpoint (b))
5202     {
5203       struct watchpoint *w = (struct watchpoint *) b;
5204
5205       cond = w->cond_exp.get ();
5206     }
5207   else
5208     cond = bl->cond.get ();
5209
5210   if (cond && b->disposition != disp_del_at_next_stop)
5211     {
5212       int within_current_scope = 1;
5213       struct watchpoint * w;
5214
5215       /* We use value_mark and value_free_to_mark because it could
5216          be a long time before we return to the command level and
5217          call free_all_values.  We can't call free_all_values
5218          because we might be in the middle of evaluating a
5219          function call.  */
5220       struct value *mark = value_mark ();
5221
5222       if (is_watchpoint (b))
5223         w = (struct watchpoint *) b;
5224       else
5225         w = NULL;
5226
5227       /* Need to select the frame, with all that implies so that
5228          the conditions will have the right context.  Because we
5229          use the frame, we will not see an inlined function's
5230          variables when we arrive at a breakpoint at the start
5231          of the inlined function; the current frame will be the
5232          call site.  */
5233       if (w == NULL || w->cond_exp_valid_block == NULL)
5234         select_frame (get_current_frame ());
5235       else
5236         {
5237           struct frame_info *frame;
5238
5239           /* For local watchpoint expressions, which particular
5240              instance of a local is being watched matters, so we
5241              keep track of the frame to evaluate the expression
5242              in.  To evaluate the condition however, it doesn't
5243              really matter which instantiation of the function
5244              where the condition makes sense triggers the
5245              watchpoint.  This allows an expression like "watch
5246              global if q > 10" set in `func', catch writes to
5247              global on all threads that call `func', or catch
5248              writes on all recursive calls of `func' by a single
5249              thread.  We simply always evaluate the condition in
5250              the innermost frame that's executing where it makes
5251              sense to evaluate the condition.  It seems
5252              intuitive.  */
5253           frame = block_innermost_frame (w->cond_exp_valid_block);
5254           if (frame != NULL)
5255             select_frame (frame);
5256           else
5257             within_current_scope = 0;
5258         }
5259       if (within_current_scope)
5260         {
5261           TRY
5262             {
5263               condition_result = breakpoint_cond_eval (cond);
5264             }
5265           CATCH (ex, RETURN_MASK_ALL)
5266             {
5267               exception_fprintf (gdb_stderr, ex,
5268                                  "Error in testing breakpoint condition:\n");
5269             }
5270           END_CATCH
5271         }
5272       else
5273         {
5274           warning (_("Watchpoint condition cannot be tested "
5275                      "in the current scope"));
5276           /* If we failed to set the right context for this
5277              watchpoint, unconditionally report it.  */
5278         }
5279       /* FIXME-someday, should give breakpoint #.  */
5280       value_free_to_mark (mark);
5281     }
5282
5283   if (cond && !condition_result)
5284     {
5285       bs->stop = 0;
5286     }
5287   else if (b->ignore_count > 0)
5288     {
5289       b->ignore_count--;
5290       bs->stop = 0;
5291       /* Increase the hit count even though we don't stop.  */
5292       ++(b->hit_count);
5293       gdb::observers::breakpoint_modified.notify (b);
5294     }   
5295 }
5296
5297 /* Returns true if we need to track moribund locations of LOC's type
5298    on the current target.  */
5299
5300 static int
5301 need_moribund_for_location_type (struct bp_location *loc)
5302 {
5303   return ((loc->loc_type == bp_loc_software_breakpoint
5304            && !target_supports_stopped_by_sw_breakpoint ())
5305           || (loc->loc_type == bp_loc_hardware_breakpoint
5306               && !target_supports_stopped_by_hw_breakpoint ()));
5307 }
5308
5309 /* See breakpoint.h.  */
5310
5311 bpstat
5312 build_bpstat_chain (const address_space *aspace, CORE_ADDR bp_addr,
5313                     const struct target_waitstatus *ws)
5314 {
5315   struct breakpoint *b;
5316   bpstat bs_head = NULL, *bs_link = &bs_head;
5317
5318   ALL_BREAKPOINTS (b)
5319     {
5320       if (!breakpoint_enabled (b))
5321         continue;
5322
5323       for (bp_location *bl = b->loc; bl != NULL; bl = bl->next)
5324         {
5325           /* For hardware watchpoints, we look only at the first
5326              location.  The watchpoint_check function will work on the
5327              entire expression, not the individual locations.  For
5328              read watchpoints, the watchpoints_triggered function has
5329              checked all locations already.  */
5330           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5331             break;
5332
5333           if (!bl->enabled || bl->shlib_disabled)
5334             continue;
5335
5336           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5337             continue;
5338
5339           /* Come here if it's a watchpoint, or if the break address
5340              matches.  */
5341
5342           bpstat bs = new bpstats (bl, &bs_link);       /* Alloc a bpstat to
5343                                                            explain stop.  */
5344
5345           /* Assume we stop.  Should we find a watchpoint that is not
5346              actually triggered, or if the condition of the breakpoint
5347              evaluates as false, we'll reset 'stop' to 0.  */
5348           bs->stop = 1;
5349           bs->print = 1;
5350
5351           /* If this is a scope breakpoint, mark the associated
5352              watchpoint as triggered so that we will handle the
5353              out-of-scope event.  We'll get to the watchpoint next
5354              iteration.  */
5355           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5356             {
5357               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5358
5359               w->watchpoint_triggered = watch_triggered_yes;
5360             }
5361         }
5362     }
5363
5364   /* Check if a moribund breakpoint explains the stop.  */
5365   if (!target_supports_stopped_by_sw_breakpoint ()
5366       || !target_supports_stopped_by_hw_breakpoint ())
5367     {
5368       for (bp_location *loc : moribund_locations)
5369         {
5370           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5371               && need_moribund_for_location_type (loc))
5372             {
5373               bpstat bs = new bpstats (loc, &bs_link);
5374               /* For hits of moribund locations, we should just proceed.  */
5375               bs->stop = 0;
5376               bs->print = 0;
5377               bs->print_it = print_it_noop;
5378             }
5379         }
5380     }
5381
5382   return bs_head;
5383 }
5384
5385 /* See breakpoint.h.  */
5386
5387 bpstat
5388 bpstat_stop_status (const address_space *aspace,
5389                     CORE_ADDR bp_addr, thread_info *thread,
5390                     const struct target_waitstatus *ws,
5391                     bpstat stop_chain)
5392 {
5393   struct breakpoint *b = NULL;
5394   /* First item of allocated bpstat's.  */
5395   bpstat bs_head = stop_chain;
5396   bpstat bs;
5397   int need_remove_insert;
5398   int removed_any;
5399
5400   /* First, build the bpstat chain with locations that explain a
5401      target stop, while being careful to not set the target running,
5402      as that may invalidate locations (in particular watchpoint
5403      locations are recreated).  Resuming will happen here with
5404      breakpoint conditions or watchpoint expressions that include
5405      inferior function calls.  */
5406   if (bs_head == NULL)
5407     bs_head = build_bpstat_chain (aspace, bp_addr, ws);
5408
5409   /* A bit of special processing for shlib breakpoints.  We need to
5410      process solib loading here, so that the lists of loaded and
5411      unloaded libraries are correct before we handle "catch load" and
5412      "catch unload".  */
5413   for (bs = bs_head; bs != NULL; bs = bs->next)
5414     {
5415       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5416         {
5417           handle_solib_event ();
5418           break;
5419         }
5420     }
5421
5422   /* Now go through the locations that caused the target to stop, and
5423      check whether we're interested in reporting this stop to higher
5424      layers, or whether we should resume the target transparently.  */
5425
5426   removed_any = 0;
5427
5428   for (bs = bs_head; bs != NULL; bs = bs->next)
5429     {
5430       if (!bs->stop)
5431         continue;
5432
5433       b = bs->breakpoint_at;
5434       b->ops->check_status (bs);
5435       if (bs->stop)
5436         {
5437           bpstat_check_breakpoint_conditions (bs, thread);
5438
5439           if (bs->stop)
5440             {
5441               ++(b->hit_count);
5442               gdb::observers::breakpoint_modified.notify (b);
5443
5444               /* We will stop here.  */
5445               if (b->disposition == disp_disable)
5446                 {
5447                   --(b->enable_count);
5448                   if (b->enable_count <= 0)
5449                     b->enable_state = bp_disabled;
5450                   removed_any = 1;
5451                 }
5452               if (b->silent)
5453                 bs->print = 0;
5454               bs->commands = b->commands;
5455               if (command_line_is_silent (bs->commands
5456                                           ? bs->commands.get () : NULL))
5457                 bs->print = 0;
5458
5459               b->ops->after_condition_true (bs);
5460             }
5461
5462         }
5463
5464       /* Print nothing for this entry if we don't stop or don't
5465          print.  */
5466       if (!bs->stop || !bs->print)
5467         bs->print_it = print_it_noop;
5468     }
5469
5470   /* If we aren't stopping, the value of some hardware watchpoint may
5471      not have changed, but the intermediate memory locations we are
5472      watching may have.  Don't bother if we're stopping; this will get
5473      done later.  */
5474   need_remove_insert = 0;
5475   if (! bpstat_causes_stop (bs_head))
5476     for (bs = bs_head; bs != NULL; bs = bs->next)
5477       if (!bs->stop
5478           && bs->breakpoint_at
5479           && is_hardware_watchpoint (bs->breakpoint_at))
5480         {
5481           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5482
5483           update_watchpoint (w, 0 /* don't reparse.  */);
5484           need_remove_insert = 1;
5485         }
5486
5487   if (need_remove_insert)
5488     update_global_location_list (UGLL_MAY_INSERT);
5489   else if (removed_any)
5490     update_global_location_list (UGLL_DONT_INSERT);
5491
5492   return bs_head;
5493 }
5494
5495 static void
5496 handle_jit_event (void)
5497 {
5498   struct frame_info *frame;
5499   struct gdbarch *gdbarch;
5500
5501   if (debug_infrun)
5502     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5503
5504   /* Switch terminal for any messages produced by
5505      breakpoint_re_set.  */
5506   target_terminal::ours_for_output ();
5507
5508   frame = get_current_frame ();
5509   gdbarch = get_frame_arch (frame);
5510
5511   jit_event_handler (gdbarch);
5512
5513   target_terminal::inferior ();
5514 }
5515
5516 /* Prepare WHAT final decision for infrun.  */
5517
5518 /* Decide what infrun needs to do with this bpstat.  */
5519
5520 struct bpstat_what
5521 bpstat_what (bpstat bs_head)
5522 {
5523   struct bpstat_what retval;
5524   bpstat bs;
5525
5526   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5527   retval.call_dummy = STOP_NONE;
5528   retval.is_longjmp = 0;
5529
5530   for (bs = bs_head; bs != NULL; bs = bs->next)
5531     {
5532       /* Extract this BS's action.  After processing each BS, we check
5533          if its action overrides all we've seem so far.  */
5534       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5535       enum bptype bptype;
5536
5537       if (bs->breakpoint_at == NULL)
5538         {
5539           /* I suspect this can happen if it was a momentary
5540              breakpoint which has since been deleted.  */
5541           bptype = bp_none;
5542         }
5543       else
5544         bptype = bs->breakpoint_at->type;
5545
5546       switch (bptype)
5547         {
5548         case bp_none:
5549           break;
5550         case bp_breakpoint:
5551         case bp_hardware_breakpoint:
5552         case bp_single_step:
5553         case bp_until:
5554         case bp_finish:
5555         case bp_shlib_event:
5556           if (bs->stop)
5557             {
5558               if (bs->print)
5559                 this_action = BPSTAT_WHAT_STOP_NOISY;
5560               else
5561                 this_action = BPSTAT_WHAT_STOP_SILENT;
5562             }
5563           else
5564             this_action = BPSTAT_WHAT_SINGLE;
5565           break;
5566         case bp_watchpoint:
5567         case bp_hardware_watchpoint:
5568         case bp_read_watchpoint:
5569         case bp_access_watchpoint:
5570           if (bs->stop)
5571             {
5572               if (bs->print)
5573                 this_action = BPSTAT_WHAT_STOP_NOISY;
5574               else
5575                 this_action = BPSTAT_WHAT_STOP_SILENT;
5576             }
5577           else
5578             {
5579               /* There was a watchpoint, but we're not stopping.
5580                  This requires no further action.  */
5581             }
5582           break;
5583         case bp_longjmp:
5584         case bp_longjmp_call_dummy:
5585         case bp_exception:
5586           if (bs->stop)
5587             {
5588               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5589               retval.is_longjmp = bptype != bp_exception;
5590             }
5591           else
5592             this_action = BPSTAT_WHAT_SINGLE;
5593           break;
5594         case bp_longjmp_resume:
5595         case bp_exception_resume:
5596           if (bs->stop)
5597             {
5598               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5599               retval.is_longjmp = bptype == bp_longjmp_resume;
5600             }
5601           else
5602             this_action = BPSTAT_WHAT_SINGLE;
5603           break;
5604         case bp_step_resume:
5605           if (bs->stop)
5606             this_action = BPSTAT_WHAT_STEP_RESUME;
5607           else
5608             {
5609               /* It is for the wrong frame.  */
5610               this_action = BPSTAT_WHAT_SINGLE;
5611             }
5612           break;
5613         case bp_hp_step_resume:
5614           if (bs->stop)
5615             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5616           else
5617             {
5618               /* It is for the wrong frame.  */
5619               this_action = BPSTAT_WHAT_SINGLE;
5620             }
5621           break;
5622         case bp_watchpoint_scope:
5623         case bp_thread_event:
5624         case bp_overlay_event:
5625         case bp_longjmp_master:
5626         case bp_std_terminate_master:
5627         case bp_exception_master:
5628           this_action = BPSTAT_WHAT_SINGLE;
5629           break;
5630         case bp_catchpoint:
5631           if (bs->stop)
5632             {
5633               if (bs->print)
5634                 this_action = BPSTAT_WHAT_STOP_NOISY;
5635               else
5636                 this_action = BPSTAT_WHAT_STOP_SILENT;
5637             }
5638           else
5639             {
5640               /* There was a catchpoint, but we're not stopping.
5641                  This requires no further action.  */
5642             }
5643           break;
5644         case bp_jit_event:
5645           this_action = BPSTAT_WHAT_SINGLE;
5646           break;
5647         case bp_call_dummy:
5648           /* Make sure the action is stop (silent or noisy),
5649              so infrun.c pops the dummy frame.  */
5650           retval.call_dummy = STOP_STACK_DUMMY;
5651           this_action = BPSTAT_WHAT_STOP_SILENT;
5652           break;
5653         case bp_std_terminate:
5654           /* Make sure the action is stop (silent or noisy),
5655              so infrun.c pops the dummy frame.  */
5656           retval.call_dummy = STOP_STD_TERMINATE;
5657           this_action = BPSTAT_WHAT_STOP_SILENT;
5658           break;
5659         case bp_tracepoint:
5660         case bp_fast_tracepoint:
5661         case bp_static_tracepoint:
5662           /* Tracepoint hits should not be reported back to GDB, and
5663              if one got through somehow, it should have been filtered
5664              out already.  */
5665           internal_error (__FILE__, __LINE__,
5666                           _("bpstat_what: tracepoint encountered"));
5667           break;
5668         case bp_gnu_ifunc_resolver:
5669           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5670           this_action = BPSTAT_WHAT_SINGLE;
5671           break;
5672         case bp_gnu_ifunc_resolver_return:
5673           /* The breakpoint will be removed, execution will restart from the
5674              PC of the former breakpoint.  */
5675           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5676           break;
5677
5678         case bp_dprintf:
5679           if (bs->stop)
5680             this_action = BPSTAT_WHAT_STOP_SILENT;
5681           else
5682             this_action = BPSTAT_WHAT_SINGLE;
5683           break;
5684
5685         default:
5686           internal_error (__FILE__, __LINE__,
5687                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5688         }
5689
5690       retval.main_action = std::max (retval.main_action, this_action);
5691     }
5692
5693   return retval;
5694 }
5695
5696 void
5697 bpstat_run_callbacks (bpstat bs_head)
5698 {
5699   bpstat bs;
5700
5701   for (bs = bs_head; bs != NULL; bs = bs->next)
5702     {
5703       struct breakpoint *b = bs->breakpoint_at;
5704
5705       if (b == NULL)
5706         continue;
5707       switch (b->type)
5708         {
5709         case bp_jit_event:
5710           handle_jit_event ();
5711           break;
5712         case bp_gnu_ifunc_resolver:
5713           gnu_ifunc_resolver_stop (b);
5714           break;
5715         case bp_gnu_ifunc_resolver_return:
5716           gnu_ifunc_resolver_return_stop (b);
5717           break;
5718         }
5719     }
5720 }
5721
5722 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5723    without hardware support).  This isn't related to a specific bpstat,
5724    just to things like whether watchpoints are set.  */
5725
5726 int
5727 bpstat_should_step (void)
5728 {
5729   struct breakpoint *b;
5730
5731   ALL_BREAKPOINTS (b)
5732     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5733       return 1;
5734   return 0;
5735 }
5736
5737 int
5738 bpstat_causes_stop (bpstat bs)
5739 {
5740   for (; bs != NULL; bs = bs->next)
5741     if (bs->stop)
5742       return 1;
5743
5744   return 0;
5745 }
5746
5747 \f
5748
5749 /* Compute a string of spaces suitable to indent the next line
5750    so it starts at the position corresponding to the table column
5751    named COL_NAME in the currently active table of UIOUT.  */
5752
5753 static char *
5754 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5755 {
5756   static char wrap_indent[80];
5757   int i, total_width, width, align;
5758   const char *text;
5759
5760   total_width = 0;
5761   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
5762     {
5763       if (strcmp (text, col_name) == 0)
5764         {
5765           gdb_assert (total_width < sizeof wrap_indent);
5766           memset (wrap_indent, ' ', total_width);
5767           wrap_indent[total_width] = 0;
5768
5769           return wrap_indent;
5770         }
5771
5772       total_width += width + 1;
5773     }
5774
5775   return NULL;
5776 }
5777
5778 /* Determine if the locations of this breakpoint will have their conditions
5779    evaluated by the target, host or a mix of both.  Returns the following:
5780
5781     "host": Host evals condition.
5782     "host or target": Host or Target evals condition.
5783     "target": Target evals condition.
5784 */
5785
5786 static const char *
5787 bp_condition_evaluator (struct breakpoint *b)
5788 {
5789   struct bp_location *bl;
5790   char host_evals = 0;
5791   char target_evals = 0;
5792
5793   if (!b)
5794     return NULL;
5795
5796   if (!is_breakpoint (b))
5797     return NULL;
5798
5799   if (gdb_evaluates_breakpoint_condition_p ()
5800       || !target_supports_evaluation_of_breakpoint_conditions ())
5801     return condition_evaluation_host;
5802
5803   for (bl = b->loc; bl; bl = bl->next)
5804     {
5805       if (bl->cond_bytecode)
5806         target_evals++;
5807       else
5808         host_evals++;
5809     }
5810
5811   if (host_evals && target_evals)
5812     return condition_evaluation_both;
5813   else if (target_evals)
5814     return condition_evaluation_target;
5815   else
5816     return condition_evaluation_host;
5817 }
5818
5819 /* Determine the breakpoint location's condition evaluator.  This is
5820    similar to bp_condition_evaluator, but for locations.  */
5821
5822 static const char *
5823 bp_location_condition_evaluator (struct bp_location *bl)
5824 {
5825   if (bl && !is_breakpoint (bl->owner))
5826     return NULL;
5827
5828   if (gdb_evaluates_breakpoint_condition_p ()
5829       || !target_supports_evaluation_of_breakpoint_conditions ())
5830     return condition_evaluation_host;
5831
5832   if (bl && bl->cond_bytecode)
5833     return condition_evaluation_target;
5834   else
5835     return condition_evaluation_host;
5836 }
5837
5838 /* Print the LOC location out of the list of B->LOC locations.  */
5839
5840 static void
5841 print_breakpoint_location (struct breakpoint *b,
5842                            struct bp_location *loc)
5843 {
5844   struct ui_out *uiout = current_uiout;
5845
5846   scoped_restore_current_program_space restore_pspace;
5847
5848   if (loc != NULL && loc->shlib_disabled)
5849     loc = NULL;
5850
5851   if (loc != NULL)
5852     set_current_program_space (loc->pspace);
5853
5854   if (b->display_canonical)
5855     uiout->field_string ("what", event_location_to_string (b->location.get ()));
5856   else if (loc && loc->symtab)
5857     {
5858       const struct symbol *sym = loc->symbol;
5859
5860       if (sym)
5861         {
5862           uiout->text ("in ");
5863           uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
5864           uiout->text (" ");
5865           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
5866           uiout->text ("at ");
5867         }
5868       uiout->field_string ("file",
5869                            symtab_to_filename_for_display (loc->symtab));
5870       uiout->text (":");
5871
5872       if (uiout->is_mi_like_p ())
5873         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
5874       
5875       uiout->field_int ("line", loc->line_number);
5876     }
5877   else if (loc)
5878     {
5879       string_file stb;
5880
5881       print_address_symbolic (loc->gdbarch, loc->address, &stb,
5882                               demangle, "");
5883       uiout->field_stream ("at", stb);
5884     }
5885   else
5886     {
5887       uiout->field_string ("pending",
5888                            event_location_to_string (b->location.get ()));
5889       /* If extra_string is available, it could be holding a condition
5890          or dprintf arguments.  In either case, make sure it is printed,
5891          too, but only for non-MI streams.  */
5892       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
5893         {
5894           if (b->type == bp_dprintf)
5895             uiout->text (",");
5896           else
5897             uiout->text (" ");
5898           uiout->text (b->extra_string);
5899         }
5900     }
5901
5902   if (loc && is_breakpoint (b)
5903       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5904       && bp_condition_evaluator (b) == condition_evaluation_both)
5905     {
5906       uiout->text (" (");
5907       uiout->field_string ("evaluated-by",
5908                            bp_location_condition_evaluator (loc));
5909       uiout->text (")");
5910     }
5911 }
5912
5913 static const char *
5914 bptype_string (enum bptype type)
5915 {
5916   struct ep_type_description
5917     {
5918       enum bptype type;
5919       const char *description;
5920     };
5921   static struct ep_type_description bptypes[] =
5922   {
5923     {bp_none, "?deleted?"},
5924     {bp_breakpoint, "breakpoint"},
5925     {bp_hardware_breakpoint, "hw breakpoint"},
5926     {bp_single_step, "sw single-step"},
5927     {bp_until, "until"},
5928     {bp_finish, "finish"},
5929     {bp_watchpoint, "watchpoint"},
5930     {bp_hardware_watchpoint, "hw watchpoint"},
5931     {bp_read_watchpoint, "read watchpoint"},
5932     {bp_access_watchpoint, "acc watchpoint"},
5933     {bp_longjmp, "longjmp"},
5934     {bp_longjmp_resume, "longjmp resume"},
5935     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5936     {bp_exception, "exception"},
5937     {bp_exception_resume, "exception resume"},
5938     {bp_step_resume, "step resume"},
5939     {bp_hp_step_resume, "high-priority step resume"},
5940     {bp_watchpoint_scope, "watchpoint scope"},
5941     {bp_call_dummy, "call dummy"},
5942     {bp_std_terminate, "std::terminate"},
5943     {bp_shlib_event, "shlib events"},
5944     {bp_thread_event, "thread events"},
5945     {bp_overlay_event, "overlay events"},
5946     {bp_longjmp_master, "longjmp master"},
5947     {bp_std_terminate_master, "std::terminate master"},
5948     {bp_exception_master, "exception master"},
5949     {bp_catchpoint, "catchpoint"},
5950     {bp_tracepoint, "tracepoint"},
5951     {bp_fast_tracepoint, "fast tracepoint"},
5952     {bp_static_tracepoint, "static tracepoint"},
5953     {bp_dprintf, "dprintf"},
5954     {bp_jit_event, "jit events"},
5955     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5956     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5957   };
5958
5959   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5960       || ((int) type != bptypes[(int) type].type))
5961     internal_error (__FILE__, __LINE__,
5962                     _("bptypes table does not describe type #%d."),
5963                     (int) type);
5964
5965   return bptypes[(int) type].description;
5966 }
5967
5968 /* For MI, output a field named 'thread-groups' with a list as the value.
5969    For CLI, prefix the list with the string 'inf'. */
5970
5971 static void
5972 output_thread_groups (struct ui_out *uiout,
5973                       const char *field_name,
5974                       const std::vector<int> &inf_nums,
5975                       int mi_only)
5976 {
5977   int is_mi = uiout->is_mi_like_p ();
5978
5979   /* For backward compatibility, don't display inferiors in CLI unless
5980      there are several.  Always display them for MI. */
5981   if (!is_mi && mi_only)
5982     return;
5983
5984   ui_out_emit_list list_emitter (uiout, field_name);
5985
5986   for (size_t i = 0; i < inf_nums.size (); i++)
5987     {
5988       if (is_mi)
5989         {
5990           char mi_group[10];
5991
5992           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf_nums[i]);
5993           uiout->field_string (NULL, mi_group);
5994         }
5995       else
5996         {
5997           if (i == 0)
5998             uiout->text (" inf ");
5999           else
6000             uiout->text (", ");
6001         
6002           uiout->text (plongest (inf_nums[i]));
6003         }
6004     }
6005 }
6006
6007 /* Print B to gdb_stdout.  */
6008
6009 static void
6010 print_one_breakpoint_location (struct breakpoint *b,
6011                                struct bp_location *loc,
6012                                int loc_number,
6013                                struct bp_location **last_loc,
6014                                int allflag)
6015 {
6016   struct command_line *l;
6017   static char bpenables[] = "nynny";
6018
6019   struct ui_out *uiout = current_uiout;
6020   int header_of_multiple = 0;
6021   int part_of_multiple = (loc != NULL);
6022   struct value_print_options opts;
6023
6024   get_user_print_options (&opts);
6025
6026   gdb_assert (!loc || loc_number != 0);
6027   /* See comment in print_one_breakpoint concerning treatment of
6028      breakpoints with single disabled location.  */
6029   if (loc == NULL 
6030       && (b->loc != NULL 
6031           && (b->loc->next != NULL || !b->loc->enabled)))
6032     header_of_multiple = 1;
6033   if (loc == NULL)
6034     loc = b->loc;
6035
6036   annotate_record ();
6037
6038   /* 1 */
6039   annotate_field (0);
6040   if (part_of_multiple)
6041     uiout->field_fmt ("number", "%d.%d", b->number, loc_number);
6042   else
6043     uiout->field_int ("number", b->number);
6044
6045   /* 2 */
6046   annotate_field (1);
6047   if (part_of_multiple)
6048     uiout->field_skip ("type");
6049   else
6050     uiout->field_string ("type", bptype_string (b->type));
6051
6052   /* 3 */
6053   annotate_field (2);
6054   if (part_of_multiple)
6055     uiout->field_skip ("disp");
6056   else
6057     uiout->field_string ("disp", bpdisp_text (b->disposition));
6058
6059   /* 4 */
6060   annotate_field (3);
6061   if (part_of_multiple)
6062     uiout->field_string ("enabled", loc->enabled ? "y" : "n");
6063   else
6064     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6065
6066   /* 5 and 6 */
6067   if (b->ops != NULL && b->ops->print_one != NULL)
6068     {
6069       /* Although the print_one can possibly print all locations,
6070          calling it here is not likely to get any nice result.  So,
6071          make sure there's just one location.  */
6072       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6073       b->ops->print_one (b, last_loc);
6074     }
6075   else
6076     switch (b->type)
6077       {
6078       case bp_none:
6079         internal_error (__FILE__, __LINE__,
6080                         _("print_one_breakpoint: bp_none encountered\n"));
6081         break;
6082
6083       case bp_watchpoint:
6084       case bp_hardware_watchpoint:
6085       case bp_read_watchpoint:
6086       case bp_access_watchpoint:
6087         {
6088           struct watchpoint *w = (struct watchpoint *) b;
6089
6090           /* Field 4, the address, is omitted (which makes the columns
6091              not line up too nicely with the headers, but the effect
6092              is relatively readable).  */
6093           if (opts.addressprint)
6094             uiout->field_skip ("addr");
6095           annotate_field (5);
6096           uiout->field_string ("what", w->exp_string);
6097         }
6098         break;
6099
6100       case bp_breakpoint:
6101       case bp_hardware_breakpoint:
6102       case bp_single_step:
6103       case bp_until:
6104       case bp_finish:
6105       case bp_longjmp:
6106       case bp_longjmp_resume:
6107       case bp_longjmp_call_dummy:
6108       case bp_exception:
6109       case bp_exception_resume:
6110       case bp_step_resume:
6111       case bp_hp_step_resume:
6112       case bp_watchpoint_scope:
6113       case bp_call_dummy:
6114       case bp_std_terminate:
6115       case bp_shlib_event:
6116       case bp_thread_event:
6117       case bp_overlay_event:
6118       case bp_longjmp_master:
6119       case bp_std_terminate_master:
6120       case bp_exception_master:
6121       case bp_tracepoint:
6122       case bp_fast_tracepoint:
6123       case bp_static_tracepoint:
6124       case bp_dprintf:
6125       case bp_jit_event:
6126       case bp_gnu_ifunc_resolver:
6127       case bp_gnu_ifunc_resolver_return:
6128         if (opts.addressprint)
6129           {
6130             annotate_field (4);
6131             if (header_of_multiple)
6132               uiout->field_string ("addr", "<MULTIPLE>");
6133             else if (b->loc == NULL || loc->shlib_disabled)
6134               uiout->field_string ("addr", "<PENDING>");
6135             else
6136               uiout->field_core_addr ("addr",
6137                                       loc->gdbarch, loc->address);
6138           }
6139         annotate_field (5);
6140         if (!header_of_multiple)
6141           print_breakpoint_location (b, loc);
6142         if (b->loc)
6143           *last_loc = b->loc;
6144         break;
6145       }
6146
6147
6148   if (loc != NULL && !header_of_multiple)
6149     {
6150       std::vector<int> inf_nums;
6151       int mi_only = 1;
6152
6153       for (inferior *inf : all_inferiors ())
6154         {
6155           if (inf->pspace == loc->pspace)
6156             inf_nums.push_back (inf->num);
6157         }
6158
6159         /* For backward compatibility, don't display inferiors in CLI unless
6160            there are several.  Always display for MI. */
6161         if (allflag
6162             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6163                 && (number_of_program_spaces () > 1
6164                     || number_of_inferiors () > 1)
6165                 /* LOC is for existing B, it cannot be in
6166                    moribund_locations and thus having NULL OWNER.  */
6167                 && loc->owner->type != bp_catchpoint))
6168         mi_only = 0;
6169       output_thread_groups (uiout, "thread-groups", inf_nums, mi_only);
6170     }
6171
6172   if (!part_of_multiple)
6173     {
6174       if (b->thread != -1)
6175         {
6176           /* FIXME: This seems to be redundant and lost here; see the
6177              "stop only in" line a little further down.  */
6178           uiout->text (" thread ");
6179           uiout->field_int ("thread", b->thread);
6180         }
6181       else if (b->task != 0)
6182         {
6183           uiout->text (" task ");
6184           uiout->field_int ("task", b->task);
6185         }
6186     }
6187
6188   uiout->text ("\n");
6189
6190   if (!part_of_multiple)
6191     b->ops->print_one_detail (b, uiout);
6192
6193   if (part_of_multiple && frame_id_p (b->frame_id))
6194     {
6195       annotate_field (6);
6196       uiout->text ("\tstop only in stack frame at ");
6197       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6198          the frame ID.  */
6199       uiout->field_core_addr ("frame",
6200                               b->gdbarch, b->frame_id.stack_addr);
6201       uiout->text ("\n");
6202     }
6203   
6204   if (!part_of_multiple && b->cond_string)
6205     {
6206       annotate_field (7);
6207       if (is_tracepoint (b))
6208         uiout->text ("\ttrace only if ");
6209       else
6210         uiout->text ("\tstop only if ");
6211       uiout->field_string ("cond", b->cond_string);
6212
6213       /* Print whether the target is doing the breakpoint's condition
6214          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6215       if (is_breakpoint (b)
6216           && breakpoint_condition_evaluation_mode ()
6217           == condition_evaluation_target)
6218         {
6219           uiout->text (" (");
6220           uiout->field_string ("evaluated-by",
6221                                bp_condition_evaluator (b));
6222           uiout->text (" evals)");
6223         }
6224       uiout->text ("\n");
6225     }
6226
6227   if (!part_of_multiple && b->thread != -1)
6228     {
6229       /* FIXME should make an annotation for this.  */
6230       uiout->text ("\tstop only in thread ");
6231       if (uiout->is_mi_like_p ())
6232         uiout->field_int ("thread", b->thread);
6233       else
6234         {
6235           struct thread_info *thr = find_thread_global_id (b->thread);
6236
6237           uiout->field_string ("thread", print_thread_id (thr));
6238         }
6239       uiout->text ("\n");
6240     }
6241   
6242   if (!part_of_multiple)
6243     {
6244       if (b->hit_count)
6245         {
6246           /* FIXME should make an annotation for this.  */
6247           if (is_catchpoint (b))
6248             uiout->text ("\tcatchpoint");
6249           else if (is_tracepoint (b))
6250             uiout->text ("\ttracepoint");
6251           else
6252             uiout->text ("\tbreakpoint");
6253           uiout->text (" already hit ");
6254           uiout->field_int ("times", b->hit_count);
6255           if (b->hit_count == 1)
6256             uiout->text (" time\n");
6257           else
6258             uiout->text (" times\n");
6259         }
6260       else
6261         {
6262           /* Output the count also if it is zero, but only if this is mi.  */
6263           if (uiout->is_mi_like_p ())
6264             uiout->field_int ("times", b->hit_count);
6265         }
6266     }
6267
6268   if (!part_of_multiple && b->ignore_count)
6269     {
6270       annotate_field (8);
6271       uiout->text ("\tignore next ");
6272       uiout->field_int ("ignore", b->ignore_count);
6273       uiout->text (" hits\n");
6274     }
6275
6276   /* Note that an enable count of 1 corresponds to "enable once"
6277      behavior, which is reported by the combination of enablement and
6278      disposition, so we don't need to mention it here.  */
6279   if (!part_of_multiple && b->enable_count > 1)
6280     {
6281       annotate_field (8);
6282       uiout->text ("\tdisable after ");
6283       /* Tweak the wording to clarify that ignore and enable counts
6284          are distinct, and have additive effect.  */
6285       if (b->ignore_count)
6286         uiout->text ("additional ");
6287       else
6288         uiout->text ("next ");
6289       uiout->field_int ("enable", b->enable_count);
6290       uiout->text (" hits\n");
6291     }
6292
6293   if (!part_of_multiple && is_tracepoint (b))
6294     {
6295       struct tracepoint *tp = (struct tracepoint *) b;
6296
6297       if (tp->traceframe_usage)
6298         {
6299           uiout->text ("\ttrace buffer usage ");
6300           uiout->field_int ("traceframe-usage", tp->traceframe_usage);
6301           uiout->text (" bytes\n");
6302         }
6303     }
6304
6305   l = b->commands ? b->commands.get () : NULL;
6306   if (!part_of_multiple && l)
6307     {
6308       annotate_field (9);
6309       ui_out_emit_tuple tuple_emitter (uiout, "script");
6310       print_command_lines (uiout, l, 4);
6311     }
6312
6313   if (is_tracepoint (b))
6314     {
6315       struct tracepoint *t = (struct tracepoint *) b;
6316
6317       if (!part_of_multiple && t->pass_count)
6318         {
6319           annotate_field (10);
6320           uiout->text ("\tpass count ");
6321           uiout->field_int ("pass", t->pass_count);
6322           uiout->text (" \n");
6323         }
6324
6325       /* Don't display it when tracepoint or tracepoint location is
6326          pending.   */
6327       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6328         {
6329           annotate_field (11);
6330
6331           if (uiout->is_mi_like_p ())
6332             uiout->field_string ("installed",
6333                                  loc->inserted ? "y" : "n");
6334           else
6335             {
6336               if (loc->inserted)
6337                 uiout->text ("\t");
6338               else
6339                 uiout->text ("\tnot ");
6340               uiout->text ("installed on target\n");
6341             }
6342         }
6343     }
6344
6345   if (uiout->is_mi_like_p () && !part_of_multiple)
6346     {
6347       if (is_watchpoint (b))
6348         {
6349           struct watchpoint *w = (struct watchpoint *) b;
6350
6351           uiout->field_string ("original-location", w->exp_string);
6352         }
6353       else if (b->location != NULL
6354                && event_location_to_string (b->location.get ()) != NULL)
6355         uiout->field_string ("original-location",
6356                              event_location_to_string (b->location.get ()));
6357     }
6358 }
6359
6360 static void
6361 print_one_breakpoint (struct breakpoint *b,
6362                       struct bp_location **last_loc, 
6363                       int allflag)
6364 {
6365   struct ui_out *uiout = current_uiout;
6366
6367   {
6368     ui_out_emit_tuple tuple_emitter (uiout, "bkpt");
6369
6370     print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6371   }
6372
6373   /* If this breakpoint has custom print function,
6374      it's already printed.  Otherwise, print individual
6375      locations, if any.  */
6376   if (b->ops == NULL || b->ops->print_one == NULL)
6377     {
6378       /* If breakpoint has a single location that is disabled, we
6379          print it as if it had several locations, since otherwise it's
6380          hard to represent "breakpoint enabled, location disabled"
6381          situation.
6382
6383          Note that while hardware watchpoints have several locations
6384          internally, that's not a property exposed to user.  */
6385       if (b->loc 
6386           && !is_hardware_watchpoint (b)
6387           && (b->loc->next || !b->loc->enabled))
6388         {
6389           struct bp_location *loc;
6390           int n = 1;
6391
6392           for (loc = b->loc; loc; loc = loc->next, ++n)
6393             {
6394               ui_out_emit_tuple tuple_emitter (uiout, NULL);
6395               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6396             }
6397         }
6398     }
6399 }
6400
6401 static int
6402 breakpoint_address_bits (struct breakpoint *b)
6403 {
6404   int print_address_bits = 0;
6405   struct bp_location *loc;
6406
6407   /* Software watchpoints that aren't watching memory don't have an
6408      address to print.  */
6409   if (is_no_memory_software_watchpoint (b))
6410     return 0;
6411
6412   for (loc = b->loc; loc; loc = loc->next)
6413     {
6414       int addr_bit;
6415
6416       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6417       if (addr_bit > print_address_bits)
6418         print_address_bits = addr_bit;
6419     }
6420
6421   return print_address_bits;
6422 }
6423
6424 /* See breakpoint.h.  */
6425
6426 void
6427 print_breakpoint (breakpoint *b)
6428 {
6429   struct bp_location *dummy_loc = NULL;
6430   print_one_breakpoint (b, &dummy_loc, 0);
6431 }
6432
6433 /* Return true if this breakpoint was set by the user, false if it is
6434    internal or momentary.  */
6435
6436 int
6437 user_breakpoint_p (struct breakpoint *b)
6438 {
6439   return b->number > 0;
6440 }
6441
6442 /* See breakpoint.h.  */
6443
6444 int
6445 pending_breakpoint_p (struct breakpoint *b)
6446 {
6447   return b->loc == NULL;
6448 }
6449
6450 /* Print information on user settable breakpoint (watchpoint, etc)
6451    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6452    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6453    FILTER is non-NULL, call it on each breakpoint and only include the
6454    ones for which it returns non-zero.  Return the total number of
6455    breakpoints listed.  */
6456
6457 static int
6458 breakpoint_1 (const char *args, int allflag, 
6459               int (*filter) (const struct breakpoint *))
6460 {
6461   struct breakpoint *b;
6462   struct bp_location *last_loc = NULL;
6463   int nr_printable_breakpoints;
6464   struct value_print_options opts;
6465   int print_address_bits = 0;
6466   int print_type_col_width = 14;
6467   struct ui_out *uiout = current_uiout;
6468
6469   get_user_print_options (&opts);
6470
6471   /* Compute the number of rows in the table, as well as the size
6472      required for address fields.  */
6473   nr_printable_breakpoints = 0;
6474   ALL_BREAKPOINTS (b)
6475     {
6476       /* If we have a filter, only list the breakpoints it accepts.  */
6477       if (filter && !filter (b))
6478         continue;
6479
6480       /* If we have an "args" string, it is a list of breakpoints to 
6481          accept.  Skip the others.  */
6482       if (args != NULL && *args != '\0')
6483         {
6484           if (allflag && parse_and_eval_long (args) != b->number)
6485             continue;
6486           if (!allflag && !number_is_in_list (args, b->number))
6487             continue;
6488         }
6489
6490       if (allflag || user_breakpoint_p (b))
6491         {
6492           int addr_bit, type_len;
6493
6494           addr_bit = breakpoint_address_bits (b);
6495           if (addr_bit > print_address_bits)
6496             print_address_bits = addr_bit;
6497
6498           type_len = strlen (bptype_string (b->type));
6499           if (type_len > print_type_col_width)
6500             print_type_col_width = type_len;
6501
6502           nr_printable_breakpoints++;
6503         }
6504     }
6505
6506   {
6507     ui_out_emit_table table_emitter (uiout,
6508                                      opts.addressprint ? 6 : 5,
6509                                      nr_printable_breakpoints,
6510                                      "BreakpointTable");
6511
6512     if (nr_printable_breakpoints > 0)
6513       annotate_breakpoints_headers ();
6514     if (nr_printable_breakpoints > 0)
6515       annotate_field (0);
6516     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6517     if (nr_printable_breakpoints > 0)
6518       annotate_field (1);
6519     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6520     if (nr_printable_breakpoints > 0)
6521       annotate_field (2);
6522     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6523     if (nr_printable_breakpoints > 0)
6524       annotate_field (3);
6525     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6526     if (opts.addressprint)
6527       {
6528         if (nr_printable_breakpoints > 0)
6529           annotate_field (4);
6530         if (print_address_bits <= 32)
6531           uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6532         else
6533           uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6534       }
6535     if (nr_printable_breakpoints > 0)
6536       annotate_field (5);
6537     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6538     uiout->table_body ();
6539     if (nr_printable_breakpoints > 0)
6540       annotate_breakpoints_table ();
6541
6542     ALL_BREAKPOINTS (b)
6543       {
6544         QUIT;
6545         /* If we have a filter, only list the breakpoints it accepts.  */
6546         if (filter && !filter (b))
6547           continue;
6548
6549         /* If we have an "args" string, it is a list of breakpoints to 
6550            accept.  Skip the others.  */
6551
6552         if (args != NULL && *args != '\0')
6553           {
6554             if (allflag)        /* maintenance info breakpoint */
6555               {
6556                 if (parse_and_eval_long (args) != b->number)
6557                   continue;
6558               }
6559             else                /* all others */
6560               {
6561                 if (!number_is_in_list (args, b->number))
6562                   continue;
6563               }
6564           }
6565         /* We only print out user settable breakpoints unless the
6566            allflag is set.  */
6567         if (allflag || user_breakpoint_p (b))
6568           print_one_breakpoint (b, &last_loc, allflag);
6569       }
6570   }
6571
6572   if (nr_printable_breakpoints == 0)
6573     {
6574       /* If there's a filter, let the caller decide how to report
6575          empty list.  */
6576       if (!filter)
6577         {
6578           if (args == NULL || *args == '\0')
6579             uiout->message ("No breakpoints or watchpoints.\n");
6580           else
6581             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6582                             args);
6583         }
6584     }
6585   else
6586     {
6587       if (last_loc && !server_command)
6588         set_next_address (last_loc->gdbarch, last_loc->address);
6589     }
6590
6591   /* FIXME?  Should this be moved up so that it is only called when
6592      there have been breakpoints? */
6593   annotate_breakpoints_table_end ();
6594
6595   return nr_printable_breakpoints;
6596 }
6597
6598 /* Display the value of default-collect in a way that is generally
6599    compatible with the breakpoint list.  */
6600
6601 static void
6602 default_collect_info (void)
6603 {
6604   struct ui_out *uiout = current_uiout;
6605
6606   /* If it has no value (which is frequently the case), say nothing; a
6607      message like "No default-collect." gets in user's face when it's
6608      not wanted.  */
6609   if (!*default_collect)
6610     return;
6611
6612   /* The following phrase lines up nicely with per-tracepoint collect
6613      actions.  */
6614   uiout->text ("default collect ");
6615   uiout->field_string ("default-collect", default_collect);
6616   uiout->text (" \n");
6617 }
6618   
6619 static void
6620 info_breakpoints_command (const char *args, int from_tty)
6621 {
6622   breakpoint_1 (args, 0, NULL);
6623
6624   default_collect_info ();
6625 }
6626
6627 static void
6628 info_watchpoints_command (const char *args, int from_tty)
6629 {
6630   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6631   struct ui_out *uiout = current_uiout;
6632
6633   if (num_printed == 0)
6634     {
6635       if (args == NULL || *args == '\0')
6636         uiout->message ("No watchpoints.\n");
6637       else
6638         uiout->message ("No watchpoint matching '%s'.\n", args);
6639     }
6640 }
6641
6642 static void
6643 maintenance_info_breakpoints (const char *args, int from_tty)
6644 {
6645   breakpoint_1 (args, 1, NULL);
6646
6647   default_collect_info ();
6648 }
6649
6650 static int
6651 breakpoint_has_pc (struct breakpoint *b,
6652                    struct program_space *pspace,
6653                    CORE_ADDR pc, struct obj_section *section)
6654 {
6655   struct bp_location *bl = b->loc;
6656
6657   for (; bl; bl = bl->next)
6658     {
6659       if (bl->pspace == pspace
6660           && bl->address == pc
6661           && (!overlay_debugging || bl->section == section))
6662         return 1;         
6663     }
6664   return 0;
6665 }
6666
6667 /* Print a message describing any user-breakpoints set at PC.  This
6668    concerns with logical breakpoints, so we match program spaces, not
6669    address spaces.  */
6670
6671 static void
6672 describe_other_breakpoints (struct gdbarch *gdbarch,
6673                             struct program_space *pspace, CORE_ADDR pc,
6674                             struct obj_section *section, int thread)
6675 {
6676   int others = 0;
6677   struct breakpoint *b;
6678
6679   ALL_BREAKPOINTS (b)
6680     others += (user_breakpoint_p (b)
6681                && breakpoint_has_pc (b, pspace, pc, section));
6682   if (others > 0)
6683     {
6684       if (others == 1)
6685         printf_filtered (_("Note: breakpoint "));
6686       else /* if (others == ???) */
6687         printf_filtered (_("Note: breakpoints "));
6688       ALL_BREAKPOINTS (b)
6689         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6690           {
6691             others--;
6692             printf_filtered ("%d", b->number);
6693             if (b->thread == -1 && thread != -1)
6694               printf_filtered (" (all threads)");
6695             else if (b->thread != -1)
6696               printf_filtered (" (thread %d)", b->thread);
6697             printf_filtered ("%s%s ",
6698                              ((b->enable_state == bp_disabled
6699                                || b->enable_state == bp_call_disabled)
6700                               ? " (disabled)"
6701                               : ""),
6702                              (others > 1) ? "," 
6703                              : ((others == 1) ? " and" : ""));
6704           }
6705       printf_filtered (_("also set at pc "));
6706       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6707       printf_filtered (".\n");
6708     }
6709 }
6710 \f
6711
6712 /* Return true iff it is meaningful to use the address member of
6713    BPT locations.  For some breakpoint types, the locations' address members
6714    are irrelevant and it makes no sense to attempt to compare them to other
6715    addresses (or use them for any other purpose either).
6716
6717    More specifically, each of the following breakpoint types will
6718    always have a zero valued location address and we don't want to mark
6719    breakpoints of any of these types to be a duplicate of an actual
6720    breakpoint location at address zero:
6721
6722       bp_watchpoint
6723       bp_catchpoint
6724
6725 */
6726
6727 static int
6728 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6729 {
6730   enum bptype type = bpt->type;
6731
6732   return (type != bp_watchpoint && type != bp_catchpoint);
6733 }
6734
6735 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6736    true if LOC1 and LOC2 represent the same watchpoint location.  */
6737
6738 static int
6739 watchpoint_locations_match (struct bp_location *loc1, 
6740                             struct bp_location *loc2)
6741 {
6742   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6743   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6744
6745   /* Both of them must exist.  */
6746   gdb_assert (w1 != NULL);
6747   gdb_assert (w2 != NULL);
6748
6749   /* If the target can evaluate the condition expression in hardware,
6750      then we we need to insert both watchpoints even if they are at
6751      the same place.  Otherwise the watchpoint will only trigger when
6752      the condition of whichever watchpoint was inserted evaluates to
6753      true, not giving a chance for GDB to check the condition of the
6754      other watchpoint.  */
6755   if ((w1->cond_exp
6756        && target_can_accel_watchpoint_condition (loc1->address, 
6757                                                  loc1->length,
6758                                                  loc1->watchpoint_type,
6759                                                  w1->cond_exp.get ()))
6760       || (w2->cond_exp
6761           && target_can_accel_watchpoint_condition (loc2->address, 
6762                                                     loc2->length,
6763                                                     loc2->watchpoint_type,
6764                                                     w2->cond_exp.get ())))
6765     return 0;
6766
6767   /* Note that this checks the owner's type, not the location's.  In
6768      case the target does not support read watchpoints, but does
6769      support access watchpoints, we'll have bp_read_watchpoint
6770      watchpoints with hw_access locations.  Those should be considered
6771      duplicates of hw_read locations.  The hw_read locations will
6772      become hw_access locations later.  */
6773   return (loc1->owner->type == loc2->owner->type
6774           && loc1->pspace->aspace == loc2->pspace->aspace
6775           && loc1->address == loc2->address
6776           && loc1->length == loc2->length);
6777 }
6778
6779 /* See breakpoint.h.  */
6780
6781 int
6782 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
6783                           const address_space *aspace2, CORE_ADDR addr2)
6784 {
6785   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6786            || aspace1 == aspace2)
6787           && addr1 == addr2);
6788 }
6789
6790 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6791    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6792    matches ASPACE2.  On targets that have global breakpoints, the address
6793    space doesn't really matter.  */
6794
6795 static int
6796 breakpoint_address_match_range (const address_space *aspace1,
6797                                 CORE_ADDR addr1,
6798                                 int len1, const address_space *aspace2,
6799                                 CORE_ADDR addr2)
6800 {
6801   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6802            || aspace1 == aspace2)
6803           && addr2 >= addr1 && addr2 < addr1 + len1);
6804 }
6805
6806 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6807    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6808    matches the breakpoint's address space.  On targets that have global
6809    breakpoints, the address space doesn't really matter.  */
6810
6811 static int
6812 breakpoint_location_address_match (struct bp_location *bl,
6813                                    const address_space *aspace,
6814                                    CORE_ADDR addr)
6815 {
6816   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6817                                     aspace, addr)
6818           || (bl->length
6819               && breakpoint_address_match_range (bl->pspace->aspace,
6820                                                  bl->address, bl->length,
6821                                                  aspace, addr)));
6822 }
6823
6824 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
6825    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
6826    match happens only if ASPACE matches the breakpoint's address
6827    space.  On targets that have global breakpoints, the address space
6828    doesn't really matter.  */
6829
6830 static int
6831 breakpoint_location_address_range_overlap (struct bp_location *bl,
6832                                            const address_space *aspace,
6833                                            CORE_ADDR addr, int len)
6834 {
6835   if (gdbarch_has_global_breakpoints (target_gdbarch ())
6836       || bl->pspace->aspace == aspace)
6837     {
6838       int bl_len = bl->length != 0 ? bl->length : 1;
6839
6840       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
6841         return 1;
6842     }
6843   return 0;
6844 }
6845
6846 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6847    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6848    true, otherwise returns false.  */
6849
6850 static int
6851 tracepoint_locations_match (struct bp_location *loc1,
6852                             struct bp_location *loc2)
6853 {
6854   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6855     /* Since tracepoint locations are never duplicated with others', tracepoint
6856        locations at the same address of different tracepoints are regarded as
6857        different locations.  */
6858     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6859   else
6860     return 0;
6861 }
6862
6863 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6864    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6865    represent the same location.  */
6866
6867 static int
6868 breakpoint_locations_match (struct bp_location *loc1, 
6869                             struct bp_location *loc2)
6870 {
6871   int hw_point1, hw_point2;
6872
6873   /* Both of them must not be in moribund_locations.  */
6874   gdb_assert (loc1->owner != NULL);
6875   gdb_assert (loc2->owner != NULL);
6876
6877   hw_point1 = is_hardware_watchpoint (loc1->owner);
6878   hw_point2 = is_hardware_watchpoint (loc2->owner);
6879
6880   if (hw_point1 != hw_point2)
6881     return 0;
6882   else if (hw_point1)
6883     return watchpoint_locations_match (loc1, loc2);
6884   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6885     return tracepoint_locations_match (loc1, loc2);
6886   else
6887     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6888     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6889                                      loc2->pspace->aspace, loc2->address)
6890             && loc1->length == loc2->length);
6891 }
6892
6893 static void
6894 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6895                                int bnum, int have_bnum)
6896 {
6897   /* The longest string possibly returned by hex_string_custom
6898      is 50 chars.  These must be at least that big for safety.  */
6899   char astr1[64];
6900   char astr2[64];
6901
6902   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6903   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6904   if (have_bnum)
6905     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6906              bnum, astr1, astr2);
6907   else
6908     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6909 }
6910
6911 /* Adjust a breakpoint's address to account for architectural
6912    constraints on breakpoint placement.  Return the adjusted address.
6913    Note: Very few targets require this kind of adjustment.  For most
6914    targets, this function is simply the identity function.  */
6915
6916 static CORE_ADDR
6917 adjust_breakpoint_address (struct gdbarch *gdbarch,
6918                            CORE_ADDR bpaddr, enum bptype bptype)
6919 {
6920   if (bptype == bp_watchpoint
6921       || bptype == bp_hardware_watchpoint
6922       || bptype == bp_read_watchpoint
6923       || bptype == bp_access_watchpoint
6924       || bptype == bp_catchpoint)
6925     {
6926       /* Watchpoints and the various bp_catch_* eventpoints should not
6927          have their addresses modified.  */
6928       return bpaddr;
6929     }
6930   else if (bptype == bp_single_step)
6931     {
6932       /* Single-step breakpoints should not have their addresses
6933          modified.  If there's any architectural constrain that
6934          applies to this address, then it should have already been
6935          taken into account when the breakpoint was created in the
6936          first place.  If we didn't do this, stepping through e.g.,
6937          Thumb-2 IT blocks would break.  */
6938       return bpaddr;
6939     }
6940   else
6941     {
6942       CORE_ADDR adjusted_bpaddr = bpaddr;
6943
6944       if (gdbarch_adjust_breakpoint_address_p (gdbarch))
6945         {
6946           /* Some targets have architectural constraints on the placement
6947              of breakpoint instructions.  Obtain the adjusted address.  */
6948           adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6949         }
6950
6951       adjusted_bpaddr = address_significant (gdbarch, adjusted_bpaddr);
6952
6953       /* An adjusted breakpoint address can significantly alter
6954          a user's expectations.  Print a warning if an adjustment
6955          is required.  */
6956       if (adjusted_bpaddr != bpaddr)
6957         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6958
6959       return adjusted_bpaddr;
6960     }
6961 }
6962
6963 bp_location::bp_location (const bp_location_ops *ops, breakpoint *owner)
6964 {
6965   bp_location *loc = this;
6966
6967   gdb_assert (ops != NULL);
6968
6969   loc->ops = ops;
6970   loc->owner = owner;
6971   loc->cond_bytecode = NULL;
6972   loc->shlib_disabled = 0;
6973   loc->enabled = 1;
6974
6975   switch (owner->type)
6976     {
6977     case bp_breakpoint:
6978     case bp_single_step:
6979     case bp_until:
6980     case bp_finish:
6981     case bp_longjmp:
6982     case bp_longjmp_resume:
6983     case bp_longjmp_call_dummy:
6984     case bp_exception:
6985     case bp_exception_resume:
6986     case bp_step_resume:
6987     case bp_hp_step_resume:
6988     case bp_watchpoint_scope:
6989     case bp_call_dummy:
6990     case bp_std_terminate:
6991     case bp_shlib_event:
6992     case bp_thread_event:
6993     case bp_overlay_event:
6994     case bp_jit_event:
6995     case bp_longjmp_master:
6996     case bp_std_terminate_master:
6997     case bp_exception_master:
6998     case bp_gnu_ifunc_resolver:
6999     case bp_gnu_ifunc_resolver_return:
7000     case bp_dprintf:
7001       loc->loc_type = bp_loc_software_breakpoint;
7002       mark_breakpoint_location_modified (loc);
7003       break;
7004     case bp_hardware_breakpoint:
7005       loc->loc_type = bp_loc_hardware_breakpoint;
7006       mark_breakpoint_location_modified (loc);
7007       break;
7008     case bp_hardware_watchpoint:
7009     case bp_read_watchpoint:
7010     case bp_access_watchpoint:
7011       loc->loc_type = bp_loc_hardware_watchpoint;
7012       break;
7013     case bp_watchpoint:
7014     case bp_catchpoint:
7015     case bp_tracepoint:
7016     case bp_fast_tracepoint:
7017     case bp_static_tracepoint:
7018       loc->loc_type = bp_loc_other;
7019       break;
7020     default:
7021       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7022     }
7023
7024   loc->refc = 1;
7025 }
7026
7027 /* Allocate a struct bp_location.  */
7028
7029 static struct bp_location *
7030 allocate_bp_location (struct breakpoint *bpt)
7031 {
7032   return bpt->ops->allocate_location (bpt);
7033 }
7034
7035 static void
7036 free_bp_location (struct bp_location *loc)
7037 {
7038   loc->ops->dtor (loc);
7039   delete loc;
7040 }
7041
7042 /* Increment reference count.  */
7043
7044 static void
7045 incref_bp_location (struct bp_location *bl)
7046 {
7047   ++bl->refc;
7048 }
7049
7050 /* Decrement reference count.  If the reference count reaches 0,
7051    destroy the bp_location.  Sets *BLP to NULL.  */
7052
7053 static void
7054 decref_bp_location (struct bp_location **blp)
7055 {
7056   gdb_assert ((*blp)->refc > 0);
7057
7058   if (--(*blp)->refc == 0)
7059     free_bp_location (*blp);
7060   *blp = NULL;
7061 }
7062
7063 /* Add breakpoint B at the end of the global breakpoint chain.  */
7064
7065 static breakpoint *
7066 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7067 {
7068   struct breakpoint *b1;
7069   struct breakpoint *result = b.get ();
7070
7071   /* Add this breakpoint to the end of the chain so that a list of
7072      breakpoints will come out in order of increasing numbers.  */
7073
7074   b1 = breakpoint_chain;
7075   if (b1 == 0)
7076     breakpoint_chain = b.release ();
7077   else
7078     {
7079       while (b1->next)
7080         b1 = b1->next;
7081       b1->next = b.release ();
7082     }
7083
7084   return result;
7085 }
7086
7087 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7088
7089 static void
7090 init_raw_breakpoint_without_location (struct breakpoint *b,
7091                                       struct gdbarch *gdbarch,
7092                                       enum bptype bptype,
7093                                       const struct breakpoint_ops *ops)
7094 {
7095   gdb_assert (ops != NULL);
7096
7097   b->ops = ops;
7098   b->type = bptype;
7099   b->gdbarch = gdbarch;
7100   b->language = current_language->la_language;
7101   b->input_radix = input_radix;
7102   b->related_breakpoint = b;
7103 }
7104
7105 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7106    that has type BPTYPE and has no locations as yet.  */
7107
7108 static struct breakpoint *
7109 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7110                                      enum bptype bptype,
7111                                      const struct breakpoint_ops *ops)
7112 {
7113   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7114
7115   init_raw_breakpoint_without_location (b.get (), gdbarch, bptype, ops);
7116   return add_to_breakpoint_chain (std::move (b));
7117 }
7118
7119 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7120    resolutions should be made as the user specified the location explicitly
7121    enough.  */
7122
7123 static void
7124 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7125 {
7126   gdb_assert (loc->owner != NULL);
7127
7128   if (loc->owner->type == bp_breakpoint
7129       || loc->owner->type == bp_hardware_breakpoint
7130       || is_tracepoint (loc->owner))
7131     {
7132       const char *function_name;
7133
7134       if (loc->msymbol != NULL
7135           && (MSYMBOL_TYPE (loc->msymbol) == mst_text_gnu_ifunc
7136               || MSYMBOL_TYPE (loc->msymbol) == mst_data_gnu_ifunc)
7137           && !explicit_loc)
7138         {
7139           struct breakpoint *b = loc->owner;
7140
7141           function_name = MSYMBOL_LINKAGE_NAME (loc->msymbol);
7142
7143           if (b->type == bp_breakpoint && b->loc == loc
7144               && loc->next == NULL && b->related_breakpoint == b)
7145             {
7146               /* Create only the whole new breakpoint of this type but do not
7147                  mess more complicated breakpoints with multiple locations.  */
7148               b->type = bp_gnu_ifunc_resolver;
7149               /* Remember the resolver's address for use by the return
7150                  breakpoint.  */
7151               loc->related_address = loc->address;
7152             }
7153         }
7154       else
7155         find_pc_partial_function (loc->address, &function_name, NULL, NULL);
7156
7157       if (function_name)
7158         loc->function_name = xstrdup (function_name);
7159     }
7160 }
7161
7162 /* Attempt to determine architecture of location identified by SAL.  */
7163 struct gdbarch *
7164 get_sal_arch (struct symtab_and_line sal)
7165 {
7166   if (sal.section)
7167     return get_objfile_arch (sal.section->objfile);
7168   if (sal.symtab)
7169     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7170
7171   return NULL;
7172 }
7173
7174 /* Low level routine for partially initializing a breakpoint of type
7175    BPTYPE.  The newly created breakpoint's address, section, source
7176    file name, and line number are provided by SAL.
7177
7178    It is expected that the caller will complete the initialization of
7179    the newly created breakpoint struct as well as output any status
7180    information regarding the creation of a new breakpoint.  */
7181
7182 static void
7183 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7184                      struct symtab_and_line sal, enum bptype bptype,
7185                      const struct breakpoint_ops *ops)
7186 {
7187   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7188
7189   add_location_to_breakpoint (b, &sal);
7190
7191   if (bptype != bp_catchpoint)
7192     gdb_assert (sal.pspace != NULL);
7193
7194   /* Store the program space that was used to set the breakpoint,
7195      except for ordinary breakpoints, which are independent of the
7196      program space.  */
7197   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7198     b->pspace = sal.pspace;
7199 }
7200
7201 /* set_raw_breakpoint is a low level routine for allocating and
7202    partially initializing a breakpoint of type BPTYPE.  The newly
7203    created breakpoint's address, section, source file name, and line
7204    number are provided by SAL.  The newly created and partially
7205    initialized breakpoint is added to the breakpoint chain and
7206    is also returned as the value of this function.
7207
7208    It is expected that the caller will complete the initialization of
7209    the newly created breakpoint struct as well as output any status
7210    information regarding the creation of a new breakpoint.  In
7211    particular, set_raw_breakpoint does NOT set the breakpoint
7212    number!  Care should be taken to not allow an error to occur
7213    prior to completing the initialization of the breakpoint.  If this
7214    should happen, a bogus breakpoint will be left on the chain.  */
7215
7216 struct breakpoint *
7217 set_raw_breakpoint (struct gdbarch *gdbarch,
7218                     struct symtab_and_line sal, enum bptype bptype,
7219                     const struct breakpoint_ops *ops)
7220 {
7221   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7222
7223   init_raw_breakpoint (b.get (), gdbarch, sal, bptype, ops);
7224   return add_to_breakpoint_chain (std::move (b));
7225 }
7226
7227 /* Call this routine when stepping and nexting to enable a breakpoint
7228    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7229    initiated the operation.  */
7230
7231 void
7232 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7233 {
7234   struct breakpoint *b, *b_tmp;
7235   int thread = tp->global_num;
7236
7237   /* To avoid having to rescan all objfile symbols at every step,
7238      we maintain a list of continually-inserted but always disabled
7239      longjmp "master" breakpoints.  Here, we simply create momentary
7240      clones of those and enable them for the requested thread.  */
7241   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7242     if (b->pspace == current_program_space
7243         && (b->type == bp_longjmp_master
7244             || b->type == bp_exception_master))
7245       {
7246         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7247         struct breakpoint *clone;
7248
7249         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7250            after their removal.  */
7251         clone = momentary_breakpoint_from_master (b, type,
7252                                                   &momentary_breakpoint_ops, 1);
7253         clone->thread = thread;
7254       }
7255
7256   tp->initiating_frame = frame;
7257 }
7258
7259 /* Delete all longjmp breakpoints from THREAD.  */
7260 void
7261 delete_longjmp_breakpoint (int thread)
7262 {
7263   struct breakpoint *b, *b_tmp;
7264
7265   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7266     if (b->type == bp_longjmp || b->type == bp_exception)
7267       {
7268         if (b->thread == thread)
7269           delete_breakpoint (b);
7270       }
7271 }
7272
7273 void
7274 delete_longjmp_breakpoint_at_next_stop (int thread)
7275 {
7276   struct breakpoint *b, *b_tmp;
7277
7278   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7279     if (b->type == bp_longjmp || b->type == bp_exception)
7280       {
7281         if (b->thread == thread)
7282           b->disposition = disp_del_at_next_stop;
7283       }
7284 }
7285
7286 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7287    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7288    pointer to any of them.  Return NULL if this system cannot place longjmp
7289    breakpoints.  */
7290
7291 struct breakpoint *
7292 set_longjmp_breakpoint_for_call_dummy (void)
7293 {
7294   struct breakpoint *b, *retval = NULL;
7295
7296   ALL_BREAKPOINTS (b)
7297     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7298       {
7299         struct breakpoint *new_b;
7300
7301         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7302                                                   &momentary_breakpoint_ops,
7303                                                   1);
7304         new_b->thread = inferior_thread ()->global_num;
7305
7306         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7307
7308         gdb_assert (new_b->related_breakpoint == new_b);
7309         if (retval == NULL)
7310           retval = new_b;
7311         new_b->related_breakpoint = retval;
7312         while (retval->related_breakpoint != new_b->related_breakpoint)
7313           retval = retval->related_breakpoint;
7314         retval->related_breakpoint = new_b;
7315       }
7316
7317   return retval;
7318 }
7319
7320 /* Verify all existing dummy frames and their associated breakpoints for
7321    TP.  Remove those which can no longer be found in the current frame
7322    stack.
7323
7324    You should call this function only at places where it is safe to currently
7325    unwind the whole stack.  Failed stack unwind would discard live dummy
7326    frames.  */
7327
7328 void
7329 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7330 {
7331   struct breakpoint *b, *b_tmp;
7332
7333   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7334     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7335       {
7336         struct breakpoint *dummy_b = b->related_breakpoint;
7337
7338         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7339           dummy_b = dummy_b->related_breakpoint;
7340         if (dummy_b->type != bp_call_dummy
7341             || frame_find_by_id (dummy_b->frame_id) != NULL)
7342           continue;
7343         
7344         dummy_frame_discard (dummy_b->frame_id, tp);
7345
7346         while (b->related_breakpoint != b)
7347           {
7348             if (b_tmp == b->related_breakpoint)
7349               b_tmp = b->related_breakpoint->next;
7350             delete_breakpoint (b->related_breakpoint);
7351           }
7352         delete_breakpoint (b);
7353       }
7354 }
7355
7356 void
7357 enable_overlay_breakpoints (void)
7358 {
7359   struct breakpoint *b;
7360
7361   ALL_BREAKPOINTS (b)
7362     if (b->type == bp_overlay_event)
7363     {
7364       b->enable_state = bp_enabled;
7365       update_global_location_list (UGLL_MAY_INSERT);
7366       overlay_events_enabled = 1;
7367     }
7368 }
7369
7370 void
7371 disable_overlay_breakpoints (void)
7372 {
7373   struct breakpoint *b;
7374
7375   ALL_BREAKPOINTS (b)
7376     if (b->type == bp_overlay_event)
7377     {
7378       b->enable_state = bp_disabled;
7379       update_global_location_list (UGLL_DONT_INSERT);
7380       overlay_events_enabled = 0;
7381     }
7382 }
7383
7384 /* Set an active std::terminate breakpoint for each std::terminate
7385    master breakpoint.  */
7386 void
7387 set_std_terminate_breakpoint (void)
7388 {
7389   struct breakpoint *b, *b_tmp;
7390
7391   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7392     if (b->pspace == current_program_space
7393         && b->type == bp_std_terminate_master)
7394       {
7395         momentary_breakpoint_from_master (b, bp_std_terminate,
7396                                           &momentary_breakpoint_ops, 1);
7397       }
7398 }
7399
7400 /* Delete all the std::terminate breakpoints.  */
7401 void
7402 delete_std_terminate_breakpoint (void)
7403 {
7404   struct breakpoint *b, *b_tmp;
7405
7406   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7407     if (b->type == bp_std_terminate)
7408       delete_breakpoint (b);
7409 }
7410
7411 struct breakpoint *
7412 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7413 {
7414   struct breakpoint *b;
7415
7416   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7417                                   &internal_breakpoint_ops);
7418
7419   b->enable_state = bp_enabled;
7420   /* location has to be used or breakpoint_re_set will delete me.  */
7421   b->location = new_address_location (b->loc->address, NULL, 0);
7422
7423   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7424
7425   return b;
7426 }
7427
7428 struct lang_and_radix
7429   {
7430     enum language lang;
7431     int radix;
7432   };
7433
7434 /* Create a breakpoint for JIT code registration and unregistration.  */
7435
7436 struct breakpoint *
7437 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7438 {
7439   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7440                                      &internal_breakpoint_ops);
7441 }
7442
7443 /* Remove JIT code registration and unregistration breakpoint(s).  */
7444
7445 void
7446 remove_jit_event_breakpoints (void)
7447 {
7448   struct breakpoint *b, *b_tmp;
7449
7450   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7451     if (b->type == bp_jit_event
7452         && b->loc->pspace == current_program_space)
7453       delete_breakpoint (b);
7454 }
7455
7456 void
7457 remove_solib_event_breakpoints (void)
7458 {
7459   struct breakpoint *b, *b_tmp;
7460
7461   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7462     if (b->type == bp_shlib_event
7463         && b->loc->pspace == current_program_space)
7464       delete_breakpoint (b);
7465 }
7466
7467 /* See breakpoint.h.  */
7468
7469 void
7470 remove_solib_event_breakpoints_at_next_stop (void)
7471 {
7472   struct breakpoint *b, *b_tmp;
7473
7474   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7475     if (b->type == bp_shlib_event
7476         && b->loc->pspace == current_program_space)
7477       b->disposition = disp_del_at_next_stop;
7478 }
7479
7480 /* Helper for create_solib_event_breakpoint /
7481    create_and_insert_solib_event_breakpoint.  Allows specifying which
7482    INSERT_MODE to pass through to update_global_location_list.  */
7483
7484 static struct breakpoint *
7485 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7486                                  enum ugll_insert_mode insert_mode)
7487 {
7488   struct breakpoint *b;
7489
7490   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7491                                   &internal_breakpoint_ops);
7492   update_global_location_list_nothrow (insert_mode);
7493   return b;
7494 }
7495
7496 struct breakpoint *
7497 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7498 {
7499   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7500 }
7501
7502 /* See breakpoint.h.  */
7503
7504 struct breakpoint *
7505 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7506 {
7507   struct breakpoint *b;
7508
7509   /* Explicitly tell update_global_location_list to insert
7510      locations.  */
7511   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7512   if (!b->loc->inserted)
7513     {
7514       delete_breakpoint (b);
7515       return NULL;
7516     }
7517   return b;
7518 }
7519
7520 /* Disable any breakpoints that are on code in shared libraries.  Only
7521    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7522
7523 void
7524 disable_breakpoints_in_shlibs (void)
7525 {
7526   struct bp_location *loc, **locp_tmp;
7527
7528   ALL_BP_LOCATIONS (loc, locp_tmp)
7529   {
7530     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7531     struct breakpoint *b = loc->owner;
7532
7533     /* We apply the check to all breakpoints, including disabled for
7534        those with loc->duplicate set.  This is so that when breakpoint
7535        becomes enabled, or the duplicate is removed, gdb will try to
7536        insert all breakpoints.  If we don't set shlib_disabled here,
7537        we'll try to insert those breakpoints and fail.  */
7538     if (((b->type == bp_breakpoint)
7539          || (b->type == bp_jit_event)
7540          || (b->type == bp_hardware_breakpoint)
7541          || (is_tracepoint (b)))
7542         && loc->pspace == current_program_space
7543         && !loc->shlib_disabled
7544         && solib_name_from_address (loc->pspace, loc->address)
7545         )
7546       {
7547         loc->shlib_disabled = 1;
7548       }
7549   }
7550 }
7551
7552 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7553    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7554    disabled ones can just stay disabled.  */
7555
7556 static void
7557 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7558 {
7559   struct bp_location *loc, **locp_tmp;
7560   int disabled_shlib_breaks = 0;
7561
7562   ALL_BP_LOCATIONS (loc, locp_tmp)
7563   {
7564     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7565     struct breakpoint *b = loc->owner;
7566
7567     if (solib->pspace == loc->pspace
7568         && !loc->shlib_disabled
7569         && (((b->type == bp_breakpoint
7570               || b->type == bp_jit_event
7571               || b->type == bp_hardware_breakpoint)
7572              && (loc->loc_type == bp_loc_hardware_breakpoint
7573                  || loc->loc_type == bp_loc_software_breakpoint))
7574             || is_tracepoint (b))
7575         && solib_contains_address_p (solib, loc->address))
7576       {
7577         loc->shlib_disabled = 1;
7578         /* At this point, we cannot rely on remove_breakpoint
7579            succeeding so we must mark the breakpoint as not inserted
7580            to prevent future errors occurring in remove_breakpoints.  */
7581         loc->inserted = 0;
7582
7583         /* This may cause duplicate notifications for the same breakpoint.  */
7584         gdb::observers::breakpoint_modified.notify (b);
7585
7586         if (!disabled_shlib_breaks)
7587           {
7588             target_terminal::ours_for_output ();
7589             warning (_("Temporarily disabling breakpoints "
7590                        "for unloaded shared library \"%s\""),
7591                      solib->so_name);
7592           }
7593         disabled_shlib_breaks = 1;
7594       }
7595   }
7596 }
7597
7598 /* Disable any breakpoints and tracepoints in OBJFILE upon
7599    notification of free_objfile.  Only apply to enabled breakpoints,
7600    disabled ones can just stay disabled.  */
7601
7602 static void
7603 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7604 {
7605   struct breakpoint *b;
7606
7607   if (objfile == NULL)
7608     return;
7609
7610   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7611      managed by the user with add-symbol-file/remove-symbol-file.
7612      Similarly to how breakpoints in shared libraries are handled in
7613      response to "nosharedlibrary", mark breakpoints in such modules
7614      shlib_disabled so they end up uninserted on the next global
7615      location list update.  Shared libraries not loaded by the user
7616      aren't handled here -- they're already handled in
7617      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7618      solib_unloaded observer.  We skip objfiles that are not
7619      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7620      main objfile).  */
7621   if ((objfile->flags & OBJF_SHARED) == 0
7622       || (objfile->flags & OBJF_USERLOADED) == 0)
7623     return;
7624
7625   ALL_BREAKPOINTS (b)
7626     {
7627       struct bp_location *loc;
7628       int bp_modified = 0;
7629
7630       if (!is_breakpoint (b) && !is_tracepoint (b))
7631         continue;
7632
7633       for (loc = b->loc; loc != NULL; loc = loc->next)
7634         {
7635           CORE_ADDR loc_addr = loc->address;
7636
7637           if (loc->loc_type != bp_loc_hardware_breakpoint
7638               && loc->loc_type != bp_loc_software_breakpoint)
7639             continue;
7640
7641           if (loc->shlib_disabled != 0)
7642             continue;
7643
7644           if (objfile->pspace != loc->pspace)
7645             continue;
7646
7647           if (loc->loc_type != bp_loc_hardware_breakpoint
7648               && loc->loc_type != bp_loc_software_breakpoint)
7649             continue;
7650
7651           if (is_addr_in_objfile (loc_addr, objfile))
7652             {
7653               loc->shlib_disabled = 1;
7654               /* At this point, we don't know whether the object was
7655                  unmapped from the inferior or not, so leave the
7656                  inserted flag alone.  We'll handle failure to
7657                  uninsert quietly, in case the object was indeed
7658                  unmapped.  */
7659
7660               mark_breakpoint_location_modified (loc);
7661
7662               bp_modified = 1;
7663             }
7664         }
7665
7666       if (bp_modified)
7667         gdb::observers::breakpoint_modified.notify (b);
7668     }
7669 }
7670
7671 /* FORK & VFORK catchpoints.  */
7672
7673 /* An instance of this type is used to represent a fork or vfork
7674    catchpoint.  A breakpoint is really of this type iff its ops pointer points
7675    to CATCH_FORK_BREAKPOINT_OPS.  */
7676
7677 struct fork_catchpoint : public breakpoint
7678 {
7679   /* Process id of a child process whose forking triggered this
7680      catchpoint.  This field is only valid immediately after this
7681      catchpoint has triggered.  */
7682   ptid_t forked_inferior_pid;
7683 };
7684
7685 /* Implement the "insert" breakpoint_ops method for fork
7686    catchpoints.  */
7687
7688 static int
7689 insert_catch_fork (struct bp_location *bl)
7690 {
7691   return target_insert_fork_catchpoint (inferior_ptid.pid ());
7692 }
7693
7694 /* Implement the "remove" breakpoint_ops method for fork
7695    catchpoints.  */
7696
7697 static int
7698 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
7699 {
7700   return target_remove_fork_catchpoint (inferior_ptid.pid ());
7701 }
7702
7703 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7704    catchpoints.  */
7705
7706 static int
7707 breakpoint_hit_catch_fork (const struct bp_location *bl,
7708                            const address_space *aspace, CORE_ADDR bp_addr,
7709                            const struct target_waitstatus *ws)
7710 {
7711   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7712
7713   if (ws->kind != TARGET_WAITKIND_FORKED)
7714     return 0;
7715
7716   c->forked_inferior_pid = ws->value.related_pid;
7717   return 1;
7718 }
7719
7720 /* Implement the "print_it" breakpoint_ops method for fork
7721    catchpoints.  */
7722
7723 static enum print_stop_action
7724 print_it_catch_fork (bpstat bs)
7725 {
7726   struct ui_out *uiout = current_uiout;
7727   struct breakpoint *b = bs->breakpoint_at;
7728   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7729
7730   annotate_catchpoint (b->number);
7731   maybe_print_thread_hit_breakpoint (uiout);
7732   if (b->disposition == disp_del)
7733     uiout->text ("Temporary catchpoint ");
7734   else
7735     uiout->text ("Catchpoint ");
7736   if (uiout->is_mi_like_p ())
7737     {
7738       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
7739       uiout->field_string ("disp", bpdisp_text (b->disposition));
7740     }
7741   uiout->field_int ("bkptno", b->number);
7742   uiout->text (" (forked process ");
7743   uiout->field_int ("newpid", c->forked_inferior_pid.pid ());
7744   uiout->text ("), ");
7745   return PRINT_SRC_AND_LOC;
7746 }
7747
7748 /* Implement the "print_one" breakpoint_ops method for fork
7749    catchpoints.  */
7750
7751 static void
7752 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7753 {
7754   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7755   struct value_print_options opts;
7756   struct ui_out *uiout = current_uiout;
7757
7758   get_user_print_options (&opts);
7759
7760   /* Field 4, the address, is omitted (which makes the columns not
7761      line up too nicely with the headers, but the effect is relatively
7762      readable).  */
7763   if (opts.addressprint)
7764     uiout->field_skip ("addr");
7765   annotate_field (5);
7766   uiout->text ("fork");
7767   if (c->forked_inferior_pid != null_ptid)
7768     {
7769       uiout->text (", process ");
7770       uiout->field_int ("what", c->forked_inferior_pid.pid ());
7771       uiout->spaces (1);
7772     }
7773
7774   if (uiout->is_mi_like_p ())
7775     uiout->field_string ("catch-type", "fork");
7776 }
7777
7778 /* Implement the "print_mention" breakpoint_ops method for fork
7779    catchpoints.  */
7780
7781 static void
7782 print_mention_catch_fork (struct breakpoint *b)
7783 {
7784   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7785 }
7786
7787 /* Implement the "print_recreate" breakpoint_ops method for fork
7788    catchpoints.  */
7789
7790 static void
7791 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7792 {
7793   fprintf_unfiltered (fp, "catch fork");
7794   print_recreate_thread (b, fp);
7795 }
7796
7797 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7798
7799 static struct breakpoint_ops catch_fork_breakpoint_ops;
7800
7801 /* Implement the "insert" breakpoint_ops method for vfork
7802    catchpoints.  */
7803
7804 static int
7805 insert_catch_vfork (struct bp_location *bl)
7806 {
7807   return target_insert_vfork_catchpoint (inferior_ptid.pid ());
7808 }
7809
7810 /* Implement the "remove" breakpoint_ops method for vfork
7811    catchpoints.  */
7812
7813 static int
7814 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
7815 {
7816   return target_remove_vfork_catchpoint (inferior_ptid.pid ());
7817 }
7818
7819 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7820    catchpoints.  */
7821
7822 static int
7823 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7824                             const address_space *aspace, CORE_ADDR bp_addr,
7825                             const struct target_waitstatus *ws)
7826 {
7827   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7828
7829   if (ws->kind != TARGET_WAITKIND_VFORKED)
7830     return 0;
7831
7832   c->forked_inferior_pid = ws->value.related_pid;
7833   return 1;
7834 }
7835
7836 /* Implement the "print_it" breakpoint_ops method for vfork
7837    catchpoints.  */
7838
7839 static enum print_stop_action
7840 print_it_catch_vfork (bpstat bs)
7841 {
7842   struct ui_out *uiout = current_uiout;
7843   struct breakpoint *b = bs->breakpoint_at;
7844   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7845
7846   annotate_catchpoint (b->number);
7847   maybe_print_thread_hit_breakpoint (uiout);
7848   if (b->disposition == disp_del)
7849     uiout->text ("Temporary catchpoint ");
7850   else
7851     uiout->text ("Catchpoint ");
7852   if (uiout->is_mi_like_p ())
7853     {
7854       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
7855       uiout->field_string ("disp", bpdisp_text (b->disposition));
7856     }
7857   uiout->field_int ("bkptno", b->number);
7858   uiout->text (" (vforked process ");
7859   uiout->field_int ("newpid", c->forked_inferior_pid.pid ());
7860   uiout->text ("), ");
7861   return PRINT_SRC_AND_LOC;
7862 }
7863
7864 /* Implement the "print_one" breakpoint_ops method for vfork
7865    catchpoints.  */
7866
7867 static void
7868 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7869 {
7870   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7871   struct value_print_options opts;
7872   struct ui_out *uiout = current_uiout;
7873
7874   get_user_print_options (&opts);
7875   /* Field 4, the address, is omitted (which makes the columns not
7876      line up too nicely with the headers, but the effect is relatively
7877      readable).  */
7878   if (opts.addressprint)
7879     uiout->field_skip ("addr");
7880   annotate_field (5);
7881   uiout->text ("vfork");
7882   if (c->forked_inferior_pid != null_ptid)
7883     {
7884       uiout->text (", process ");
7885       uiout->field_int ("what", c->forked_inferior_pid.pid ());
7886       uiout->spaces (1);
7887     }
7888
7889   if (uiout->is_mi_like_p ())
7890     uiout->field_string ("catch-type", "vfork");
7891 }
7892
7893 /* Implement the "print_mention" breakpoint_ops method for vfork
7894    catchpoints.  */
7895
7896 static void
7897 print_mention_catch_vfork (struct breakpoint *b)
7898 {
7899   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7900 }
7901
7902 /* Implement the "print_recreate" breakpoint_ops method for vfork
7903    catchpoints.  */
7904
7905 static void
7906 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7907 {
7908   fprintf_unfiltered (fp, "catch vfork");
7909   print_recreate_thread (b, fp);
7910 }
7911
7912 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7913
7914 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7915
7916 /* An instance of this type is used to represent an solib catchpoint.
7917    A breakpoint is really of this type iff its ops pointer points to
7918    CATCH_SOLIB_BREAKPOINT_OPS.  */
7919
7920 struct solib_catchpoint : public breakpoint
7921 {
7922   ~solib_catchpoint () override;
7923
7924   /* True for "catch load", false for "catch unload".  */
7925   unsigned char is_load;
7926
7927   /* Regular expression to match, if any.  COMPILED is only valid when
7928      REGEX is non-NULL.  */
7929   char *regex;
7930   std::unique_ptr<compiled_regex> compiled;
7931 };
7932
7933 solib_catchpoint::~solib_catchpoint ()
7934 {
7935   xfree (this->regex);
7936 }
7937
7938 static int
7939 insert_catch_solib (struct bp_location *ignore)
7940 {
7941   return 0;
7942 }
7943
7944 static int
7945 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
7946 {
7947   return 0;
7948 }
7949
7950 static int
7951 breakpoint_hit_catch_solib (const struct bp_location *bl,
7952                             const address_space *aspace,
7953                             CORE_ADDR bp_addr,
7954                             const struct target_waitstatus *ws)
7955 {
7956   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7957   struct breakpoint *other;
7958
7959   if (ws->kind == TARGET_WAITKIND_LOADED)
7960     return 1;
7961
7962   ALL_BREAKPOINTS (other)
7963   {
7964     struct bp_location *other_bl;
7965
7966     if (other == bl->owner)
7967       continue;
7968
7969     if (other->type != bp_shlib_event)
7970       continue;
7971
7972     if (self->pspace != NULL && other->pspace != self->pspace)
7973       continue;
7974
7975     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7976       {
7977         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7978           return 1;
7979       }
7980   }
7981
7982   return 0;
7983 }
7984
7985 static void
7986 check_status_catch_solib (struct bpstats *bs)
7987 {
7988   struct solib_catchpoint *self
7989     = (struct solib_catchpoint *) bs->breakpoint_at;
7990
7991   if (self->is_load)
7992     {
7993       for (so_list *iter : current_program_space->added_solibs)
7994         {
7995           if (!self->regex
7996               || self->compiled->exec (iter->so_name, 0, NULL, 0) == 0)
7997             return;
7998         }
7999     }
8000   else
8001     {
8002       for (const std::string &iter : current_program_space->deleted_solibs)
8003         {
8004           if (!self->regex
8005               || self->compiled->exec (iter.c_str (), 0, NULL, 0) == 0)
8006             return;
8007         }
8008     }
8009
8010   bs->stop = 0;
8011   bs->print_it = print_it_noop;
8012 }
8013
8014 static enum print_stop_action
8015 print_it_catch_solib (bpstat bs)
8016 {
8017   struct breakpoint *b = bs->breakpoint_at;
8018   struct ui_out *uiout = current_uiout;
8019
8020   annotate_catchpoint (b->number);
8021   maybe_print_thread_hit_breakpoint (uiout);
8022   if (b->disposition == disp_del)
8023     uiout->text ("Temporary catchpoint ");
8024   else
8025     uiout->text ("Catchpoint ");
8026   uiout->field_int ("bkptno", b->number);
8027   uiout->text ("\n");
8028   if (uiout->is_mi_like_p ())
8029     uiout->field_string ("disp", bpdisp_text (b->disposition));
8030   print_solib_event (1);
8031   return PRINT_SRC_AND_LOC;
8032 }
8033
8034 static void
8035 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8036 {
8037   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8038   struct value_print_options opts;
8039   struct ui_out *uiout = current_uiout;
8040
8041   get_user_print_options (&opts);
8042   /* Field 4, the address, is omitted (which makes the columns not
8043      line up too nicely with the headers, but the effect is relatively
8044      readable).  */
8045   if (opts.addressprint)
8046     {
8047       annotate_field (4);
8048       uiout->field_skip ("addr");
8049     }
8050
8051   std::string msg;
8052   annotate_field (5);
8053   if (self->is_load)
8054     {
8055       if (self->regex)
8056         msg = string_printf (_("load of library matching %s"), self->regex);
8057       else
8058         msg = _("load of library");
8059     }
8060   else
8061     {
8062       if (self->regex)
8063         msg = string_printf (_("unload of library matching %s"), self->regex);
8064       else
8065         msg = _("unload of library");
8066     }
8067   uiout->field_string ("what", msg);
8068
8069   if (uiout->is_mi_like_p ())
8070     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8071 }
8072
8073 static void
8074 print_mention_catch_solib (struct breakpoint *b)
8075 {
8076   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8077
8078   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8079                    self->is_load ? "load" : "unload");
8080 }
8081
8082 static void
8083 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8084 {
8085   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8086
8087   fprintf_unfiltered (fp, "%s %s",
8088                       b->disposition == disp_del ? "tcatch" : "catch",
8089                       self->is_load ? "load" : "unload");
8090   if (self->regex)
8091     fprintf_unfiltered (fp, " %s", self->regex);
8092   fprintf_unfiltered (fp, "\n");
8093 }
8094
8095 static struct breakpoint_ops catch_solib_breakpoint_ops;
8096
8097 /* Shared helper function (MI and CLI) for creating and installing
8098    a shared object event catchpoint.  If IS_LOAD is non-zero then
8099    the events to be caught are load events, otherwise they are
8100    unload events.  If IS_TEMP is non-zero the catchpoint is a
8101    temporary one.  If ENABLED is non-zero the catchpoint is
8102    created in an enabled state.  */
8103
8104 void
8105 add_solib_catchpoint (const char *arg, int is_load, int is_temp, int enabled)
8106 {
8107   struct gdbarch *gdbarch = get_current_arch ();
8108
8109   if (!arg)
8110     arg = "";
8111   arg = skip_spaces (arg);
8112
8113   std::unique_ptr<solib_catchpoint> c (new solib_catchpoint ());
8114
8115   if (*arg != '\0')
8116     {
8117       c->compiled.reset (new compiled_regex (arg, REG_NOSUB,
8118                                              _("Invalid regexp")));
8119       c->regex = xstrdup (arg);
8120     }
8121
8122   c->is_load = is_load;
8123   init_catchpoint (c.get (), gdbarch, is_temp, NULL,
8124                    &catch_solib_breakpoint_ops);
8125
8126   c->enable_state = enabled ? bp_enabled : bp_disabled;
8127
8128   install_breakpoint (0, std::move (c), 1);
8129 }
8130
8131 /* A helper function that does all the work for "catch load" and
8132    "catch unload".  */
8133
8134 static void
8135 catch_load_or_unload (const char *arg, int from_tty, int is_load,
8136                       struct cmd_list_element *command)
8137 {
8138   int tempflag;
8139   const int enabled = 1;
8140
8141   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8142
8143   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8144 }
8145
8146 static void
8147 catch_load_command_1 (const char *arg, int from_tty,
8148                       struct cmd_list_element *command)
8149 {
8150   catch_load_or_unload (arg, from_tty, 1, command);
8151 }
8152
8153 static void
8154 catch_unload_command_1 (const char *arg, int from_tty,
8155                         struct cmd_list_element *command)
8156 {
8157   catch_load_or_unload (arg, from_tty, 0, command);
8158 }
8159
8160 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8161    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8162    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8163    the breakpoint_ops structure associated to the catchpoint.  */
8164
8165 void
8166 init_catchpoint (struct breakpoint *b,
8167                  struct gdbarch *gdbarch, int tempflag,
8168                  const char *cond_string,
8169                  const struct breakpoint_ops *ops)
8170 {
8171   symtab_and_line sal;
8172   sal.pspace = current_program_space;
8173
8174   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8175
8176   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8177   b->disposition = tempflag ? disp_del : disp_donttouch;
8178 }
8179
8180 void
8181 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8182 {
8183   breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8184   set_breakpoint_number (internal, b);
8185   if (is_tracepoint (b))
8186     set_tracepoint_count (breakpoint_count);
8187   if (!internal)
8188     mention (b);
8189   gdb::observers::breakpoint_created.notify (b);
8190
8191   if (update_gll)
8192     update_global_location_list (UGLL_MAY_INSERT);
8193 }
8194
8195 static void
8196 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8197                                     int tempflag, const char *cond_string,
8198                                     const struct breakpoint_ops *ops)
8199 {
8200   std::unique_ptr<fork_catchpoint> c (new fork_catchpoint ());
8201
8202   init_catchpoint (c.get (), gdbarch, tempflag, cond_string, ops);
8203
8204   c->forked_inferior_pid = null_ptid;
8205
8206   install_breakpoint (0, std::move (c), 1);
8207 }
8208
8209 /* Exec catchpoints.  */
8210
8211 /* An instance of this type is used to represent an exec catchpoint.
8212    A breakpoint is really of this type iff its ops pointer points to
8213    CATCH_EXEC_BREAKPOINT_OPS.  */
8214
8215 struct exec_catchpoint : public breakpoint
8216 {
8217   ~exec_catchpoint () override;
8218
8219   /* Filename of a program whose exec triggered this catchpoint.
8220      This field is only valid immediately after this catchpoint has
8221      triggered.  */
8222   char *exec_pathname;
8223 };
8224
8225 /* Exec catchpoint destructor.  */
8226
8227 exec_catchpoint::~exec_catchpoint ()
8228 {
8229   xfree (this->exec_pathname);
8230 }
8231
8232 static int
8233 insert_catch_exec (struct bp_location *bl)
8234 {
8235   return target_insert_exec_catchpoint (inferior_ptid.pid ());
8236 }
8237
8238 static int
8239 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8240 {
8241   return target_remove_exec_catchpoint (inferior_ptid.pid ());
8242 }
8243
8244 static int
8245 breakpoint_hit_catch_exec (const struct bp_location *bl,
8246                            const address_space *aspace, CORE_ADDR bp_addr,
8247                            const struct target_waitstatus *ws)
8248 {
8249   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8250
8251   if (ws->kind != TARGET_WAITKIND_EXECD)
8252     return 0;
8253
8254   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8255   return 1;
8256 }
8257
8258 static enum print_stop_action
8259 print_it_catch_exec (bpstat bs)
8260 {
8261   struct ui_out *uiout = current_uiout;
8262   struct breakpoint *b = bs->breakpoint_at;
8263   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8264
8265   annotate_catchpoint (b->number);
8266   maybe_print_thread_hit_breakpoint (uiout);
8267   if (b->disposition == disp_del)
8268     uiout->text ("Temporary catchpoint ");
8269   else
8270     uiout->text ("Catchpoint ");
8271   if (uiout->is_mi_like_p ())
8272     {
8273       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8274       uiout->field_string ("disp", bpdisp_text (b->disposition));
8275     }
8276   uiout->field_int ("bkptno", b->number);
8277   uiout->text (" (exec'd ");
8278   uiout->field_string ("new-exec", c->exec_pathname);
8279   uiout->text ("), ");
8280
8281   return PRINT_SRC_AND_LOC;
8282 }
8283
8284 static void
8285 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8286 {
8287   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8288   struct value_print_options opts;
8289   struct ui_out *uiout = current_uiout;
8290
8291   get_user_print_options (&opts);
8292
8293   /* Field 4, the address, is omitted (which makes the columns
8294      not line up too nicely with the headers, but the effect
8295      is relatively readable).  */
8296   if (opts.addressprint)
8297     uiout->field_skip ("addr");
8298   annotate_field (5);
8299   uiout->text ("exec");
8300   if (c->exec_pathname != NULL)
8301     {
8302       uiout->text (", program \"");
8303       uiout->field_string ("what", c->exec_pathname);
8304       uiout->text ("\" ");
8305     }
8306
8307   if (uiout->is_mi_like_p ())
8308     uiout->field_string ("catch-type", "exec");
8309 }
8310
8311 static void
8312 print_mention_catch_exec (struct breakpoint *b)
8313 {
8314   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8315 }
8316
8317 /* Implement the "print_recreate" breakpoint_ops method for exec
8318    catchpoints.  */
8319
8320 static void
8321 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8322 {
8323   fprintf_unfiltered (fp, "catch exec");
8324   print_recreate_thread (b, fp);
8325 }
8326
8327 static struct breakpoint_ops catch_exec_breakpoint_ops;
8328
8329 static int
8330 hw_breakpoint_used_count (void)
8331 {
8332   int i = 0;
8333   struct breakpoint *b;
8334   struct bp_location *bl;
8335
8336   ALL_BREAKPOINTS (b)
8337   {
8338     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8339       for (bl = b->loc; bl; bl = bl->next)
8340         {
8341           /* Special types of hardware breakpoints may use more than
8342              one register.  */
8343           i += b->ops->resources_needed (bl);
8344         }
8345   }
8346
8347   return i;
8348 }
8349
8350 /* Returns the resources B would use if it were a hardware
8351    watchpoint.  */
8352
8353 static int
8354 hw_watchpoint_use_count (struct breakpoint *b)
8355 {
8356   int i = 0;
8357   struct bp_location *bl;
8358
8359   if (!breakpoint_enabled (b))
8360     return 0;
8361
8362   for (bl = b->loc; bl; bl = bl->next)
8363     {
8364       /* Special types of hardware watchpoints may use more than
8365          one register.  */
8366       i += b->ops->resources_needed (bl);
8367     }
8368
8369   return i;
8370 }
8371
8372 /* Returns the sum the used resources of all hardware watchpoints of
8373    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8374    the sum of the used resources of all hardware watchpoints of other
8375    types _not_ TYPE.  */
8376
8377 static int
8378 hw_watchpoint_used_count_others (struct breakpoint *except,
8379                                  enum bptype type, int *other_type_used)
8380 {
8381   int i = 0;
8382   struct breakpoint *b;
8383
8384   *other_type_used = 0;
8385   ALL_BREAKPOINTS (b)
8386     {
8387       if (b == except)
8388         continue;
8389       if (!breakpoint_enabled (b))
8390         continue;
8391
8392       if (b->type == type)
8393         i += hw_watchpoint_use_count (b);
8394       else if (is_hardware_watchpoint (b))
8395         *other_type_used = 1;
8396     }
8397
8398   return i;
8399 }
8400
8401 void
8402 disable_watchpoints_before_interactive_call_start (void)
8403 {
8404   struct breakpoint *b;
8405
8406   ALL_BREAKPOINTS (b)
8407   {
8408     if (is_watchpoint (b) && breakpoint_enabled (b))
8409       {
8410         b->enable_state = bp_call_disabled;
8411         update_global_location_list (UGLL_DONT_INSERT);
8412       }
8413   }
8414 }
8415
8416 void
8417 enable_watchpoints_after_interactive_call_stop (void)
8418 {
8419   struct breakpoint *b;
8420
8421   ALL_BREAKPOINTS (b)
8422   {
8423     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8424       {
8425         b->enable_state = bp_enabled;
8426         update_global_location_list (UGLL_MAY_INSERT);
8427       }
8428   }
8429 }
8430
8431 void
8432 disable_breakpoints_before_startup (void)
8433 {
8434   current_program_space->executing_startup = 1;
8435   update_global_location_list (UGLL_DONT_INSERT);
8436 }
8437
8438 void
8439 enable_breakpoints_after_startup (void)
8440 {
8441   current_program_space->executing_startup = 0;
8442   breakpoint_re_set ();
8443 }
8444
8445 /* Create a new single-step breakpoint for thread THREAD, with no
8446    locations.  */
8447
8448 static struct breakpoint *
8449 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8450 {
8451   std::unique_ptr<breakpoint> b (new breakpoint ());
8452
8453   init_raw_breakpoint_without_location (b.get (), gdbarch, bp_single_step,
8454                                         &momentary_breakpoint_ops);
8455
8456   b->disposition = disp_donttouch;
8457   b->frame_id = null_frame_id;
8458
8459   b->thread = thread;
8460   gdb_assert (b->thread != 0);
8461
8462   return add_to_breakpoint_chain (std::move (b));
8463 }
8464
8465 /* Set a momentary breakpoint of type TYPE at address specified by
8466    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8467    frame.  */
8468
8469 breakpoint_up
8470 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8471                           struct frame_id frame_id, enum bptype type)
8472 {
8473   struct breakpoint *b;
8474
8475   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8476      tail-called one.  */
8477   gdb_assert (!frame_id_artificial_p (frame_id));
8478
8479   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8480   b->enable_state = bp_enabled;
8481   b->disposition = disp_donttouch;
8482   b->frame_id = frame_id;
8483
8484   b->thread = inferior_thread ()->global_num;
8485
8486   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8487
8488   return breakpoint_up (b);
8489 }
8490
8491 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8492    The new breakpoint will have type TYPE, use OPS as its
8493    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8494
8495 static struct breakpoint *
8496 momentary_breakpoint_from_master (struct breakpoint *orig,
8497                                   enum bptype type,
8498                                   const struct breakpoint_ops *ops,
8499                                   int loc_enabled)
8500 {
8501   struct breakpoint *copy;
8502
8503   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8504   copy->loc = allocate_bp_location (copy);
8505   set_breakpoint_location_function (copy->loc, 1);
8506
8507   copy->loc->gdbarch = orig->loc->gdbarch;
8508   copy->loc->requested_address = orig->loc->requested_address;
8509   copy->loc->address = orig->loc->address;
8510   copy->loc->section = orig->loc->section;
8511   copy->loc->pspace = orig->loc->pspace;
8512   copy->loc->probe = orig->loc->probe;
8513   copy->loc->line_number = orig->loc->line_number;
8514   copy->loc->symtab = orig->loc->symtab;
8515   copy->loc->enabled = loc_enabled;
8516   copy->frame_id = orig->frame_id;
8517   copy->thread = orig->thread;
8518   copy->pspace = orig->pspace;
8519
8520   copy->enable_state = bp_enabled;
8521   copy->disposition = disp_donttouch;
8522   copy->number = internal_breakpoint_number--;
8523
8524   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8525   return copy;
8526 }
8527
8528 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8529    ORIG is NULL.  */
8530
8531 struct breakpoint *
8532 clone_momentary_breakpoint (struct breakpoint *orig)
8533 {
8534   /* If there's nothing to clone, then return nothing.  */
8535   if (orig == NULL)
8536     return NULL;
8537
8538   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8539 }
8540
8541 breakpoint_up
8542 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8543                                 enum bptype type)
8544 {
8545   struct symtab_and_line sal;
8546
8547   sal = find_pc_line (pc, 0);
8548   sal.pc = pc;
8549   sal.section = find_pc_overlay (pc);
8550   sal.explicit_pc = 1;
8551
8552   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8553 }
8554 \f
8555
8556 /* Tell the user we have just set a breakpoint B.  */
8557
8558 static void
8559 mention (struct breakpoint *b)
8560 {
8561   b->ops->print_mention (b);
8562   current_uiout->text ("\n");
8563 }
8564 \f
8565
8566 static int bp_loc_is_permanent (struct bp_location *loc);
8567
8568 static struct bp_location *
8569 add_location_to_breakpoint (struct breakpoint *b,
8570                             const struct symtab_and_line *sal)
8571 {
8572   struct bp_location *loc, **tmp;
8573   CORE_ADDR adjusted_address;
8574   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8575
8576   if (loc_gdbarch == NULL)
8577     loc_gdbarch = b->gdbarch;
8578
8579   /* Adjust the breakpoint's address prior to allocating a location.
8580      Once we call allocate_bp_location(), that mostly uninitialized
8581      location will be placed on the location chain.  Adjustment of the
8582      breakpoint may cause target_read_memory() to be called and we do
8583      not want its scan of the location chain to find a breakpoint and
8584      location that's only been partially initialized.  */
8585   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8586                                                 sal->pc, b->type);
8587
8588   /* Sort the locations by their ADDRESS.  */
8589   loc = allocate_bp_location (b);
8590   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8591        tmp = &((*tmp)->next))
8592     ;
8593   loc->next = *tmp;
8594   *tmp = loc;
8595
8596   loc->requested_address = sal->pc;
8597   loc->address = adjusted_address;
8598   loc->pspace = sal->pspace;
8599   loc->probe.prob = sal->prob;
8600   loc->probe.objfile = sal->objfile;
8601   gdb_assert (loc->pspace != NULL);
8602   loc->section = sal->section;
8603   loc->gdbarch = loc_gdbarch;
8604   loc->line_number = sal->line;
8605   loc->symtab = sal->symtab;
8606   loc->symbol = sal->symbol;
8607   loc->msymbol = sal->msymbol;
8608   loc->objfile = sal->objfile;
8609
8610   set_breakpoint_location_function (loc,
8611                                     sal->explicit_pc || sal->explicit_line);
8612
8613   /* While by definition, permanent breakpoints are already present in the
8614      code, we don't mark the location as inserted.  Normally one would expect
8615      that GDB could rely on that breakpoint instruction to stop the program,
8616      thus removing the need to insert its own breakpoint, except that executing
8617      the breakpoint instruction can kill the target instead of reporting a
8618      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8619      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8620      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8621      breakpoint be inserted normally results in QEMU knowing about the GDB
8622      breakpoint, and thus trap before the breakpoint instruction is executed.
8623      (If GDB later needs to continue execution past the permanent breakpoint,
8624      it manually increments the PC, thus avoiding executing the breakpoint
8625      instruction.)  */
8626   if (bp_loc_is_permanent (loc))
8627     loc->permanent = 1;
8628
8629   return loc;
8630 }
8631 \f
8632
8633 /* See breakpoint.h.  */
8634
8635 int
8636 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
8637 {
8638   int len;
8639   CORE_ADDR addr;
8640   const gdb_byte *bpoint;
8641   gdb_byte *target_mem;
8642
8643   addr = address;
8644   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
8645
8646   /* Software breakpoints unsupported?  */
8647   if (bpoint == NULL)
8648     return 0;
8649
8650   target_mem = (gdb_byte *) alloca (len);
8651
8652   /* Enable the automatic memory restoration from breakpoints while
8653      we read the memory.  Otherwise we could say about our temporary
8654      breakpoints they are permanent.  */
8655   scoped_restore restore_memory
8656     = make_scoped_restore_show_memory_breakpoints (0);
8657
8658   if (target_read_memory (address, target_mem, len) == 0
8659       && memcmp (target_mem, bpoint, len) == 0)
8660     return 1;
8661
8662   return 0;
8663 }
8664
8665 /* Return 1 if LOC is pointing to a permanent breakpoint,
8666    return 0 otherwise.  */
8667
8668 static int
8669 bp_loc_is_permanent (struct bp_location *loc)
8670 {
8671   gdb_assert (loc != NULL);
8672
8673   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
8674      attempt to read from the addresses the locations of these breakpoint types
8675      point to.  program_breakpoint_here_p, below, will attempt to read
8676      memory.  */
8677   if (!breakpoint_address_is_meaningful (loc->owner))
8678     return 0;
8679
8680   scoped_restore_current_pspace_and_thread restore_pspace_thread;
8681   switch_to_program_space_and_thread (loc->pspace);
8682   return program_breakpoint_here_p (loc->gdbarch, loc->address);
8683 }
8684
8685 /* Build a command list for the dprintf corresponding to the current
8686    settings of the dprintf style options.  */
8687
8688 static void
8689 update_dprintf_command_list (struct breakpoint *b)
8690 {
8691   char *dprintf_args = b->extra_string;
8692   char *printf_line = NULL;
8693
8694   if (!dprintf_args)
8695     return;
8696
8697   dprintf_args = skip_spaces (dprintf_args);
8698
8699   /* Allow a comma, as it may have terminated a location, but don't
8700      insist on it.  */
8701   if (*dprintf_args == ',')
8702     ++dprintf_args;
8703   dprintf_args = skip_spaces (dprintf_args);
8704
8705   if (*dprintf_args != '"')
8706     error (_("Bad format string, missing '\"'."));
8707
8708   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8709     printf_line = xstrprintf ("printf %s", dprintf_args);
8710   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8711     {
8712       if (!dprintf_function)
8713         error (_("No function supplied for dprintf call"));
8714
8715       if (dprintf_channel && strlen (dprintf_channel) > 0)
8716         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8717                                   dprintf_function,
8718                                   dprintf_channel,
8719                                   dprintf_args);
8720       else
8721         printf_line = xstrprintf ("call (void) %s (%s)",
8722                                   dprintf_function,
8723                                   dprintf_args);
8724     }
8725   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8726     {
8727       if (target_can_run_breakpoint_commands ())
8728         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8729       else
8730         {
8731           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8732           printf_line = xstrprintf ("printf %s", dprintf_args);
8733         }
8734     }
8735   else
8736     internal_error (__FILE__, __LINE__,
8737                     _("Invalid dprintf style."));
8738
8739   gdb_assert (printf_line != NULL);
8740
8741   /* Manufacture a printf sequence.  */
8742   struct command_line *printf_cmd_line
8743     = new struct command_line (simple_control, printf_line);
8744   breakpoint_set_commands (b, counted_command_line (printf_cmd_line,
8745                                                     command_lines_deleter ()));
8746 }
8747
8748 /* Update all dprintf commands, making their command lists reflect
8749    current style settings.  */
8750
8751 static void
8752 update_dprintf_commands (const char *args, int from_tty,
8753                          struct cmd_list_element *c)
8754 {
8755   struct breakpoint *b;
8756
8757   ALL_BREAKPOINTS (b)
8758     {
8759       if (b->type == bp_dprintf)
8760         update_dprintf_command_list (b);
8761     }
8762 }
8763
8764 /* Create a breakpoint with SAL as location.  Use LOCATION
8765    as a description of the location, and COND_STRING
8766    as condition expression.  If LOCATION is NULL then create an
8767    "address location" from the address in the SAL.  */
8768
8769 static void
8770 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8771                      gdb::array_view<const symtab_and_line> sals,
8772                      event_location_up &&location,
8773                      gdb::unique_xmalloc_ptr<char> filter,
8774                      gdb::unique_xmalloc_ptr<char> cond_string,
8775                      gdb::unique_xmalloc_ptr<char> extra_string,
8776                      enum bptype type, enum bpdisp disposition,
8777                      int thread, int task, int ignore_count,
8778                      const struct breakpoint_ops *ops, int from_tty,
8779                      int enabled, int internal, unsigned flags,
8780                      int display_canonical)
8781 {
8782   int i;
8783
8784   if (type == bp_hardware_breakpoint)
8785     {
8786       int target_resources_ok;
8787
8788       i = hw_breakpoint_used_count ();
8789       target_resources_ok =
8790         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8791                                             i + 1, 0);
8792       if (target_resources_ok == 0)
8793         error (_("No hardware breakpoint support in the target."));
8794       else if (target_resources_ok < 0)
8795         error (_("Hardware breakpoints used exceeds limit."));
8796     }
8797
8798   gdb_assert (!sals.empty ());
8799
8800   for (const auto &sal : sals)
8801     {
8802       struct bp_location *loc;
8803
8804       if (from_tty)
8805         {
8806           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8807           if (!loc_gdbarch)
8808             loc_gdbarch = gdbarch;
8809
8810           describe_other_breakpoints (loc_gdbarch,
8811                                       sal.pspace, sal.pc, sal.section, thread);
8812         }
8813
8814       if (&sal == &sals[0])
8815         {
8816           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8817           b->thread = thread;
8818           b->task = task;
8819
8820           b->cond_string = cond_string.release ();
8821           b->extra_string = extra_string.release ();
8822           b->ignore_count = ignore_count;
8823           b->enable_state = enabled ? bp_enabled : bp_disabled;
8824           b->disposition = disposition;
8825
8826           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8827             b->loc->inserted = 1;
8828
8829           if (type == bp_static_tracepoint)
8830             {
8831               struct tracepoint *t = (struct tracepoint *) b;
8832               struct static_tracepoint_marker marker;
8833
8834               if (strace_marker_p (b))
8835                 {
8836                   /* We already know the marker exists, otherwise, we
8837                      wouldn't see a sal for it.  */
8838                   const char *p
8839                     = &event_location_to_string (b->location.get ())[3];
8840                   const char *endp;
8841
8842                   p = skip_spaces (p);
8843
8844                   endp = skip_to_space (p);
8845
8846                   t->static_trace_marker_id.assign (p, endp - p);
8847
8848                   printf_filtered (_("Probed static tracepoint "
8849                                      "marker \"%s\"\n"),
8850                                    t->static_trace_marker_id.c_str ());
8851                 }
8852               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8853                 {
8854                   t->static_trace_marker_id = std::move (marker.str_id);
8855
8856                   printf_filtered (_("Probed static tracepoint "
8857                                      "marker \"%s\"\n"),
8858                                    t->static_trace_marker_id.c_str ());
8859                 }
8860               else
8861                 warning (_("Couldn't determine the static "
8862                            "tracepoint marker to probe"));
8863             }
8864
8865           loc = b->loc;
8866         }
8867       else
8868         {
8869           loc = add_location_to_breakpoint (b, &sal);
8870           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8871             loc->inserted = 1;
8872         }
8873
8874       if (b->cond_string)
8875         {
8876           const char *arg = b->cond_string;
8877
8878           loc->cond = parse_exp_1 (&arg, loc->address,
8879                                    block_for_pc (loc->address), 0);
8880           if (*arg)
8881               error (_("Garbage '%s' follows condition"), arg);
8882         }
8883
8884       /* Dynamic printf requires and uses additional arguments on the
8885          command line, otherwise it's an error.  */
8886       if (type == bp_dprintf)
8887         {
8888           if (b->extra_string)
8889             update_dprintf_command_list (b);
8890           else
8891             error (_("Format string required"));
8892         }
8893       else if (b->extra_string)
8894         error (_("Garbage '%s' at end of command"), b->extra_string);
8895     }
8896
8897   b->display_canonical = display_canonical;
8898   if (location != NULL)
8899     b->location = std::move (location);
8900   else
8901     b->location = new_address_location (b->loc->address, NULL, 0);
8902   b->filter = filter.release ();
8903 }
8904
8905 static void
8906 create_breakpoint_sal (struct gdbarch *gdbarch,
8907                        gdb::array_view<const symtab_and_line> sals,
8908                        event_location_up &&location,
8909                        gdb::unique_xmalloc_ptr<char> filter,
8910                        gdb::unique_xmalloc_ptr<char> cond_string,
8911                        gdb::unique_xmalloc_ptr<char> extra_string,
8912                        enum bptype type, enum bpdisp disposition,
8913                        int thread, int task, int ignore_count,
8914                        const struct breakpoint_ops *ops, int from_tty,
8915                        int enabled, int internal, unsigned flags,
8916                        int display_canonical)
8917 {
8918   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (type);
8919
8920   init_breakpoint_sal (b.get (), gdbarch,
8921                        sals, std::move (location),
8922                        std::move (filter),
8923                        std::move (cond_string),
8924                        std::move (extra_string),
8925                        type, disposition,
8926                        thread, task, ignore_count,
8927                        ops, from_tty,
8928                        enabled, internal, flags,
8929                        display_canonical);
8930
8931   install_breakpoint (internal, std::move (b), 0);
8932 }
8933
8934 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
8935    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8936    value.  COND_STRING, if not NULL, specified the condition to be
8937    used for all breakpoints.  Essentially the only case where
8938    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8939    function.  In that case, it's still not possible to specify
8940    separate conditions for different overloaded functions, so
8941    we take just a single condition string.
8942    
8943    NOTE: If the function succeeds, the caller is expected to cleanup
8944    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8945    array contents).  If the function fails (error() is called), the
8946    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8947    COND and SALS arrays and each of those arrays contents.  */
8948
8949 static void
8950 create_breakpoints_sal (struct gdbarch *gdbarch,
8951                         struct linespec_result *canonical,
8952                         gdb::unique_xmalloc_ptr<char> cond_string,
8953                         gdb::unique_xmalloc_ptr<char> extra_string,
8954                         enum bptype type, enum bpdisp disposition,
8955                         int thread, int task, int ignore_count,
8956                         const struct breakpoint_ops *ops, int from_tty,
8957                         int enabled, int internal, unsigned flags)
8958 {
8959   if (canonical->pre_expanded)
8960     gdb_assert (canonical->lsals.size () == 1);
8961
8962   for (const auto &lsal : canonical->lsals)
8963     {
8964       /* Note that 'location' can be NULL in the case of a plain
8965          'break', without arguments.  */
8966       event_location_up location
8967         = (canonical->location != NULL
8968            ? copy_event_location (canonical->location.get ()) : NULL);
8969       gdb::unique_xmalloc_ptr<char> filter_string
8970         (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
8971
8972       create_breakpoint_sal (gdbarch, lsal.sals,
8973                              std::move (location),
8974                              std::move (filter_string),
8975                              std::move (cond_string),
8976                              std::move (extra_string),
8977                              type, disposition,
8978                              thread, task, ignore_count, ops,
8979                              from_tty, enabled, internal, flags,
8980                              canonical->special_display);
8981     }
8982 }
8983
8984 /* Parse LOCATION which is assumed to be a SAL specification possibly
8985    followed by conditionals.  On return, SALS contains an array of SAL
8986    addresses found.  LOCATION points to the end of the SAL (for
8987    linespec locations).
8988
8989    The array and the line spec strings are allocated on the heap, it is
8990    the caller's responsibility to free them.  */
8991
8992 static void
8993 parse_breakpoint_sals (const struct event_location *location,
8994                        struct linespec_result *canonical)
8995 {
8996   struct symtab_and_line cursal;
8997
8998   if (event_location_type (location) == LINESPEC_LOCATION)
8999     {
9000       const char *spec = get_linespec_location (location)->spec_string;
9001
9002       if (spec == NULL)
9003         {
9004           /* The last displayed codepoint, if it's valid, is our default
9005              breakpoint address.  */
9006           if (last_displayed_sal_is_valid ())
9007             {
9008               /* Set sal's pspace, pc, symtab, and line to the values
9009                  corresponding to the last call to print_frame_info.
9010                  Be sure to reinitialize LINE with NOTCURRENT == 0
9011                  as the breakpoint line number is inappropriate otherwise.
9012                  find_pc_line would adjust PC, re-set it back.  */
9013               symtab_and_line sal = get_last_displayed_sal ();
9014               CORE_ADDR pc = sal.pc;
9015
9016               sal = find_pc_line (pc, 0);
9017
9018               /* "break" without arguments is equivalent to "break *PC"
9019                  where PC is the last displayed codepoint's address.  So
9020                  make sure to set sal.explicit_pc to prevent GDB from
9021                  trying to expand the list of sals to include all other
9022                  instances with the same symtab and line.  */
9023               sal.pc = pc;
9024               sal.explicit_pc = 1;
9025
9026               struct linespec_sals lsal;
9027               lsal.sals = {sal};
9028               lsal.canonical = NULL;
9029
9030               canonical->lsals.push_back (std::move (lsal));
9031               return;
9032             }
9033           else
9034             error (_("No default breakpoint address now."));
9035         }
9036     }
9037
9038   /* Force almost all breakpoints to be in terms of the
9039      current_source_symtab (which is decode_line_1's default).
9040      This should produce the results we want almost all of the
9041      time while leaving default_breakpoint_* alone.
9042
9043      ObjC: However, don't match an Objective-C method name which
9044      may have a '+' or '-' succeeded by a '['.  */
9045   cursal = get_current_source_symtab_and_line ();
9046   if (last_displayed_sal_is_valid ())
9047     {
9048       const char *spec = NULL;
9049
9050       if (event_location_type (location) == LINESPEC_LOCATION)
9051         spec = get_linespec_location (location)->spec_string;
9052
9053       if (!cursal.symtab
9054           || (spec != NULL
9055               && strchr ("+-", spec[0]) != NULL
9056               && spec[1] != '['))
9057         {
9058           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9059                             get_last_displayed_symtab (),
9060                             get_last_displayed_line (),
9061                             canonical, NULL, NULL);
9062           return;
9063         }
9064     }
9065
9066   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9067                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9068 }
9069
9070
9071 /* Convert each SAL into a real PC.  Verify that the PC can be
9072    inserted as a breakpoint.  If it can't throw an error.  */
9073
9074 static void
9075 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
9076 {    
9077   for (auto &sal : sals)
9078     resolve_sal_pc (&sal);
9079 }
9080
9081 /* Fast tracepoints may have restrictions on valid locations.  For
9082    instance, a fast tracepoint using a jump instead of a trap will
9083    likely have to overwrite more bytes than a trap would, and so can
9084    only be placed where the instruction is longer than the jump, or a
9085    multi-instruction sequence does not have a jump into the middle of
9086    it, etc.  */
9087
9088 static void
9089 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9090                             gdb::array_view<const symtab_and_line> sals)
9091 {
9092   for (const auto &sal : sals)
9093     {
9094       struct gdbarch *sarch;
9095
9096       sarch = get_sal_arch (sal);
9097       /* We fall back to GDBARCH if there is no architecture
9098          associated with SAL.  */
9099       if (sarch == NULL)
9100         sarch = gdbarch;
9101       std::string msg;
9102       if (!gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg))
9103         error (_("May not have a fast tracepoint at %s%s"),
9104                paddress (sarch, sal.pc), msg.c_str ());
9105     }
9106 }
9107
9108 /* Given TOK, a string specification of condition and thread, as
9109    accepted by the 'break' command, extract the condition
9110    string and thread number and set *COND_STRING and *THREAD.
9111    PC identifies the context at which the condition should be parsed.
9112    If no condition is found, *COND_STRING is set to NULL.
9113    If no thread is found, *THREAD is set to -1.  */
9114
9115 static void
9116 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9117                            char **cond_string, int *thread, int *task,
9118                            char **rest)
9119 {
9120   *cond_string = NULL;
9121   *thread = -1;
9122   *task = 0;
9123   *rest = NULL;
9124
9125   while (tok && *tok)
9126     {
9127       const char *end_tok;
9128       int toklen;
9129       const char *cond_start = NULL;
9130       const char *cond_end = NULL;
9131
9132       tok = skip_spaces (tok);
9133
9134       if ((*tok == '"' || *tok == ',') && rest)
9135         {
9136           *rest = savestring (tok, strlen (tok));
9137           return;
9138         }
9139
9140       end_tok = skip_to_space (tok);
9141
9142       toklen = end_tok - tok;
9143
9144       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9145         {
9146           tok = cond_start = end_tok + 1;
9147           parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9148           cond_end = tok;
9149           *cond_string = savestring (cond_start, cond_end - cond_start);
9150         }
9151       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9152         {
9153           const char *tmptok;
9154           struct thread_info *thr;
9155
9156           tok = end_tok + 1;
9157           thr = parse_thread_id (tok, &tmptok);
9158           if (tok == tmptok)
9159             error (_("Junk after thread keyword."));
9160           *thread = thr->global_num;
9161           tok = tmptok;
9162         }
9163       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9164         {
9165           char *tmptok;
9166
9167           tok = end_tok + 1;
9168           *task = strtol (tok, &tmptok, 0);
9169           if (tok == tmptok)
9170             error (_("Junk after task keyword."));
9171           if (!valid_task_id (*task))
9172             error (_("Unknown task %d."), *task);
9173           tok = tmptok;
9174         }
9175       else if (rest)
9176         {
9177           *rest = savestring (tok, strlen (tok));
9178           return;
9179         }
9180       else
9181         error (_("Junk at end of arguments."));
9182     }
9183 }
9184
9185 /* Decode a static tracepoint marker spec.  */
9186
9187 static std::vector<symtab_and_line>
9188 decode_static_tracepoint_spec (const char **arg_p)
9189 {
9190   const char *p = &(*arg_p)[3];
9191   const char *endp;
9192
9193   p = skip_spaces (p);
9194
9195   endp = skip_to_space (p);
9196
9197   std::string marker_str (p, endp - p);
9198
9199   std::vector<static_tracepoint_marker> markers
9200     = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
9201   if (markers.empty ())
9202     error (_("No known static tracepoint marker named %s"),
9203            marker_str.c_str ());
9204
9205   std::vector<symtab_and_line> sals;
9206   sals.reserve (markers.size ());
9207
9208   for (const static_tracepoint_marker &marker : markers)
9209     {
9210       symtab_and_line sal = find_pc_line (marker.address, 0);
9211       sal.pc = marker.address;
9212       sals.push_back (sal);
9213    }
9214
9215   *arg_p = endp;
9216   return sals;
9217 }
9218
9219 /* See breakpoint.h.  */
9220
9221 int
9222 create_breakpoint (struct gdbarch *gdbarch,
9223                    const struct event_location *location,
9224                    const char *cond_string,
9225                    int thread, const char *extra_string,
9226                    int parse_extra,
9227                    int tempflag, enum bptype type_wanted,
9228                    int ignore_count,
9229                    enum auto_boolean pending_break_support,
9230                    const struct breakpoint_ops *ops,
9231                    int from_tty, int enabled, int internal,
9232                    unsigned flags)
9233 {
9234   struct linespec_result canonical;
9235   struct cleanup *bkpt_chain = NULL;
9236   int pending = 0;
9237   int task = 0;
9238   int prev_bkpt_count = breakpoint_count;
9239
9240   gdb_assert (ops != NULL);
9241
9242   /* If extra_string isn't useful, set it to NULL.  */
9243   if (extra_string != NULL && *extra_string == '\0')
9244     extra_string = NULL;
9245
9246   TRY
9247     {
9248       ops->create_sals_from_location (location, &canonical, type_wanted);
9249     }
9250   CATCH (e, RETURN_MASK_ERROR)
9251     {
9252       /* If caller is interested in rc value from parse, set
9253          value.  */
9254       if (e.error == NOT_FOUND_ERROR)
9255         {
9256           /* If pending breakpoint support is turned off, throw
9257              error.  */
9258
9259           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9260             throw_exception (e);
9261
9262           exception_print (gdb_stderr, e);
9263
9264           /* If pending breakpoint support is auto query and the user
9265              selects no, then simply return the error code.  */
9266           if (pending_break_support == AUTO_BOOLEAN_AUTO
9267               && !nquery (_("Make %s pending on future shared library load? "),
9268                           bptype_string (type_wanted)))
9269             return 0;
9270
9271           /* At this point, either the user was queried about setting
9272              a pending breakpoint and selected yes, or pending
9273              breakpoint behavior is on and thus a pending breakpoint
9274              is defaulted on behalf of the user.  */
9275           pending = 1;
9276         }
9277       else
9278         throw_exception (e);
9279     }
9280   END_CATCH
9281
9282   if (!pending && canonical.lsals.empty ())
9283     return 0;
9284
9285   /* ----------------------------- SNIP -----------------------------
9286      Anything added to the cleanup chain beyond this point is assumed
9287      to be part of a breakpoint.  If the breakpoint create succeeds
9288      then the memory is not reclaimed.  */
9289   bkpt_chain = make_cleanup (null_cleanup, 0);
9290
9291   /* Resolve all line numbers to PC's and verify that the addresses
9292      are ok for the target.  */
9293   if (!pending)
9294     {
9295       for (auto &lsal : canonical.lsals)
9296         breakpoint_sals_to_pc (lsal.sals);
9297     }
9298
9299   /* Fast tracepoints may have additional restrictions on location.  */
9300   if (!pending && type_wanted == bp_fast_tracepoint)
9301     {
9302       for (const auto &lsal : canonical.lsals)
9303         check_fast_tracepoint_sals (gdbarch, lsal.sals);
9304     }
9305
9306   /* Verify that condition can be parsed, before setting any
9307      breakpoints.  Allocate a separate condition expression for each
9308      breakpoint.  */
9309   if (!pending)
9310     {
9311       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9312       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9313
9314       if (parse_extra)
9315         {
9316           char *rest;
9317           char *cond;
9318
9319           const linespec_sals &lsal = canonical.lsals[0];
9320
9321           /* Here we only parse 'arg' to separate condition
9322              from thread number, so parsing in context of first
9323              sal is OK.  When setting the breakpoint we'll
9324              re-parse it in context of each sal.  */
9325
9326           find_condition_and_thread (extra_string, lsal.sals[0].pc,
9327                                      &cond, &thread, &task, &rest);
9328           cond_string_copy.reset (cond);
9329           extra_string_copy.reset (rest);
9330         }
9331       else
9332         {
9333           if (type_wanted != bp_dprintf
9334               && extra_string != NULL && *extra_string != '\0')
9335                 error (_("Garbage '%s' at end of location"), extra_string);
9336
9337           /* Create a private copy of condition string.  */
9338           if (cond_string)
9339             cond_string_copy.reset (xstrdup (cond_string));
9340           /* Create a private copy of any extra string.  */
9341           if (extra_string)
9342             extra_string_copy.reset (xstrdup (extra_string));
9343         }
9344
9345       ops->create_breakpoints_sal (gdbarch, &canonical,
9346                                    std::move (cond_string_copy),
9347                                    std::move (extra_string_copy),
9348                                    type_wanted,
9349                                    tempflag ? disp_del : disp_donttouch,
9350                                    thread, task, ignore_count, ops,
9351                                    from_tty, enabled, internal, flags);
9352     }
9353   else
9354     {
9355       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (type_wanted);
9356
9357       init_raw_breakpoint_without_location (b.get (), gdbarch, type_wanted, ops);
9358       b->location = copy_event_location (location);
9359
9360       if (parse_extra)
9361         b->cond_string = NULL;
9362       else
9363         {
9364           /* Create a private copy of condition string.  */
9365           b->cond_string = cond_string != NULL ? xstrdup (cond_string) : NULL;
9366           b->thread = thread;
9367         }
9368
9369       /* Create a private copy of any extra string.  */
9370       b->extra_string = extra_string != NULL ? xstrdup (extra_string) : NULL;
9371       b->ignore_count = ignore_count;
9372       b->disposition = tempflag ? disp_del : disp_donttouch;
9373       b->condition_not_parsed = 1;
9374       b->enable_state = enabled ? bp_enabled : bp_disabled;
9375       if ((type_wanted != bp_breakpoint
9376            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9377         b->pspace = current_program_space;
9378
9379       install_breakpoint (internal, std::move (b), 0);
9380     }
9381   
9382   if (canonical.lsals.size () > 1)
9383     {
9384       warning (_("Multiple breakpoints were set.\nUse the "
9385                  "\"delete\" command to delete unwanted breakpoints."));
9386       prev_breakpoint_count = prev_bkpt_count;
9387     }
9388
9389   /* That's it.  Discard the cleanups for data inserted into the
9390      breakpoint.  */
9391   discard_cleanups (bkpt_chain);
9392
9393   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9394   update_global_location_list (UGLL_MAY_INSERT);
9395
9396   return 1;
9397 }
9398
9399 /* Set a breakpoint.
9400    ARG is a string describing breakpoint address,
9401    condition, and thread.
9402    FLAG specifies if a breakpoint is hardware on,
9403    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9404    and BP_TEMPFLAG.  */
9405
9406 static void
9407 break_command_1 (const char *arg, int flag, int from_tty)
9408 {
9409   int tempflag = flag & BP_TEMPFLAG;
9410   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9411                              ? bp_hardware_breakpoint
9412                              : bp_breakpoint);
9413   struct breakpoint_ops *ops;
9414
9415   event_location_up location = string_to_event_location (&arg, current_language);
9416
9417   /* Matching breakpoints on probes.  */
9418   if (location != NULL
9419       && event_location_type (location.get ()) == PROBE_LOCATION)
9420     ops = &bkpt_probe_breakpoint_ops;
9421   else
9422     ops = &bkpt_breakpoint_ops;
9423
9424   create_breakpoint (get_current_arch (),
9425                      location.get (),
9426                      NULL, 0, arg, 1 /* parse arg */,
9427                      tempflag, type_wanted,
9428                      0 /* Ignore count */,
9429                      pending_break_support,
9430                      ops,
9431                      from_tty,
9432                      1 /* enabled */,
9433                      0 /* internal */,
9434                      0);
9435 }
9436
9437 /* Helper function for break_command_1 and disassemble_command.  */
9438
9439 void
9440 resolve_sal_pc (struct symtab_and_line *sal)
9441 {
9442   CORE_ADDR pc;
9443
9444   if (sal->pc == 0 && sal->symtab != NULL)
9445     {
9446       if (!find_line_pc (sal->symtab, sal->line, &pc))
9447         error (_("No line %d in file \"%s\"."),
9448                sal->line, symtab_to_filename_for_display (sal->symtab));
9449       sal->pc = pc;
9450
9451       /* If this SAL corresponds to a breakpoint inserted using a line
9452          number, then skip the function prologue if necessary.  */
9453       if (sal->explicit_line)
9454         skip_prologue_sal (sal);
9455     }
9456
9457   if (sal->section == 0 && sal->symtab != NULL)
9458     {
9459       const struct blockvector *bv;
9460       const struct block *b;
9461       struct symbol *sym;
9462
9463       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9464                                     SYMTAB_COMPUNIT (sal->symtab));
9465       if (bv != NULL)
9466         {
9467           sym = block_linkage_function (b);
9468           if (sym != NULL)
9469             {
9470               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9471               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9472                                                  sym);
9473             }
9474           else
9475             {
9476               /* It really is worthwhile to have the section, so we'll
9477                  just have to look harder. This case can be executed
9478                  if we have line numbers but no functions (as can
9479                  happen in assembly source).  */
9480
9481               scoped_restore_current_pspace_and_thread restore_pspace_thread;
9482               switch_to_program_space_and_thread (sal->pspace);
9483
9484               bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9485               if (msym.minsym)
9486                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9487             }
9488         }
9489     }
9490 }
9491
9492 void
9493 break_command (const char *arg, int from_tty)
9494 {
9495   break_command_1 (arg, 0, from_tty);
9496 }
9497
9498 void
9499 tbreak_command (const char *arg, int from_tty)
9500 {
9501   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9502 }
9503
9504 static void
9505 hbreak_command (const char *arg, int from_tty)
9506 {
9507   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9508 }
9509
9510 static void
9511 thbreak_command (const char *arg, int from_tty)
9512 {
9513   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9514 }
9515
9516 static void
9517 stop_command (const char *arg, int from_tty)
9518 {
9519   printf_filtered (_("Specify the type of breakpoint to set.\n\
9520 Usage: stop in <function | address>\n\
9521        stop at <line>\n"));
9522 }
9523
9524 static void
9525 stopin_command (const char *arg, int from_tty)
9526 {
9527   int badInput = 0;
9528
9529   if (arg == (char *) NULL)
9530     badInput = 1;
9531   else if (*arg != '*')
9532     {
9533       const char *argptr = arg;
9534       int hasColon = 0;
9535
9536       /* Look for a ':'.  If this is a line number specification, then
9537          say it is bad, otherwise, it should be an address or
9538          function/method name.  */
9539       while (*argptr && !hasColon)
9540         {
9541           hasColon = (*argptr == ':');
9542           argptr++;
9543         }
9544
9545       if (hasColon)
9546         badInput = (*argptr != ':');    /* Not a class::method */
9547       else
9548         badInput = isdigit (*arg);      /* a simple line number */
9549     }
9550
9551   if (badInput)
9552     printf_filtered (_("Usage: stop in <function | address>\n"));
9553   else
9554     break_command_1 (arg, 0, from_tty);
9555 }
9556
9557 static void
9558 stopat_command (const char *arg, int from_tty)
9559 {
9560   int badInput = 0;
9561
9562   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9563     badInput = 1;
9564   else
9565     {
9566       const char *argptr = arg;
9567       int hasColon = 0;
9568
9569       /* Look for a ':'.  If there is a '::' then get out, otherwise
9570          it is probably a line number.  */
9571       while (*argptr && !hasColon)
9572         {
9573           hasColon = (*argptr == ':');
9574           argptr++;
9575         }
9576
9577       if (hasColon)
9578         badInput = (*argptr == ':');    /* we have class::method */
9579       else
9580         badInput = !isdigit (*arg);     /* not a line number */
9581     }
9582
9583   if (badInput)
9584     printf_filtered (_("Usage: stop at LINE\n"));
9585   else
9586     break_command_1 (arg, 0, from_tty);
9587 }
9588
9589 /* The dynamic printf command is mostly like a regular breakpoint, but
9590    with a prewired command list consisting of a single output command,
9591    built from extra arguments supplied on the dprintf command
9592    line.  */
9593
9594 static void
9595 dprintf_command (const char *arg, int from_tty)
9596 {
9597   event_location_up location = string_to_event_location (&arg, current_language);
9598
9599   /* If non-NULL, ARG should have been advanced past the location;
9600      the next character must be ','.  */
9601   if (arg != NULL)
9602     {
9603       if (arg[0] != ',' || arg[1] == '\0')
9604         error (_("Format string required"));
9605       else
9606         {
9607           /* Skip the comma.  */
9608           ++arg;
9609         }
9610     }
9611
9612   create_breakpoint (get_current_arch (),
9613                      location.get (),
9614                      NULL, 0, arg, 1 /* parse arg */,
9615                      0, bp_dprintf,
9616                      0 /* Ignore count */,
9617                      pending_break_support,
9618                      &dprintf_breakpoint_ops,
9619                      from_tty,
9620                      1 /* enabled */,
9621                      0 /* internal */,
9622                      0);
9623 }
9624
9625 static void
9626 agent_printf_command (const char *arg, int from_tty)
9627 {
9628   error (_("May only run agent-printf on the target"));
9629 }
9630
9631 /* Implement the "breakpoint_hit" breakpoint_ops method for
9632    ranged breakpoints.  */
9633
9634 static int
9635 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9636                                   const address_space *aspace,
9637                                   CORE_ADDR bp_addr,
9638                                   const struct target_waitstatus *ws)
9639 {
9640   if (ws->kind != TARGET_WAITKIND_STOPPED
9641       || ws->value.sig != GDB_SIGNAL_TRAP)
9642     return 0;
9643
9644   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9645                                          bl->length, aspace, bp_addr);
9646 }
9647
9648 /* Implement the "resources_needed" breakpoint_ops method for
9649    ranged breakpoints.  */
9650
9651 static int
9652 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9653 {
9654   return target_ranged_break_num_registers ();
9655 }
9656
9657 /* Implement the "print_it" breakpoint_ops method for
9658    ranged breakpoints.  */
9659
9660 static enum print_stop_action
9661 print_it_ranged_breakpoint (bpstat bs)
9662 {
9663   struct breakpoint *b = bs->breakpoint_at;
9664   struct bp_location *bl = b->loc;
9665   struct ui_out *uiout = current_uiout;
9666
9667   gdb_assert (b->type == bp_hardware_breakpoint);
9668
9669   /* Ranged breakpoints have only one location.  */
9670   gdb_assert (bl && bl->next == NULL);
9671
9672   annotate_breakpoint (b->number);
9673
9674   maybe_print_thread_hit_breakpoint (uiout);
9675
9676   if (b->disposition == disp_del)
9677     uiout->text ("Temporary ranged breakpoint ");
9678   else
9679     uiout->text ("Ranged breakpoint ");
9680   if (uiout->is_mi_like_p ())
9681     {
9682       uiout->field_string ("reason",
9683                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9684       uiout->field_string ("disp", bpdisp_text (b->disposition));
9685     }
9686   uiout->field_int ("bkptno", b->number);
9687   uiout->text (", ");
9688
9689   return PRINT_SRC_AND_LOC;
9690 }
9691
9692 /* Implement the "print_one" breakpoint_ops method for
9693    ranged breakpoints.  */
9694
9695 static void
9696 print_one_ranged_breakpoint (struct breakpoint *b,
9697                              struct bp_location **last_loc)
9698 {
9699   struct bp_location *bl = b->loc;
9700   struct value_print_options opts;
9701   struct ui_out *uiout = current_uiout;
9702
9703   /* Ranged breakpoints have only one location.  */
9704   gdb_assert (bl && bl->next == NULL);
9705
9706   get_user_print_options (&opts);
9707
9708   if (opts.addressprint)
9709     /* We don't print the address range here, it will be printed later
9710        by print_one_detail_ranged_breakpoint.  */
9711     uiout->field_skip ("addr");
9712   annotate_field (5);
9713   print_breakpoint_location (b, bl);
9714   *last_loc = bl;
9715 }
9716
9717 /* Implement the "print_one_detail" breakpoint_ops method for
9718    ranged breakpoints.  */
9719
9720 static void
9721 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9722                                     struct ui_out *uiout)
9723 {
9724   CORE_ADDR address_start, address_end;
9725   struct bp_location *bl = b->loc;
9726   string_file stb;
9727
9728   gdb_assert (bl);
9729
9730   address_start = bl->address;
9731   address_end = address_start + bl->length - 1;
9732
9733   uiout->text ("\taddress range: ");
9734   stb.printf ("[%s, %s]",
9735               print_core_address (bl->gdbarch, address_start),
9736               print_core_address (bl->gdbarch, address_end));
9737   uiout->field_stream ("addr", stb);
9738   uiout->text ("\n");
9739 }
9740
9741 /* Implement the "print_mention" breakpoint_ops method for
9742    ranged breakpoints.  */
9743
9744 static void
9745 print_mention_ranged_breakpoint (struct breakpoint *b)
9746 {
9747   struct bp_location *bl = b->loc;
9748   struct ui_out *uiout = current_uiout;
9749
9750   gdb_assert (bl);
9751   gdb_assert (b->type == bp_hardware_breakpoint);
9752
9753   uiout->message (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9754                   b->number, paddress (bl->gdbarch, bl->address),
9755                   paddress (bl->gdbarch, bl->address + bl->length - 1));
9756 }
9757
9758 /* Implement the "print_recreate" breakpoint_ops method for
9759    ranged breakpoints.  */
9760
9761 static void
9762 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9763 {
9764   fprintf_unfiltered (fp, "break-range %s, %s",
9765                       event_location_to_string (b->location.get ()),
9766                       event_location_to_string (b->location_range_end.get ()));
9767   print_recreate_thread (b, fp);
9768 }
9769
9770 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9771
9772 static struct breakpoint_ops ranged_breakpoint_ops;
9773
9774 /* Find the address where the end of the breakpoint range should be
9775    placed, given the SAL of the end of the range.  This is so that if
9776    the user provides a line number, the end of the range is set to the
9777    last instruction of the given line.  */
9778
9779 static CORE_ADDR
9780 find_breakpoint_range_end (struct symtab_and_line sal)
9781 {
9782   CORE_ADDR end;
9783
9784   /* If the user provided a PC value, use it.  Otherwise,
9785      find the address of the end of the given location.  */
9786   if (sal.explicit_pc)
9787     end = sal.pc;
9788   else
9789     {
9790       int ret;
9791       CORE_ADDR start;
9792
9793       ret = find_line_pc_range (sal, &start, &end);
9794       if (!ret)
9795         error (_("Could not find location of the end of the range."));
9796
9797       /* find_line_pc_range returns the start of the next line.  */
9798       end--;
9799     }
9800
9801   return end;
9802 }
9803
9804 /* Implement the "break-range" CLI command.  */
9805
9806 static void
9807 break_range_command (const char *arg, int from_tty)
9808 {
9809   const char *arg_start;
9810   struct linespec_result canonical_start, canonical_end;
9811   int bp_count, can_use_bp, length;
9812   CORE_ADDR end;
9813   struct breakpoint *b;
9814
9815   /* We don't support software ranged breakpoints.  */
9816   if (target_ranged_break_num_registers () < 0)
9817     error (_("This target does not support hardware ranged breakpoints."));
9818
9819   bp_count = hw_breakpoint_used_count ();
9820   bp_count += target_ranged_break_num_registers ();
9821   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9822                                                    bp_count, 0);
9823   if (can_use_bp < 0)
9824     error (_("Hardware breakpoints used exceeds limit."));
9825
9826   arg = skip_spaces (arg);
9827   if (arg == NULL || arg[0] == '\0')
9828     error(_("No address range specified."));
9829
9830   arg_start = arg;
9831   event_location_up start_location = string_to_event_location (&arg,
9832                                                                current_language);
9833   parse_breakpoint_sals (start_location.get (), &canonical_start);
9834
9835   if (arg[0] != ',')
9836     error (_("Too few arguments."));
9837   else if (canonical_start.lsals.empty ())
9838     error (_("Could not find location of the beginning of the range."));
9839
9840   const linespec_sals &lsal_start = canonical_start.lsals[0];
9841
9842   if (canonical_start.lsals.size () > 1
9843       || lsal_start.sals.size () != 1)
9844     error (_("Cannot create a ranged breakpoint with multiple locations."));
9845
9846   const symtab_and_line &sal_start = lsal_start.sals[0];
9847   std::string addr_string_start (arg_start, arg - arg_start);
9848
9849   arg++;        /* Skip the comma.  */
9850   arg = skip_spaces (arg);
9851
9852   /* Parse the end location.  */
9853
9854   arg_start = arg;
9855
9856   /* We call decode_line_full directly here instead of using
9857      parse_breakpoint_sals because we need to specify the start location's
9858      symtab and line as the default symtab and line for the end of the
9859      range.  This makes it possible to have ranges like "foo.c:27, +14",
9860      where +14 means 14 lines from the start location.  */
9861   event_location_up end_location = string_to_event_location (&arg,
9862                                                              current_language);
9863   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
9864                     sal_start.symtab, sal_start.line,
9865                     &canonical_end, NULL, NULL);
9866
9867   if (canonical_end.lsals.empty ())
9868     error (_("Could not find location of the end of the range."));
9869
9870   const linespec_sals &lsal_end = canonical_end.lsals[0];
9871   if (canonical_end.lsals.size () > 1
9872       || lsal_end.sals.size () != 1)
9873     error (_("Cannot create a ranged breakpoint with multiple locations."));
9874
9875   const symtab_and_line &sal_end = lsal_end.sals[0];
9876
9877   end = find_breakpoint_range_end (sal_end);
9878   if (sal_start.pc > end)
9879     error (_("Invalid address range, end precedes start."));
9880
9881   length = end - sal_start.pc + 1;
9882   if (length < 0)
9883     /* Length overflowed.  */
9884     error (_("Address range too large."));
9885   else if (length == 1)
9886     {
9887       /* This range is simple enough to be handled by
9888          the `hbreak' command.  */
9889       hbreak_command (&addr_string_start[0], 1);
9890
9891       return;
9892     }
9893
9894   /* Now set up the breakpoint.  */
9895   b = set_raw_breakpoint (get_current_arch (), sal_start,
9896                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
9897   set_breakpoint_count (breakpoint_count + 1);
9898   b->number = breakpoint_count;
9899   b->disposition = disp_donttouch;
9900   b->location = std::move (start_location);
9901   b->location_range_end = std::move (end_location);
9902   b->loc->length = length;
9903
9904   mention (b);
9905   gdb::observers::breakpoint_created.notify (b);
9906   update_global_location_list (UGLL_MAY_INSERT);
9907 }
9908
9909 /*  Return non-zero if EXP is verified as constant.  Returned zero
9910     means EXP is variable.  Also the constant detection may fail for
9911     some constant expressions and in such case still falsely return
9912     zero.  */
9913
9914 static int
9915 watchpoint_exp_is_const (const struct expression *exp)
9916 {
9917   int i = exp->nelts;
9918
9919   while (i > 0)
9920     {
9921       int oplenp, argsp;
9922
9923       /* We are only interested in the descriptor of each element.  */
9924       operator_length (exp, i, &oplenp, &argsp);
9925       i -= oplenp;
9926
9927       switch (exp->elts[i].opcode)
9928         {
9929         case BINOP_ADD:
9930         case BINOP_SUB:
9931         case BINOP_MUL:
9932         case BINOP_DIV:
9933         case BINOP_REM:
9934         case BINOP_MOD:
9935         case BINOP_LSH:
9936         case BINOP_RSH:
9937         case BINOP_LOGICAL_AND:
9938         case BINOP_LOGICAL_OR:
9939         case BINOP_BITWISE_AND:
9940         case BINOP_BITWISE_IOR:
9941         case BINOP_BITWISE_XOR:
9942         case BINOP_EQUAL:
9943         case BINOP_NOTEQUAL:
9944         case BINOP_LESS:
9945         case BINOP_GTR:
9946         case BINOP_LEQ:
9947         case BINOP_GEQ:
9948         case BINOP_REPEAT:
9949         case BINOP_COMMA:
9950         case BINOP_EXP:
9951         case BINOP_MIN:
9952         case BINOP_MAX:
9953         case BINOP_INTDIV:
9954         case BINOP_CONCAT:
9955         case TERNOP_COND:
9956         case TERNOP_SLICE:
9957
9958         case OP_LONG:
9959         case OP_FLOAT:
9960         case OP_LAST:
9961         case OP_COMPLEX:
9962         case OP_STRING:
9963         case OP_ARRAY:
9964         case OP_TYPE:
9965         case OP_TYPEOF:
9966         case OP_DECLTYPE:
9967         case OP_TYPEID:
9968         case OP_NAME:
9969         case OP_OBJC_NSSTRING:
9970
9971         case UNOP_NEG:
9972         case UNOP_LOGICAL_NOT:
9973         case UNOP_COMPLEMENT:
9974         case UNOP_ADDR:
9975         case UNOP_HIGH:
9976         case UNOP_CAST:
9977
9978         case UNOP_CAST_TYPE:
9979         case UNOP_REINTERPRET_CAST:
9980         case UNOP_DYNAMIC_CAST:
9981           /* Unary, binary and ternary operators: We have to check
9982              their operands.  If they are constant, then so is the
9983              result of that operation.  For instance, if A and B are
9984              determined to be constants, then so is "A + B".
9985
9986              UNOP_IND is one exception to the rule above, because the
9987              value of *ADDR is not necessarily a constant, even when
9988              ADDR is.  */
9989           break;
9990
9991         case OP_VAR_VALUE:
9992           /* Check whether the associated symbol is a constant.
9993
9994              We use SYMBOL_CLASS rather than TYPE_CONST because it's
9995              possible that a buggy compiler could mark a variable as
9996              constant even when it is not, and TYPE_CONST would return
9997              true in this case, while SYMBOL_CLASS wouldn't.
9998
9999              We also have to check for function symbols because they
10000              are always constant.  */
10001           {
10002             struct symbol *s = exp->elts[i + 2].symbol;
10003
10004             if (SYMBOL_CLASS (s) != LOC_BLOCK
10005                 && SYMBOL_CLASS (s) != LOC_CONST
10006                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10007               return 0;
10008             break;
10009           }
10010
10011         /* The default action is to return 0 because we are using
10012            the optimistic approach here: If we don't know something,
10013            then it is not a constant.  */
10014         default:
10015           return 0;
10016         }
10017     }
10018
10019   return 1;
10020 }
10021
10022 /* Watchpoint destructor.  */
10023
10024 watchpoint::~watchpoint ()
10025 {
10026   xfree (this->exp_string);
10027   xfree (this->exp_string_reparse);
10028 }
10029
10030 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10031
10032 static void
10033 re_set_watchpoint (struct breakpoint *b)
10034 {
10035   struct watchpoint *w = (struct watchpoint *) b;
10036
10037   /* Watchpoint can be either on expression using entirely global
10038      variables, or it can be on local variables.
10039
10040      Watchpoints of the first kind are never auto-deleted, and even
10041      persist across program restarts.  Since they can use variables
10042      from shared libraries, we need to reparse expression as libraries
10043      are loaded and unloaded.
10044
10045      Watchpoints on local variables can also change meaning as result
10046      of solib event.  For example, if a watchpoint uses both a local
10047      and a global variables in expression, it's a local watchpoint,
10048      but unloading of a shared library will make the expression
10049      invalid.  This is not a very common use case, but we still
10050      re-evaluate expression, to avoid surprises to the user.
10051
10052      Note that for local watchpoints, we re-evaluate it only if
10053      watchpoints frame id is still valid.  If it's not, it means the
10054      watchpoint is out of scope and will be deleted soon.  In fact,
10055      I'm not sure we'll ever be called in this case.
10056
10057      If a local watchpoint's frame id is still valid, then
10058      w->exp_valid_block is likewise valid, and we can safely use it.
10059
10060      Don't do anything about disabled watchpoints, since they will be
10061      reevaluated again when enabled.  */
10062   update_watchpoint (w, 1 /* reparse */);
10063 }
10064
10065 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10066
10067 static int
10068 insert_watchpoint (struct bp_location *bl)
10069 {
10070   struct watchpoint *w = (struct watchpoint *) bl->owner;
10071   int length = w->exact ? 1 : bl->length;
10072
10073   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10074                                    w->cond_exp.get ());
10075 }
10076
10077 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10078
10079 static int
10080 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10081 {
10082   struct watchpoint *w = (struct watchpoint *) bl->owner;
10083   int length = w->exact ? 1 : bl->length;
10084
10085   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10086                                    w->cond_exp.get ());
10087 }
10088
10089 static int
10090 breakpoint_hit_watchpoint (const struct bp_location *bl,
10091                            const address_space *aspace, CORE_ADDR bp_addr,
10092                            const struct target_waitstatus *ws)
10093 {
10094   struct breakpoint *b = bl->owner;
10095   struct watchpoint *w = (struct watchpoint *) b;
10096
10097   /* Continuable hardware watchpoints are treated as non-existent if the
10098      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10099      some data address).  Otherwise gdb won't stop on a break instruction
10100      in the code (not from a breakpoint) when a hardware watchpoint has
10101      been defined.  Also skip watchpoints which we know did not trigger
10102      (did not match the data address).  */
10103   if (is_hardware_watchpoint (b)
10104       && w->watchpoint_triggered == watch_triggered_no)
10105     return 0;
10106
10107   return 1;
10108 }
10109
10110 static void
10111 check_status_watchpoint (bpstat bs)
10112 {
10113   gdb_assert (is_watchpoint (bs->breakpoint_at));
10114
10115   bpstat_check_watchpoint (bs);
10116 }
10117
10118 /* Implement the "resources_needed" breakpoint_ops method for
10119    hardware watchpoints.  */
10120
10121 static int
10122 resources_needed_watchpoint (const struct bp_location *bl)
10123 {
10124   struct watchpoint *w = (struct watchpoint *) bl->owner;
10125   int length = w->exact? 1 : bl->length;
10126
10127   return target_region_ok_for_hw_watchpoint (bl->address, length);
10128 }
10129
10130 /* Implement the "works_in_software_mode" breakpoint_ops method for
10131    hardware watchpoints.  */
10132
10133 static int
10134 works_in_software_mode_watchpoint (const struct breakpoint *b)
10135 {
10136   /* Read and access watchpoints only work with hardware support.  */
10137   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10138 }
10139
10140 static enum print_stop_action
10141 print_it_watchpoint (bpstat bs)
10142 {
10143   struct breakpoint *b;
10144   enum print_stop_action result;
10145   struct watchpoint *w;
10146   struct ui_out *uiout = current_uiout;
10147
10148   gdb_assert (bs->bp_location_at != NULL);
10149
10150   b = bs->breakpoint_at;
10151   w = (struct watchpoint *) b;
10152
10153   annotate_watchpoint (b->number);
10154   maybe_print_thread_hit_breakpoint (uiout);
10155
10156   string_file stb;
10157
10158   gdb::optional<ui_out_emit_tuple> tuple_emitter;
10159   switch (b->type)
10160     {
10161     case bp_watchpoint:
10162     case bp_hardware_watchpoint:
10163       if (uiout->is_mi_like_p ())
10164         uiout->field_string
10165           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10166       mention (b);
10167       tuple_emitter.emplace (uiout, "value");
10168       uiout->text ("\nOld value = ");
10169       watchpoint_value_print (bs->old_val.get (), &stb);
10170       uiout->field_stream ("old", stb);
10171       uiout->text ("\nNew value = ");
10172       watchpoint_value_print (w->val.get (), &stb);
10173       uiout->field_stream ("new", stb);
10174       uiout->text ("\n");
10175       /* More than one watchpoint may have been triggered.  */
10176       result = PRINT_UNKNOWN;
10177       break;
10178
10179     case bp_read_watchpoint:
10180       if (uiout->is_mi_like_p ())
10181         uiout->field_string
10182           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10183       mention (b);
10184       tuple_emitter.emplace (uiout, "value");
10185       uiout->text ("\nValue = ");
10186       watchpoint_value_print (w->val.get (), &stb);
10187       uiout->field_stream ("value", stb);
10188       uiout->text ("\n");
10189       result = PRINT_UNKNOWN;
10190       break;
10191
10192     case bp_access_watchpoint:
10193       if (bs->old_val != NULL)
10194         {
10195           if (uiout->is_mi_like_p ())
10196             uiout->field_string
10197               ("reason",
10198                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10199           mention (b);
10200           tuple_emitter.emplace (uiout, "value");
10201           uiout->text ("\nOld value = ");
10202           watchpoint_value_print (bs->old_val.get (), &stb);
10203           uiout->field_stream ("old", stb);
10204           uiout->text ("\nNew value = ");
10205         }
10206       else
10207         {
10208           mention (b);
10209           if (uiout->is_mi_like_p ())
10210             uiout->field_string
10211               ("reason",
10212                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10213           tuple_emitter.emplace (uiout, "value");
10214           uiout->text ("\nValue = ");
10215         }
10216       watchpoint_value_print (w->val.get (), &stb);
10217       uiout->field_stream ("new", stb);
10218       uiout->text ("\n");
10219       result = PRINT_UNKNOWN;
10220       break;
10221     default:
10222       result = PRINT_UNKNOWN;
10223     }
10224
10225   return result;
10226 }
10227
10228 /* Implement the "print_mention" breakpoint_ops method for hardware
10229    watchpoints.  */
10230
10231 static void
10232 print_mention_watchpoint (struct breakpoint *b)
10233 {
10234   struct watchpoint *w = (struct watchpoint *) b;
10235   struct ui_out *uiout = current_uiout;
10236   const char *tuple_name;
10237
10238   switch (b->type)
10239     {
10240     case bp_watchpoint:
10241       uiout->text ("Watchpoint ");
10242       tuple_name = "wpt";
10243       break;
10244     case bp_hardware_watchpoint:
10245       uiout->text ("Hardware watchpoint ");
10246       tuple_name = "wpt";
10247       break;
10248     case bp_read_watchpoint:
10249       uiout->text ("Hardware read watchpoint ");
10250       tuple_name = "hw-rwpt";
10251       break;
10252     case bp_access_watchpoint:
10253       uiout->text ("Hardware access (read/write) watchpoint ");
10254       tuple_name = "hw-awpt";
10255       break;
10256     default:
10257       internal_error (__FILE__, __LINE__,
10258                       _("Invalid hardware watchpoint type."));
10259     }
10260
10261   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10262   uiout->field_int ("number", b->number);
10263   uiout->text (": ");
10264   uiout->field_string ("exp", w->exp_string);
10265 }
10266
10267 /* Implement the "print_recreate" breakpoint_ops method for
10268    watchpoints.  */
10269
10270 static void
10271 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10272 {
10273   struct watchpoint *w = (struct watchpoint *) b;
10274
10275   switch (b->type)
10276     {
10277     case bp_watchpoint:
10278     case bp_hardware_watchpoint:
10279       fprintf_unfiltered (fp, "watch");
10280       break;
10281     case bp_read_watchpoint:
10282       fprintf_unfiltered (fp, "rwatch");
10283       break;
10284     case bp_access_watchpoint:
10285       fprintf_unfiltered (fp, "awatch");
10286       break;
10287     default:
10288       internal_error (__FILE__, __LINE__,
10289                       _("Invalid watchpoint type."));
10290     }
10291
10292   fprintf_unfiltered (fp, " %s", w->exp_string);
10293   print_recreate_thread (b, fp);
10294 }
10295
10296 /* Implement the "explains_signal" breakpoint_ops method for
10297    watchpoints.  */
10298
10299 static int
10300 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10301 {
10302   /* A software watchpoint cannot cause a signal other than
10303      GDB_SIGNAL_TRAP.  */
10304   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10305     return 0;
10306
10307   return 1;
10308 }
10309
10310 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10311
10312 static struct breakpoint_ops watchpoint_breakpoint_ops;
10313
10314 /* Implement the "insert" breakpoint_ops method for
10315    masked hardware watchpoints.  */
10316
10317 static int
10318 insert_masked_watchpoint (struct bp_location *bl)
10319 {
10320   struct watchpoint *w = (struct watchpoint *) bl->owner;
10321
10322   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10323                                         bl->watchpoint_type);
10324 }
10325
10326 /* Implement the "remove" breakpoint_ops method for
10327    masked hardware watchpoints.  */
10328
10329 static int
10330 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10331 {
10332   struct watchpoint *w = (struct watchpoint *) bl->owner;
10333
10334   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10335                                         bl->watchpoint_type);
10336 }
10337
10338 /* Implement the "resources_needed" breakpoint_ops method for
10339    masked hardware watchpoints.  */
10340
10341 static int
10342 resources_needed_masked_watchpoint (const struct bp_location *bl)
10343 {
10344   struct watchpoint *w = (struct watchpoint *) bl->owner;
10345
10346   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10347 }
10348
10349 /* Implement the "works_in_software_mode" breakpoint_ops method for
10350    masked hardware watchpoints.  */
10351
10352 static int
10353 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10354 {
10355   return 0;
10356 }
10357
10358 /* Implement the "print_it" breakpoint_ops method for
10359    masked hardware watchpoints.  */
10360
10361 static enum print_stop_action
10362 print_it_masked_watchpoint (bpstat bs)
10363 {
10364   struct breakpoint *b = bs->breakpoint_at;
10365   struct ui_out *uiout = current_uiout;
10366
10367   /* Masked watchpoints have only one location.  */
10368   gdb_assert (b->loc && b->loc->next == NULL);
10369
10370   annotate_watchpoint (b->number);
10371   maybe_print_thread_hit_breakpoint (uiout);
10372
10373   switch (b->type)
10374     {
10375     case bp_hardware_watchpoint:
10376       if (uiout->is_mi_like_p ())
10377         uiout->field_string
10378           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10379       break;
10380
10381     case bp_read_watchpoint:
10382       if (uiout->is_mi_like_p ())
10383         uiout->field_string
10384           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10385       break;
10386
10387     case bp_access_watchpoint:
10388       if (uiout->is_mi_like_p ())
10389         uiout->field_string
10390           ("reason",
10391            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10392       break;
10393     default:
10394       internal_error (__FILE__, __LINE__,
10395                       _("Invalid hardware watchpoint type."));
10396     }
10397
10398   mention (b);
10399   uiout->text (_("\n\
10400 Check the underlying instruction at PC for the memory\n\
10401 address and value which triggered this watchpoint.\n"));
10402   uiout->text ("\n");
10403
10404   /* More than one watchpoint may have been triggered.  */
10405   return PRINT_UNKNOWN;
10406 }
10407
10408 /* Implement the "print_one_detail" breakpoint_ops method for
10409    masked hardware watchpoints.  */
10410
10411 static void
10412 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10413                                     struct ui_out *uiout)
10414 {
10415   struct watchpoint *w = (struct watchpoint *) b;
10416
10417   /* Masked watchpoints have only one location.  */
10418   gdb_assert (b->loc && b->loc->next == NULL);
10419
10420   uiout->text ("\tmask ");
10421   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10422   uiout->text ("\n");
10423 }
10424
10425 /* Implement the "print_mention" breakpoint_ops method for
10426    masked hardware watchpoints.  */
10427
10428 static void
10429 print_mention_masked_watchpoint (struct breakpoint *b)
10430 {
10431   struct watchpoint *w = (struct watchpoint *) b;
10432   struct ui_out *uiout = current_uiout;
10433   const char *tuple_name;
10434
10435   switch (b->type)
10436     {
10437     case bp_hardware_watchpoint:
10438       uiout->text ("Masked hardware watchpoint ");
10439       tuple_name = "wpt";
10440       break;
10441     case bp_read_watchpoint:
10442       uiout->text ("Masked hardware read watchpoint ");
10443       tuple_name = "hw-rwpt";
10444       break;
10445     case bp_access_watchpoint:
10446       uiout->text ("Masked hardware access (read/write) watchpoint ");
10447       tuple_name = "hw-awpt";
10448       break;
10449     default:
10450       internal_error (__FILE__, __LINE__,
10451                       _("Invalid hardware watchpoint type."));
10452     }
10453
10454   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10455   uiout->field_int ("number", b->number);
10456   uiout->text (": ");
10457   uiout->field_string ("exp", w->exp_string);
10458 }
10459
10460 /* Implement the "print_recreate" breakpoint_ops method for
10461    masked hardware watchpoints.  */
10462
10463 static void
10464 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10465 {
10466   struct watchpoint *w = (struct watchpoint *) b;
10467   char tmp[40];
10468
10469   switch (b->type)
10470     {
10471     case bp_hardware_watchpoint:
10472       fprintf_unfiltered (fp, "watch");
10473       break;
10474     case bp_read_watchpoint:
10475       fprintf_unfiltered (fp, "rwatch");
10476       break;
10477     case bp_access_watchpoint:
10478       fprintf_unfiltered (fp, "awatch");
10479       break;
10480     default:
10481       internal_error (__FILE__, __LINE__,
10482                       _("Invalid hardware watchpoint type."));
10483     }
10484
10485   sprintf_vma (tmp, w->hw_wp_mask);
10486   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10487   print_recreate_thread (b, fp);
10488 }
10489
10490 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10491
10492 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10493
10494 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10495
10496 static int
10497 is_masked_watchpoint (const struct breakpoint *b)
10498 {
10499   return b->ops == &masked_watchpoint_breakpoint_ops;
10500 }
10501
10502 /* accessflag:  hw_write:  watch write, 
10503                 hw_read:   watch read, 
10504                 hw_access: watch access (read or write) */
10505 static void
10506 watch_command_1 (const char *arg, int accessflag, int from_tty,
10507                  int just_location, int internal)
10508 {
10509   struct breakpoint *scope_breakpoint = NULL;
10510   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10511   struct value *result;
10512   int saved_bitpos = 0, saved_bitsize = 0;
10513   const char *exp_start = NULL;
10514   const char *exp_end = NULL;
10515   const char *tok, *end_tok;
10516   int toklen = -1;
10517   const char *cond_start = NULL;
10518   const char *cond_end = NULL;
10519   enum bptype bp_type;
10520   int thread = -1;
10521   int pc = 0;
10522   /* Flag to indicate whether we are going to use masks for
10523      the hardware watchpoint.  */
10524   int use_mask = 0;
10525   CORE_ADDR mask = 0;
10526
10527   /* Make sure that we actually have parameters to parse.  */
10528   if (arg != NULL && arg[0] != '\0')
10529     {
10530       const char *value_start;
10531
10532       exp_end = arg + strlen (arg);
10533
10534       /* Look for "parameter value" pairs at the end
10535          of the arguments string.  */
10536       for (tok = exp_end - 1; tok > arg; tok--)
10537         {
10538           /* Skip whitespace at the end of the argument list.  */
10539           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10540             tok--;
10541
10542           /* Find the beginning of the last token.
10543              This is the value of the parameter.  */
10544           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10545             tok--;
10546           value_start = tok + 1;
10547
10548           /* Skip whitespace.  */
10549           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10550             tok--;
10551
10552           end_tok = tok;
10553
10554           /* Find the beginning of the second to last token.
10555              This is the parameter itself.  */
10556           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10557             tok--;
10558           tok++;
10559           toklen = end_tok - tok + 1;
10560
10561           if (toklen == 6 && startswith (tok, "thread"))
10562             {
10563               struct thread_info *thr;
10564               /* At this point we've found a "thread" token, which means
10565                  the user is trying to set a watchpoint that triggers
10566                  only in a specific thread.  */
10567               const char *endp;
10568
10569               if (thread != -1)
10570                 error(_("You can specify only one thread."));
10571
10572               /* Extract the thread ID from the next token.  */
10573               thr = parse_thread_id (value_start, &endp);
10574
10575               /* Check if the user provided a valid thread ID.  */
10576               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10577                 invalid_thread_id_error (value_start);
10578
10579               thread = thr->global_num;
10580             }
10581           else if (toklen == 4 && startswith (tok, "mask"))
10582             {
10583               /* We've found a "mask" token, which means the user wants to
10584                  create a hardware watchpoint that is going to have the mask
10585                  facility.  */
10586               struct value *mask_value, *mark;
10587
10588               if (use_mask)
10589                 error(_("You can specify only one mask."));
10590
10591               use_mask = just_location = 1;
10592
10593               mark = value_mark ();
10594               mask_value = parse_to_comma_and_eval (&value_start);
10595               mask = value_as_address (mask_value);
10596               value_free_to_mark (mark);
10597             }
10598           else
10599             /* We didn't recognize what we found.  We should stop here.  */
10600             break;
10601
10602           /* Truncate the string and get rid of the "parameter value" pair before
10603              the arguments string is parsed by the parse_exp_1 function.  */
10604           exp_end = tok;
10605         }
10606     }
10607   else
10608     exp_end = arg;
10609
10610   /* Parse the rest of the arguments.  From here on out, everything
10611      is in terms of a newly allocated string instead of the original
10612      ARG.  */
10613   innermost_block.reset ();
10614   std::string expression (arg, exp_end - arg);
10615   exp_start = arg = expression.c_str ();
10616   expression_up exp = parse_exp_1 (&arg, 0, 0, 0);
10617   exp_end = arg;
10618   /* Remove trailing whitespace from the expression before saving it.
10619      This makes the eventual display of the expression string a bit
10620      prettier.  */
10621   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10622     --exp_end;
10623
10624   /* Checking if the expression is not constant.  */
10625   if (watchpoint_exp_is_const (exp.get ()))
10626     {
10627       int len;
10628
10629       len = exp_end - exp_start;
10630       while (len > 0 && isspace (exp_start[len - 1]))
10631         len--;
10632       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10633     }
10634
10635   exp_valid_block = innermost_block.block ();
10636   struct value *mark = value_mark ();
10637   struct value *val_as_value = nullptr;
10638   fetch_subexp_value (exp.get (), &pc, &val_as_value, &result, NULL,
10639                       just_location);
10640
10641   if (val_as_value != NULL && just_location)
10642     {
10643       saved_bitpos = value_bitpos (val_as_value);
10644       saved_bitsize = value_bitsize (val_as_value);
10645     }
10646
10647   value_ref_ptr val;
10648   if (just_location)
10649     {
10650       int ret;
10651
10652       exp_valid_block = NULL;
10653       val = release_value (value_addr (result));
10654       value_free_to_mark (mark);
10655
10656       if (use_mask)
10657         {
10658           ret = target_masked_watch_num_registers (value_as_address (val.get ()),
10659                                                    mask);
10660           if (ret == -1)
10661             error (_("This target does not support masked watchpoints."));
10662           else if (ret == -2)
10663             error (_("Invalid mask or memory region."));
10664         }
10665     }
10666   else if (val_as_value != NULL)
10667     val = release_value (val_as_value);
10668
10669   tok = skip_spaces (arg);
10670   end_tok = skip_to_space (tok);
10671
10672   toklen = end_tok - tok;
10673   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10674     {
10675       innermost_block.reset ();
10676       tok = cond_start = end_tok + 1;
10677       parse_exp_1 (&tok, 0, 0, 0);
10678
10679       /* The watchpoint expression may not be local, but the condition
10680          may still be.  E.g.: `watch global if local > 0'.  */
10681       cond_exp_valid_block = innermost_block.block ();
10682
10683       cond_end = tok;
10684     }
10685   if (*tok)
10686     error (_("Junk at end of command."));
10687
10688   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
10689
10690   /* Save this because create_internal_breakpoint below invalidates
10691      'wp_frame'.  */
10692   frame_id watchpoint_frame = get_frame_id (wp_frame);
10693
10694   /* If the expression is "local", then set up a "watchpoint scope"
10695      breakpoint at the point where we've left the scope of the watchpoint
10696      expression.  Create the scope breakpoint before the watchpoint, so
10697      that we will encounter it first in bpstat_stop_status.  */
10698   if (exp_valid_block != NULL && wp_frame != NULL)
10699     {
10700       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10701
10702       if (frame_id_p (caller_frame_id))
10703         {
10704           gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10705           CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10706
10707           scope_breakpoint
10708             = create_internal_breakpoint (caller_arch, caller_pc,
10709                                           bp_watchpoint_scope,
10710                                           &momentary_breakpoint_ops);
10711
10712           /* create_internal_breakpoint could invalidate WP_FRAME.  */
10713           wp_frame = NULL;
10714
10715           scope_breakpoint->enable_state = bp_enabled;
10716
10717           /* Automatically delete the breakpoint when it hits.  */
10718           scope_breakpoint->disposition = disp_del;
10719
10720           /* Only break in the proper frame (help with recursion).  */
10721           scope_breakpoint->frame_id = caller_frame_id;
10722
10723           /* Set the address at which we will stop.  */
10724           scope_breakpoint->loc->gdbarch = caller_arch;
10725           scope_breakpoint->loc->requested_address = caller_pc;
10726           scope_breakpoint->loc->address
10727             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10728                                          scope_breakpoint->loc->requested_address,
10729                                          scope_breakpoint->type);
10730         }
10731     }
10732
10733   /* Now set up the breakpoint.  We create all watchpoints as hardware
10734      watchpoints here even if hardware watchpoints are turned off, a call
10735      to update_watchpoint later in this function will cause the type to
10736      drop back to bp_watchpoint (software watchpoint) if required.  */
10737
10738   if (accessflag == hw_read)
10739     bp_type = bp_read_watchpoint;
10740   else if (accessflag == hw_access)
10741     bp_type = bp_access_watchpoint;
10742   else
10743     bp_type = bp_hardware_watchpoint;
10744
10745   std::unique_ptr<watchpoint> w (new watchpoint ());
10746
10747   if (use_mask)
10748     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10749                                           &masked_watchpoint_breakpoint_ops);
10750   else
10751     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10752                                           &watchpoint_breakpoint_ops);
10753   w->thread = thread;
10754   w->disposition = disp_donttouch;
10755   w->pspace = current_program_space;
10756   w->exp = std::move (exp);
10757   w->exp_valid_block = exp_valid_block;
10758   w->cond_exp_valid_block = cond_exp_valid_block;
10759   if (just_location)
10760     {
10761       struct type *t = value_type (val.get ());
10762       CORE_ADDR addr = value_as_address (val.get ());
10763
10764       w->exp_string_reparse
10765         = current_language->la_watch_location_expression (t, addr).release ();
10766
10767       w->exp_string = xstrprintf ("-location %.*s",
10768                                   (int) (exp_end - exp_start), exp_start);
10769     }
10770   else
10771     w->exp_string = savestring (exp_start, exp_end - exp_start);
10772
10773   if (use_mask)
10774     {
10775       w->hw_wp_mask = mask;
10776     }
10777   else
10778     {
10779       w->val = val;
10780       w->val_bitpos = saved_bitpos;
10781       w->val_bitsize = saved_bitsize;
10782       w->val_valid = 1;
10783     }
10784
10785   if (cond_start)
10786     w->cond_string = savestring (cond_start, cond_end - cond_start);
10787   else
10788     w->cond_string = 0;
10789
10790   if (frame_id_p (watchpoint_frame))
10791     {
10792       w->watchpoint_frame = watchpoint_frame;
10793       w->watchpoint_thread = inferior_ptid;
10794     }
10795   else
10796     {
10797       w->watchpoint_frame = null_frame_id;
10798       w->watchpoint_thread = null_ptid;
10799     }
10800
10801   if (scope_breakpoint != NULL)
10802     {
10803       /* The scope breakpoint is related to the watchpoint.  We will
10804          need to act on them together.  */
10805       w->related_breakpoint = scope_breakpoint;
10806       scope_breakpoint->related_breakpoint = w.get ();
10807     }
10808
10809   if (!just_location)
10810     value_free_to_mark (mark);
10811
10812   /* Finally update the new watchpoint.  This creates the locations
10813      that should be inserted.  */
10814   update_watchpoint (w.get (), 1);
10815
10816   install_breakpoint (internal, std::move (w), 1);
10817 }
10818
10819 /* Return count of debug registers needed to watch the given expression.
10820    If the watchpoint cannot be handled in hardware return zero.  */
10821
10822 static int
10823 can_use_hardware_watchpoint (const std::vector<value_ref_ptr> &vals)
10824 {
10825   int found_memory_cnt = 0;
10826
10827   /* Did the user specifically forbid us to use hardware watchpoints? */
10828   if (!can_use_hw_watchpoints)
10829     return 0;
10830
10831   gdb_assert (!vals.empty ());
10832   struct value *head = vals[0].get ();
10833
10834   /* Make sure that the value of the expression depends only upon
10835      memory contents, and values computed from them within GDB.  If we
10836      find any register references or function calls, we can't use a
10837      hardware watchpoint.
10838
10839      The idea here is that evaluating an expression generates a series
10840      of values, one holding the value of every subexpression.  (The
10841      expression a*b+c has five subexpressions: a, b, a*b, c, and
10842      a*b+c.)  GDB's values hold almost enough information to establish
10843      the criteria given above --- they identify memory lvalues,
10844      register lvalues, computed values, etcetera.  So we can evaluate
10845      the expression, and then scan the chain of values that leaves
10846      behind to decide whether we can detect any possible change to the
10847      expression's final value using only hardware watchpoints.
10848
10849      However, I don't think that the values returned by inferior
10850      function calls are special in any way.  So this function may not
10851      notice that an expression involving an inferior function call
10852      can't be watched with hardware watchpoints.  FIXME.  */
10853   for (const value_ref_ptr &iter : vals)
10854     {
10855       struct value *v = iter.get ();
10856
10857       if (VALUE_LVAL (v) == lval_memory)
10858         {
10859           if (v != head && value_lazy (v))
10860             /* A lazy memory lvalue in the chain is one that GDB never
10861                needed to fetch; we either just used its address (e.g.,
10862                `a' in `a.b') or we never needed it at all (e.g., `a'
10863                in `a,b').  This doesn't apply to HEAD; if that is
10864                lazy then it was not readable, but watch it anyway.  */
10865             ;
10866           else
10867             {
10868               /* Ahh, memory we actually used!  Check if we can cover
10869                  it with hardware watchpoints.  */
10870               struct type *vtype = check_typedef (value_type (v));
10871
10872               /* We only watch structs and arrays if user asked for it
10873                  explicitly, never if they just happen to appear in a
10874                  middle of some value chain.  */
10875               if (v == head
10876                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
10877                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
10878                 {
10879                   CORE_ADDR vaddr = value_address (v);
10880                   int len;
10881                   int num_regs;
10882
10883                   len = (target_exact_watchpoints
10884                          && is_scalar_type_recursive (vtype))?
10885                     1 : TYPE_LENGTH (value_type (v));
10886
10887                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10888                   if (!num_regs)
10889                     return 0;
10890                   else
10891                     found_memory_cnt += num_regs;
10892                 }
10893             }
10894         }
10895       else if (VALUE_LVAL (v) != not_lval
10896                && deprecated_value_modifiable (v) == 0)
10897         return 0;       /* These are values from the history (e.g., $1).  */
10898       else if (VALUE_LVAL (v) == lval_register)
10899         return 0;       /* Cannot watch a register with a HW watchpoint.  */
10900     }
10901
10902   /* The expression itself looks suitable for using a hardware
10903      watchpoint, but give the target machine a chance to reject it.  */
10904   return found_memory_cnt;
10905 }
10906
10907 void
10908 watch_command_wrapper (const char *arg, int from_tty, int internal)
10909 {
10910   watch_command_1 (arg, hw_write, from_tty, 0, internal);
10911 }
10912
10913 /* A helper function that looks for the "-location" argument and then
10914    calls watch_command_1.  */
10915
10916 static void
10917 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
10918 {
10919   int just_location = 0;
10920
10921   if (arg
10922       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
10923           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
10924     {
10925       arg = skip_spaces (arg);
10926       just_location = 1;
10927     }
10928
10929   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
10930 }
10931
10932 static void
10933 watch_command (const char *arg, int from_tty)
10934 {
10935   watch_maybe_just_location (arg, hw_write, from_tty);
10936 }
10937
10938 void
10939 rwatch_command_wrapper (const char *arg, int from_tty, int internal)
10940 {
10941   watch_command_1 (arg, hw_read, from_tty, 0, internal);
10942 }
10943
10944 static void
10945 rwatch_command (const char *arg, int from_tty)
10946 {
10947   watch_maybe_just_location (arg, hw_read, from_tty);
10948 }
10949
10950 void
10951 awatch_command_wrapper (const char *arg, int from_tty, int internal)
10952 {
10953   watch_command_1 (arg, hw_access, from_tty, 0, internal);
10954 }
10955
10956 static void
10957 awatch_command (const char *arg, int from_tty)
10958 {
10959   watch_maybe_just_location (arg, hw_access, from_tty);
10960 }
10961 \f
10962
10963 /* Data for the FSM that manages the until(location)/advance commands
10964    in infcmd.c.  Here because it uses the mechanisms of
10965    breakpoints.  */
10966
10967 struct until_break_fsm
10968 {
10969   /* The base class.  */
10970   struct thread_fsm thread_fsm;
10971
10972   /* The thread that as current when the command was executed.  */
10973   int thread;
10974
10975   /* The breakpoint set at the destination location.  */
10976   struct breakpoint *location_breakpoint;
10977
10978   /* Breakpoint set at the return address in the caller frame.  May be
10979      NULL.  */
10980   struct breakpoint *caller_breakpoint;
10981 };
10982
10983 static void until_break_fsm_clean_up (struct thread_fsm *self,
10984                                       struct thread_info *thread);
10985 static int until_break_fsm_should_stop (struct thread_fsm *self,
10986                                         struct thread_info *thread);
10987 static enum async_reply_reason
10988   until_break_fsm_async_reply_reason (struct thread_fsm *self);
10989
10990 /* until_break_fsm's vtable.  */
10991
10992 static struct thread_fsm_ops until_break_fsm_ops =
10993 {
10994   NULL, /* dtor */
10995   until_break_fsm_clean_up,
10996   until_break_fsm_should_stop,
10997   NULL, /* return_value */
10998   until_break_fsm_async_reply_reason,
10999 };
11000
11001 /* Allocate a new until_break_command_fsm.  */
11002
11003 static struct until_break_fsm *
11004 new_until_break_fsm (struct interp *cmd_interp, int thread,
11005                      breakpoint_up &&location_breakpoint,
11006                      breakpoint_up &&caller_breakpoint)
11007 {
11008   struct until_break_fsm *sm;
11009
11010   sm = XCNEW (struct until_break_fsm);
11011   thread_fsm_ctor (&sm->thread_fsm, &until_break_fsm_ops, cmd_interp);
11012
11013   sm->thread = thread;
11014   sm->location_breakpoint = location_breakpoint.release ();
11015   sm->caller_breakpoint = caller_breakpoint.release ();
11016
11017   return sm;
11018 }
11019
11020 /* Implementation of the 'should_stop' FSM method for the
11021    until(location)/advance commands.  */
11022
11023 static int
11024 until_break_fsm_should_stop (struct thread_fsm *self,
11025                              struct thread_info *tp)
11026 {
11027   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11028
11029   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11030                               sm->location_breakpoint) != NULL
11031       || (sm->caller_breakpoint != NULL
11032           && bpstat_find_breakpoint (tp->control.stop_bpstat,
11033                                      sm->caller_breakpoint) != NULL))
11034     thread_fsm_set_finished (self);
11035
11036   return 1;
11037 }
11038
11039 /* Implementation of the 'clean_up' FSM method for the
11040    until(location)/advance commands.  */
11041
11042 static void
11043 until_break_fsm_clean_up (struct thread_fsm *self,
11044                           struct thread_info *thread)
11045 {
11046   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11047
11048   /* Clean up our temporary breakpoints.  */
11049   if (sm->location_breakpoint != NULL)
11050     {
11051       delete_breakpoint (sm->location_breakpoint);
11052       sm->location_breakpoint = NULL;
11053     }
11054   if (sm->caller_breakpoint != NULL)
11055     {
11056       delete_breakpoint (sm->caller_breakpoint);
11057       sm->caller_breakpoint = NULL;
11058     }
11059   delete_longjmp_breakpoint (sm->thread);
11060 }
11061
11062 /* Implementation of the 'async_reply_reason' FSM method for the
11063    until(location)/advance commands.  */
11064
11065 static enum async_reply_reason
11066 until_break_fsm_async_reply_reason (struct thread_fsm *self)
11067 {
11068   return EXEC_ASYNC_LOCATION_REACHED;
11069 }
11070
11071 void
11072 until_break_command (const char *arg, int from_tty, int anywhere)
11073 {
11074   struct frame_info *frame;
11075   struct gdbarch *frame_gdbarch;
11076   struct frame_id stack_frame_id;
11077   struct frame_id caller_frame_id;
11078   struct cleanup *old_chain;
11079   int thread;
11080   struct thread_info *tp;
11081   struct until_break_fsm *sm;
11082
11083   clear_proceed_status (0);
11084
11085   /* Set a breakpoint where the user wants it and at return from
11086      this function.  */
11087
11088   event_location_up location = string_to_event_location (&arg, current_language);
11089
11090   std::vector<symtab_and_line> sals
11091     = (last_displayed_sal_is_valid ()
11092        ? decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
11093                         get_last_displayed_symtab (),
11094                         get_last_displayed_line ())
11095        : decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
11096                         NULL, (struct symtab *) NULL, 0));
11097
11098   if (sals.size () != 1)
11099     error (_("Couldn't get information on specified line."));
11100
11101   symtab_and_line &sal = sals[0];
11102
11103   if (*arg)
11104     error (_("Junk at end of arguments."));
11105
11106   resolve_sal_pc (&sal);
11107
11108   tp = inferior_thread ();
11109   thread = tp->global_num;
11110
11111   old_chain = make_cleanup (null_cleanup, NULL);
11112
11113   /* Note linespec handling above invalidates the frame chain.
11114      Installing a breakpoint also invalidates the frame chain (as it
11115      may need to switch threads), so do any frame handling before
11116      that.  */
11117
11118   frame = get_selected_frame (NULL);
11119   frame_gdbarch = get_frame_arch (frame);
11120   stack_frame_id = get_stack_frame_id (frame);
11121   caller_frame_id = frame_unwind_caller_id (frame);
11122
11123   /* Keep within the current frame, or in frames called by the current
11124      one.  */
11125
11126   breakpoint_up caller_breakpoint;
11127   if (frame_id_p (caller_frame_id))
11128     {
11129       struct symtab_and_line sal2;
11130       struct gdbarch *caller_gdbarch;
11131
11132       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11133       sal2.pc = frame_unwind_caller_pc (frame);
11134       caller_gdbarch = frame_unwind_caller_arch (frame);
11135       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11136                                                     sal2,
11137                                                     caller_frame_id,
11138                                                     bp_until);
11139
11140       set_longjmp_breakpoint (tp, caller_frame_id);
11141       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11142     }
11143
11144   /* set_momentary_breakpoint could invalidate FRAME.  */
11145   frame = NULL;
11146
11147   breakpoint_up location_breakpoint;
11148   if (anywhere)
11149     /* If the user told us to continue until a specified location,
11150        we don't specify a frame at which we need to stop.  */
11151     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11152                                                     null_frame_id, bp_until);
11153   else
11154     /* Otherwise, specify the selected frame, because we want to stop
11155        only at the very same frame.  */
11156     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11157                                                     stack_frame_id, bp_until);
11158
11159   sm = new_until_break_fsm (command_interp (), tp->global_num,
11160                             std::move (location_breakpoint),
11161                             std::move (caller_breakpoint));
11162   tp->thread_fsm = &sm->thread_fsm;
11163
11164   discard_cleanups (old_chain);
11165
11166   proceed (-1, GDB_SIGNAL_DEFAULT);
11167 }
11168
11169 /* This function attempts to parse an optional "if <cond>" clause
11170    from the arg string.  If one is not found, it returns NULL.
11171
11172    Else, it returns a pointer to the condition string.  (It does not
11173    attempt to evaluate the string against a particular block.)  And,
11174    it updates arg to point to the first character following the parsed
11175    if clause in the arg string.  */
11176
11177 const char *
11178 ep_parse_optional_if_clause (const char **arg)
11179 {
11180   const char *cond_string;
11181
11182   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11183     return NULL;
11184
11185   /* Skip the "if" keyword.  */
11186   (*arg) += 2;
11187
11188   /* Skip any extra leading whitespace, and record the start of the
11189      condition string.  */
11190   *arg = skip_spaces (*arg);
11191   cond_string = *arg;
11192
11193   /* Assume that the condition occupies the remainder of the arg
11194      string.  */
11195   (*arg) += strlen (cond_string);
11196
11197   return cond_string;
11198 }
11199
11200 /* Commands to deal with catching events, such as signals, exceptions,
11201    process start/exit, etc.  */
11202
11203 typedef enum
11204 {
11205   catch_fork_temporary, catch_vfork_temporary,
11206   catch_fork_permanent, catch_vfork_permanent
11207 }
11208 catch_fork_kind;
11209
11210 static void
11211 catch_fork_command_1 (const char *arg, int from_tty,
11212                       struct cmd_list_element *command)
11213 {
11214   struct gdbarch *gdbarch = get_current_arch ();
11215   const char *cond_string = NULL;
11216   catch_fork_kind fork_kind;
11217   int tempflag;
11218
11219   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11220   tempflag = (fork_kind == catch_fork_temporary
11221               || fork_kind == catch_vfork_temporary);
11222
11223   if (!arg)
11224     arg = "";
11225   arg = skip_spaces (arg);
11226
11227   /* The allowed syntax is:
11228      catch [v]fork
11229      catch [v]fork if <cond>
11230
11231      First, check if there's an if clause.  */
11232   cond_string = ep_parse_optional_if_clause (&arg);
11233
11234   if ((*arg != '\0') && !isspace (*arg))
11235     error (_("Junk at end of arguments."));
11236
11237   /* If this target supports it, create a fork or vfork catchpoint
11238      and enable reporting of such events.  */
11239   switch (fork_kind)
11240     {
11241     case catch_fork_temporary:
11242     case catch_fork_permanent:
11243       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11244                                           &catch_fork_breakpoint_ops);
11245       break;
11246     case catch_vfork_temporary:
11247     case catch_vfork_permanent:
11248       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11249                                           &catch_vfork_breakpoint_ops);
11250       break;
11251     default:
11252       error (_("unsupported or unknown fork kind; cannot catch it"));
11253       break;
11254     }
11255 }
11256
11257 static void
11258 catch_exec_command_1 (const char *arg, int from_tty,
11259                       struct cmd_list_element *command)
11260 {
11261   struct gdbarch *gdbarch = get_current_arch ();
11262   int tempflag;
11263   const char *cond_string = NULL;
11264
11265   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11266
11267   if (!arg)
11268     arg = "";
11269   arg = skip_spaces (arg);
11270
11271   /* The allowed syntax is:
11272      catch exec
11273      catch exec if <cond>
11274
11275      First, check if there's an if clause.  */
11276   cond_string = ep_parse_optional_if_clause (&arg);
11277
11278   if ((*arg != '\0') && !isspace (*arg))
11279     error (_("Junk at end of arguments."));
11280
11281   std::unique_ptr<exec_catchpoint> c (new exec_catchpoint ());
11282   init_catchpoint (c.get (), gdbarch, tempflag, cond_string,
11283                    &catch_exec_breakpoint_ops);
11284   c->exec_pathname = NULL;
11285
11286   install_breakpoint (0, std::move (c), 1);
11287 }
11288
11289 void
11290 init_ada_exception_breakpoint (struct breakpoint *b,
11291                                struct gdbarch *gdbarch,
11292                                struct symtab_and_line sal,
11293                                const char *addr_string,
11294                                const struct breakpoint_ops *ops,
11295                                int tempflag,
11296                                int enabled,
11297                                int from_tty)
11298 {
11299   if (from_tty)
11300     {
11301       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11302       if (!loc_gdbarch)
11303         loc_gdbarch = gdbarch;
11304
11305       describe_other_breakpoints (loc_gdbarch,
11306                                   sal.pspace, sal.pc, sal.section, -1);
11307       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11308          version for exception catchpoints, because two catchpoints
11309          used for different exception names will use the same address.
11310          In this case, a "breakpoint ... also set at..." warning is
11311          unproductive.  Besides, the warning phrasing is also a bit
11312          inappropriate, we should use the word catchpoint, and tell
11313          the user what type of catchpoint it is.  The above is good
11314          enough for now, though.  */
11315     }
11316
11317   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11318
11319   b->enable_state = enabled ? bp_enabled : bp_disabled;
11320   b->disposition = tempflag ? disp_del : disp_donttouch;
11321   b->location = string_to_event_location (&addr_string,
11322                                           language_def (language_ada));
11323   b->language = language_ada;
11324 }
11325
11326 static void
11327 catch_command (const char *arg, int from_tty)
11328 {
11329   error (_("Catch requires an event name."));
11330 }
11331 \f
11332
11333 static void
11334 tcatch_command (const char *arg, int from_tty)
11335 {
11336   error (_("Catch requires an event name."));
11337 }
11338
11339 /* Compare two breakpoints and return a strcmp-like result.  */
11340
11341 static int
11342 compare_breakpoints (const breakpoint *a, const breakpoint *b)
11343 {
11344   uintptr_t ua = (uintptr_t) a;
11345   uintptr_t ub = (uintptr_t) b;
11346
11347   if (a->number < b->number)
11348     return -1;
11349   else if (a->number > b->number)
11350     return 1;
11351
11352   /* Now sort by address, in case we see, e..g, two breakpoints with
11353      the number 0.  */
11354   if (ua < ub)
11355     return -1;
11356   return ua > ub ? 1 : 0;
11357 }
11358
11359 /* Delete breakpoints by address or line.  */
11360
11361 static void
11362 clear_command (const char *arg, int from_tty)
11363 {
11364   struct breakpoint *b;
11365   int default_match;
11366
11367   std::vector<symtab_and_line> decoded_sals;
11368   symtab_and_line last_sal;
11369   gdb::array_view<symtab_and_line> sals;
11370   if (arg)
11371     {
11372       decoded_sals
11373         = decode_line_with_current_source (arg,
11374                                            (DECODE_LINE_FUNFIRSTLINE
11375                                             | DECODE_LINE_LIST_MODE));
11376       default_match = 0;
11377       sals = decoded_sals;
11378     }
11379   else
11380     {
11381       /* Set sal's line, symtab, pc, and pspace to the values
11382          corresponding to the last call to print_frame_info.  If the
11383          codepoint is not valid, this will set all the fields to 0.  */
11384       last_sal = get_last_displayed_sal ();
11385       if (last_sal.symtab == 0)
11386         error (_("No source file specified."));
11387
11388       default_match = 1;
11389       sals = last_sal;
11390     }
11391
11392   /* We don't call resolve_sal_pc here.  That's not as bad as it
11393      seems, because all existing breakpoints typically have both
11394      file/line and pc set.  So, if clear is given file/line, we can
11395      match this to existing breakpoint without obtaining pc at all.
11396
11397      We only support clearing given the address explicitly 
11398      present in breakpoint table.  Say, we've set breakpoint 
11399      at file:line.  There were several PC values for that file:line,
11400      due to optimization, all in one block.
11401
11402      We've picked one PC value.  If "clear" is issued with another
11403      PC corresponding to the same file:line, the breakpoint won't
11404      be cleared.  We probably can still clear the breakpoint, but 
11405      since the other PC value is never presented to user, user
11406      can only find it by guessing, and it does not seem important
11407      to support that.  */
11408
11409   /* For each line spec given, delete bps which correspond to it.  Do
11410      it in two passes, solely to preserve the current behavior that
11411      from_tty is forced true if we delete more than one
11412      breakpoint.  */
11413
11414   std::vector<struct breakpoint *> found;
11415   for (const auto &sal : sals)
11416     {
11417       const char *sal_fullname;
11418
11419       /* If exact pc given, clear bpts at that pc.
11420          If line given (pc == 0), clear all bpts on specified line.
11421          If defaulting, clear all bpts on default line
11422          or at default pc.
11423
11424          defaulting    sal.pc != 0    tests to do
11425
11426          0              1             pc
11427          1              1             pc _and_ line
11428          0              0             line
11429          1              0             <can't happen> */
11430
11431       sal_fullname = (sal.symtab == NULL
11432                       ? NULL : symtab_to_fullname (sal.symtab));
11433
11434       /* Find all matching breakpoints and add them to 'found'.  */
11435       ALL_BREAKPOINTS (b)
11436         {
11437           int match = 0;
11438           /* Are we going to delete b?  */
11439           if (b->type != bp_none && !is_watchpoint (b))
11440             {
11441               struct bp_location *loc = b->loc;
11442               for (; loc; loc = loc->next)
11443                 {
11444                   /* If the user specified file:line, don't allow a PC
11445                      match.  This matches historical gdb behavior.  */
11446                   int pc_match = (!sal.explicit_line
11447                                   && sal.pc
11448                                   && (loc->pspace == sal.pspace)
11449                                   && (loc->address == sal.pc)
11450                                   && (!section_is_overlay (loc->section)
11451                                       || loc->section == sal.section));
11452                   int line_match = 0;
11453
11454                   if ((default_match || sal.explicit_line)
11455                       && loc->symtab != NULL
11456                       && sal_fullname != NULL
11457                       && sal.pspace == loc->pspace
11458                       && loc->line_number == sal.line
11459                       && filename_cmp (symtab_to_fullname (loc->symtab),
11460                                        sal_fullname) == 0)
11461                     line_match = 1;
11462
11463                   if (pc_match || line_match)
11464                     {
11465                       match = 1;
11466                       break;
11467                     }
11468                 }
11469             }
11470
11471           if (match)
11472             found.push_back (b);
11473         }
11474     }
11475
11476   /* Now go thru the 'found' chain and delete them.  */
11477   if (found.empty ())
11478     {
11479       if (arg)
11480         error (_("No breakpoint at %s."), arg);
11481       else
11482         error (_("No breakpoint at this line."));
11483     }
11484
11485   /* Remove duplicates from the vec.  */
11486   std::sort (found.begin (), found.end (),
11487              [] (const breakpoint *bp_a, const breakpoint *bp_b)
11488              {
11489                return compare_breakpoints (bp_a, bp_b) < 0;
11490              });
11491   found.erase (std::unique (found.begin (), found.end (),
11492                             [] (const breakpoint *bp_a, const breakpoint *bp_b)
11493                             {
11494                               return compare_breakpoints (bp_a, bp_b) == 0;
11495                             }),
11496                found.end ());
11497
11498   if (found.size () > 1)
11499     from_tty = 1;       /* Always report if deleted more than one.  */
11500   if (from_tty)
11501     {
11502       if (found.size () == 1)
11503         printf_unfiltered (_("Deleted breakpoint "));
11504       else
11505         printf_unfiltered (_("Deleted breakpoints "));
11506     }
11507
11508   for (breakpoint *iter : found)
11509     {
11510       if (from_tty)
11511         printf_unfiltered ("%d ", iter->number);
11512       delete_breakpoint (iter);
11513     }
11514   if (from_tty)
11515     putchar_unfiltered ('\n');
11516 }
11517 \f
11518 /* Delete breakpoint in BS if they are `delete' breakpoints and
11519    all breakpoints that are marked for deletion, whether hit or not.
11520    This is called after any breakpoint is hit, or after errors.  */
11521
11522 void
11523 breakpoint_auto_delete (bpstat bs)
11524 {
11525   struct breakpoint *b, *b_tmp;
11526
11527   for (; bs; bs = bs->next)
11528     if (bs->breakpoint_at
11529         && bs->breakpoint_at->disposition == disp_del
11530         && bs->stop)
11531       delete_breakpoint (bs->breakpoint_at);
11532
11533   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11534   {
11535     if (b->disposition == disp_del_at_next_stop)
11536       delete_breakpoint (b);
11537   }
11538 }
11539
11540 /* A comparison function for bp_location AP and BP being interfaced to
11541    qsort.  Sort elements primarily by their ADDRESS (no matter what
11542    does breakpoint_address_is_meaningful say for its OWNER),
11543    secondarily by ordering first permanent elements and
11544    terciarily just ensuring the array is sorted stable way despite
11545    qsort being an unstable algorithm.  */
11546
11547 static int
11548 bp_locations_compare (const void *ap, const void *bp)
11549 {
11550   const struct bp_location *a = *(const struct bp_location **) ap;
11551   const struct bp_location *b = *(const struct bp_location **) bp;
11552
11553   if (a->address != b->address)
11554     return (a->address > b->address) - (a->address < b->address);
11555
11556   /* Sort locations at the same address by their pspace number, keeping
11557      locations of the same inferior (in a multi-inferior environment)
11558      grouped.  */
11559
11560   if (a->pspace->num != b->pspace->num)
11561     return ((a->pspace->num > b->pspace->num)
11562             - (a->pspace->num < b->pspace->num));
11563
11564   /* Sort permanent breakpoints first.  */
11565   if (a->permanent != b->permanent)
11566     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
11567
11568   /* Make the internal GDB representation stable across GDB runs
11569      where A and B memory inside GDB can differ.  Breakpoint locations of
11570      the same type at the same address can be sorted in arbitrary order.  */
11571
11572   if (a->owner->number != b->owner->number)
11573     return ((a->owner->number > b->owner->number)
11574             - (a->owner->number < b->owner->number));
11575
11576   return (a > b) - (a < b);
11577 }
11578
11579 /* Set bp_locations_placed_address_before_address_max and
11580    bp_locations_shadow_len_after_address_max according to the current
11581    content of the bp_locations array.  */
11582
11583 static void
11584 bp_locations_target_extensions_update (void)
11585 {
11586   struct bp_location *bl, **blp_tmp;
11587
11588   bp_locations_placed_address_before_address_max = 0;
11589   bp_locations_shadow_len_after_address_max = 0;
11590
11591   ALL_BP_LOCATIONS (bl, blp_tmp)
11592     {
11593       CORE_ADDR start, end, addr;
11594
11595       if (!bp_location_has_shadow (bl))
11596         continue;
11597
11598       start = bl->target_info.placed_address;
11599       end = start + bl->target_info.shadow_len;
11600
11601       gdb_assert (bl->address >= start);
11602       addr = bl->address - start;
11603       if (addr > bp_locations_placed_address_before_address_max)
11604         bp_locations_placed_address_before_address_max = addr;
11605
11606       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11607
11608       gdb_assert (bl->address < end);
11609       addr = end - bl->address;
11610       if (addr > bp_locations_shadow_len_after_address_max)
11611         bp_locations_shadow_len_after_address_max = addr;
11612     }
11613 }
11614
11615 /* Download tracepoint locations if they haven't been.  */
11616
11617 static void
11618 download_tracepoint_locations (void)
11619 {
11620   struct breakpoint *b;
11621   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11622
11623   scoped_restore_current_pspace_and_thread restore_pspace_thread;
11624
11625   ALL_TRACEPOINTS (b)
11626     {
11627       struct bp_location *bl;
11628       struct tracepoint *t;
11629       int bp_location_downloaded = 0;
11630
11631       if ((b->type == bp_fast_tracepoint
11632            ? !may_insert_fast_tracepoints
11633            : !may_insert_tracepoints))
11634         continue;
11635
11636       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11637         {
11638           if (target_can_download_tracepoint ())
11639             can_download_tracepoint = TRIBOOL_TRUE;
11640           else
11641             can_download_tracepoint = TRIBOOL_FALSE;
11642         }
11643
11644       if (can_download_tracepoint == TRIBOOL_FALSE)
11645         break;
11646
11647       for (bl = b->loc; bl; bl = bl->next)
11648         {
11649           /* In tracepoint, locations are _never_ duplicated, so
11650              should_be_inserted is equivalent to
11651              unduplicated_should_be_inserted.  */
11652           if (!should_be_inserted (bl) || bl->inserted)
11653             continue;
11654
11655           switch_to_program_space_and_thread (bl->pspace);
11656
11657           target_download_tracepoint (bl);
11658
11659           bl->inserted = 1;
11660           bp_location_downloaded = 1;
11661         }
11662       t = (struct tracepoint *) b;
11663       t->number_on_target = b->number;
11664       if (bp_location_downloaded)
11665         gdb::observers::breakpoint_modified.notify (b);
11666     }
11667 }
11668
11669 /* Swap the insertion/duplication state between two locations.  */
11670
11671 static void
11672 swap_insertion (struct bp_location *left, struct bp_location *right)
11673 {
11674   const int left_inserted = left->inserted;
11675   const int left_duplicate = left->duplicate;
11676   const int left_needs_update = left->needs_update;
11677   const struct bp_target_info left_target_info = left->target_info;
11678
11679   /* Locations of tracepoints can never be duplicated.  */
11680   if (is_tracepoint (left->owner))
11681     gdb_assert (!left->duplicate);
11682   if (is_tracepoint (right->owner))
11683     gdb_assert (!right->duplicate);
11684
11685   left->inserted = right->inserted;
11686   left->duplicate = right->duplicate;
11687   left->needs_update = right->needs_update;
11688   left->target_info = right->target_info;
11689   right->inserted = left_inserted;
11690   right->duplicate = left_duplicate;
11691   right->needs_update = left_needs_update;
11692   right->target_info = left_target_info;
11693 }
11694
11695 /* Force the re-insertion of the locations at ADDRESS.  This is called
11696    once a new/deleted/modified duplicate location is found and we are evaluating
11697    conditions on the target's side.  Such conditions need to be updated on
11698    the target.  */
11699
11700 static void
11701 force_breakpoint_reinsertion (struct bp_location *bl)
11702 {
11703   struct bp_location **locp = NULL, **loc2p;
11704   struct bp_location *loc;
11705   CORE_ADDR address = 0;
11706   int pspace_num;
11707
11708   address = bl->address;
11709   pspace_num = bl->pspace->num;
11710
11711   /* This is only meaningful if the target is
11712      evaluating conditions and if the user has
11713      opted for condition evaluation on the target's
11714      side.  */
11715   if (gdb_evaluates_breakpoint_condition_p ()
11716       || !target_supports_evaluation_of_breakpoint_conditions ())
11717     return;
11718
11719   /* Flag all breakpoint locations with this address and
11720      the same program space as the location
11721      as "its condition has changed".  We need to
11722      update the conditions on the target's side.  */
11723   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11724     {
11725       loc = *loc2p;
11726
11727       if (!is_breakpoint (loc->owner)
11728           || pspace_num != loc->pspace->num)
11729         continue;
11730
11731       /* Flag the location appropriately.  We use a different state to
11732          let everyone know that we already updated the set of locations
11733          with addr bl->address and program space bl->pspace.  This is so
11734          we don't have to keep calling these functions just to mark locations
11735          that have already been marked.  */
11736       loc->condition_changed = condition_updated;
11737
11738       /* Free the agent expression bytecode as well.  We will compute
11739          it later on.  */
11740       loc->cond_bytecode.reset ();
11741     }
11742 }
11743 /* Called whether new breakpoints are created, or existing breakpoints
11744    deleted, to update the global location list and recompute which
11745    locations are duplicate of which.
11746
11747    The INSERT_MODE flag determines whether locations may not, may, or
11748    shall be inserted now.  See 'enum ugll_insert_mode' for more
11749    info.  */
11750
11751 static void
11752 update_global_location_list (enum ugll_insert_mode insert_mode)
11753 {
11754   struct breakpoint *b;
11755   struct bp_location **locp, *loc;
11756   /* Last breakpoint location address that was marked for update.  */
11757   CORE_ADDR last_addr = 0;
11758   /* Last breakpoint location program space that was marked for update.  */
11759   int last_pspace_num = -1;
11760
11761   /* Used in the duplicates detection below.  When iterating over all
11762      bp_locations, points to the first bp_location of a given address.
11763      Breakpoints and watchpoints of different types are never
11764      duplicates of each other.  Keep one pointer for each type of
11765      breakpoint/watchpoint, so we only need to loop over all locations
11766      once.  */
11767   struct bp_location *bp_loc_first;  /* breakpoint */
11768   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11769   struct bp_location *awp_loc_first; /* access watchpoint */
11770   struct bp_location *rwp_loc_first; /* read watchpoint */
11771
11772   /* Saved former bp_locations array which we compare against the newly
11773      built bp_locations from the current state of ALL_BREAKPOINTS.  */
11774   struct bp_location **old_locp;
11775   unsigned old_locations_count;
11776   gdb::unique_xmalloc_ptr<struct bp_location *> old_locations (bp_locations);
11777
11778   old_locations_count = bp_locations_count;
11779   bp_locations = NULL;
11780   bp_locations_count = 0;
11781
11782   ALL_BREAKPOINTS (b)
11783     for (loc = b->loc; loc; loc = loc->next)
11784       bp_locations_count++;
11785
11786   bp_locations = XNEWVEC (struct bp_location *, bp_locations_count);
11787   locp = bp_locations;
11788   ALL_BREAKPOINTS (b)
11789     for (loc = b->loc; loc; loc = loc->next)
11790       *locp++ = loc;
11791   qsort (bp_locations, bp_locations_count, sizeof (*bp_locations),
11792          bp_locations_compare);
11793
11794   bp_locations_target_extensions_update ();
11795
11796   /* Identify bp_location instances that are no longer present in the
11797      new list, and therefore should be freed.  Note that it's not
11798      necessary that those locations should be removed from inferior --
11799      if there's another location at the same address (previously
11800      marked as duplicate), we don't need to remove/insert the
11801      location.
11802      
11803      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11804      and former bp_location array state respectively.  */
11805
11806   locp = bp_locations;
11807   for (old_locp = old_locations.get ();
11808        old_locp < old_locations.get () + old_locations_count;
11809        old_locp++)
11810     {
11811       struct bp_location *old_loc = *old_locp;
11812       struct bp_location **loc2p;
11813
11814       /* Tells if 'old_loc' is found among the new locations.  If
11815          not, we have to free it.  */
11816       int found_object = 0;
11817       /* Tells if the location should remain inserted in the target.  */
11818       int keep_in_target = 0;
11819       int removed = 0;
11820
11821       /* Skip LOCP entries which will definitely never be needed.
11822          Stop either at or being the one matching OLD_LOC.  */
11823       while (locp < bp_locations + bp_locations_count
11824              && (*locp)->address < old_loc->address)
11825         locp++;
11826
11827       for (loc2p = locp;
11828            (loc2p < bp_locations + bp_locations_count
11829             && (*loc2p)->address == old_loc->address);
11830            loc2p++)
11831         {
11832           /* Check if this is a new/duplicated location or a duplicated
11833              location that had its condition modified.  If so, we want to send
11834              its condition to the target if evaluation of conditions is taking
11835              place there.  */
11836           if ((*loc2p)->condition_changed == condition_modified
11837               && (last_addr != old_loc->address
11838                   || last_pspace_num != old_loc->pspace->num))
11839             {
11840               force_breakpoint_reinsertion (*loc2p);
11841               last_pspace_num = old_loc->pspace->num;
11842             }
11843
11844           if (*loc2p == old_loc)
11845             found_object = 1;
11846         }
11847
11848       /* We have already handled this address, update it so that we don't
11849          have to go through updates again.  */
11850       last_addr = old_loc->address;
11851
11852       /* Target-side condition evaluation: Handle deleted locations.  */
11853       if (!found_object)
11854         force_breakpoint_reinsertion (old_loc);
11855
11856       /* If this location is no longer present, and inserted, look if
11857          there's maybe a new location at the same address.  If so,
11858          mark that one inserted, and don't remove this one.  This is
11859          needed so that we don't have a time window where a breakpoint
11860          at certain location is not inserted.  */
11861
11862       if (old_loc->inserted)
11863         {
11864           /* If the location is inserted now, we might have to remove
11865              it.  */
11866
11867           if (found_object && should_be_inserted (old_loc))
11868             {
11869               /* The location is still present in the location list,
11870                  and still should be inserted.  Don't do anything.  */
11871               keep_in_target = 1;
11872             }
11873           else
11874             {
11875               /* This location still exists, but it won't be kept in the
11876                  target since it may have been disabled.  We proceed to
11877                  remove its target-side condition.  */
11878
11879               /* The location is either no longer present, or got
11880                  disabled.  See if there's another location at the
11881                  same address, in which case we don't need to remove
11882                  this one from the target.  */
11883
11884               /* OLD_LOC comes from existing struct breakpoint.  */
11885               if (breakpoint_address_is_meaningful (old_loc->owner))
11886                 {
11887                   for (loc2p = locp;
11888                        (loc2p < bp_locations + bp_locations_count
11889                         && (*loc2p)->address == old_loc->address);
11890                        loc2p++)
11891                     {
11892                       struct bp_location *loc2 = *loc2p;
11893
11894                       if (breakpoint_locations_match (loc2, old_loc))
11895                         {
11896                           /* Read watchpoint locations are switched to
11897                              access watchpoints, if the former are not
11898                              supported, but the latter are.  */
11899                           if (is_hardware_watchpoint (old_loc->owner))
11900                             {
11901                               gdb_assert (is_hardware_watchpoint (loc2->owner));
11902                               loc2->watchpoint_type = old_loc->watchpoint_type;
11903                             }
11904
11905                           /* loc2 is a duplicated location. We need to check
11906                              if it should be inserted in case it will be
11907                              unduplicated.  */
11908                           if (loc2 != old_loc
11909                               && unduplicated_should_be_inserted (loc2))
11910                             {
11911                               swap_insertion (old_loc, loc2);
11912                               keep_in_target = 1;
11913                               break;
11914                             }
11915                         }
11916                     }
11917                 }
11918             }
11919
11920           if (!keep_in_target)
11921             {
11922               if (remove_breakpoint (old_loc))
11923                 {
11924                   /* This is just about all we can do.  We could keep
11925                      this location on the global list, and try to
11926                      remove it next time, but there's no particular
11927                      reason why we will succeed next time.
11928                      
11929                      Note that at this point, old_loc->owner is still
11930                      valid, as delete_breakpoint frees the breakpoint
11931                      only after calling us.  */
11932                   printf_filtered (_("warning: Error removing "
11933                                      "breakpoint %d\n"), 
11934                                    old_loc->owner->number);
11935                 }
11936               removed = 1;
11937             }
11938         }
11939
11940       if (!found_object)
11941         {
11942           if (removed && target_is_non_stop_p ()
11943               && need_moribund_for_location_type (old_loc))
11944             {
11945               /* This location was removed from the target.  In
11946                  non-stop mode, a race condition is possible where
11947                  we've removed a breakpoint, but stop events for that
11948                  breakpoint are already queued and will arrive later.
11949                  We apply an heuristic to be able to distinguish such
11950                  SIGTRAPs from other random SIGTRAPs: we keep this
11951                  breakpoint location for a bit, and will retire it
11952                  after we see some number of events.  The theory here
11953                  is that reporting of events should, "on the average",
11954                  be fair, so after a while we'll see events from all
11955                  threads that have anything of interest, and no longer
11956                  need to keep this breakpoint location around.  We
11957                  don't hold locations forever so to reduce chances of
11958                  mistaking a non-breakpoint SIGTRAP for a breakpoint
11959                  SIGTRAP.
11960
11961                  The heuristic failing can be disastrous on
11962                  decr_pc_after_break targets.
11963
11964                  On decr_pc_after_break targets, like e.g., x86-linux,
11965                  if we fail to recognize a late breakpoint SIGTRAP,
11966                  because events_till_retirement has reached 0 too
11967                  soon, we'll fail to do the PC adjustment, and report
11968                  a random SIGTRAP to the user.  When the user resumes
11969                  the inferior, it will most likely immediately crash
11970                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
11971                  corrupted, because of being resumed e.g., in the
11972                  middle of a multi-byte instruction, or skipped a
11973                  one-byte instruction.  This was actually seen happen
11974                  on native x86-linux, and should be less rare on
11975                  targets that do not support new thread events, like
11976                  remote, due to the heuristic depending on
11977                  thread_count.
11978
11979                  Mistaking a random SIGTRAP for a breakpoint trap
11980                  causes similar symptoms (PC adjustment applied when
11981                  it shouldn't), but then again, playing with SIGTRAPs
11982                  behind the debugger's back is asking for trouble.
11983
11984                  Since hardware watchpoint traps are always
11985                  distinguishable from other traps, so we don't need to
11986                  apply keep hardware watchpoint moribund locations
11987                  around.  We simply always ignore hardware watchpoint
11988                  traps we can no longer explain.  */
11989
11990               old_loc->events_till_retirement = 3 * (thread_count () + 1);
11991               old_loc->owner = NULL;
11992
11993               moribund_locations.push_back (old_loc);
11994             }
11995           else
11996             {
11997               old_loc->owner = NULL;
11998               decref_bp_location (&old_loc);
11999             }
12000         }
12001     }
12002
12003   /* Rescan breakpoints at the same address and section, marking the
12004      first one as "first" and any others as "duplicates".  This is so
12005      that the bpt instruction is only inserted once.  If we have a
12006      permanent breakpoint at the same place as BPT, make that one the
12007      official one, and the rest as duplicates.  Permanent breakpoints
12008      are sorted first for the same address.
12009
12010      Do the same for hardware watchpoints, but also considering the
12011      watchpoint's type (regular/access/read) and length.  */
12012
12013   bp_loc_first = NULL;
12014   wp_loc_first = NULL;
12015   awp_loc_first = NULL;
12016   rwp_loc_first = NULL;
12017   ALL_BP_LOCATIONS (loc, locp)
12018     {
12019       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12020          non-NULL.  */
12021       struct bp_location **loc_first_p;
12022       b = loc->owner;
12023
12024       if (!unduplicated_should_be_inserted (loc)
12025           || !breakpoint_address_is_meaningful (b)
12026           /* Don't detect duplicate for tracepoint locations because they are
12027            never duplicated.  See the comments in field `duplicate' of
12028            `struct bp_location'.  */
12029           || is_tracepoint (b))
12030         {
12031           /* Clear the condition modification flag.  */
12032           loc->condition_changed = condition_unchanged;
12033           continue;
12034         }
12035
12036       if (b->type == bp_hardware_watchpoint)
12037         loc_first_p = &wp_loc_first;
12038       else if (b->type == bp_read_watchpoint)
12039         loc_first_p = &rwp_loc_first;
12040       else if (b->type == bp_access_watchpoint)
12041         loc_first_p = &awp_loc_first;
12042       else
12043         loc_first_p = &bp_loc_first;
12044
12045       if (*loc_first_p == NULL
12046           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12047           || !breakpoint_locations_match (loc, *loc_first_p))
12048         {
12049           *loc_first_p = loc;
12050           loc->duplicate = 0;
12051
12052           if (is_breakpoint (loc->owner) && loc->condition_changed)
12053             {
12054               loc->needs_update = 1;
12055               /* Clear the condition modification flag.  */
12056               loc->condition_changed = condition_unchanged;
12057             }
12058           continue;
12059         }
12060
12061
12062       /* This and the above ensure the invariant that the first location
12063          is not duplicated, and is the inserted one.
12064          All following are marked as duplicated, and are not inserted.  */
12065       if (loc->inserted)
12066         swap_insertion (loc, *loc_first_p);
12067       loc->duplicate = 1;
12068
12069       /* Clear the condition modification flag.  */
12070       loc->condition_changed = condition_unchanged;
12071     }
12072
12073   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12074     {
12075       if (insert_mode != UGLL_DONT_INSERT)
12076         insert_breakpoint_locations ();
12077       else
12078         {
12079           /* Even though the caller told us to not insert new
12080              locations, we may still need to update conditions on the
12081              target's side of breakpoints that were already inserted
12082              if the target is evaluating breakpoint conditions.  We
12083              only update conditions for locations that are marked
12084              "needs_update".  */
12085           update_inserted_breakpoint_locations ();
12086         }
12087     }
12088
12089   if (insert_mode != UGLL_DONT_INSERT)
12090     download_tracepoint_locations ();
12091 }
12092
12093 void
12094 breakpoint_retire_moribund (void)
12095 {
12096   for (int ix = 0; ix < moribund_locations.size (); ++ix)
12097     {
12098       struct bp_location *loc = moribund_locations[ix];
12099       if (--(loc->events_till_retirement) == 0)
12100         {
12101           decref_bp_location (&loc);
12102           unordered_remove (moribund_locations, ix);
12103           --ix;
12104         }
12105     }
12106 }
12107
12108 static void
12109 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12110 {
12111
12112   TRY
12113     {
12114       update_global_location_list (insert_mode);
12115     }
12116   CATCH (e, RETURN_MASK_ERROR)
12117     {
12118     }
12119   END_CATCH
12120 }
12121
12122 /* Clear BKP from a BPS.  */
12123
12124 static void
12125 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12126 {
12127   bpstat bs;
12128
12129   for (bs = bps; bs; bs = bs->next)
12130     if (bs->breakpoint_at == bpt)
12131       {
12132         bs->breakpoint_at = NULL;
12133         bs->old_val = NULL;
12134         /* bs->commands will be freed later.  */
12135       }
12136 }
12137
12138 /* Callback for iterate_over_threads.  */
12139 static int
12140 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12141 {
12142   struct breakpoint *bpt = (struct breakpoint *) data;
12143
12144   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12145   return 0;
12146 }
12147
12148 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12149    callbacks.  */
12150
12151 static void
12152 say_where (struct breakpoint *b)
12153 {
12154   struct value_print_options opts;
12155
12156   get_user_print_options (&opts);
12157
12158   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12159      single string.  */
12160   if (b->loc == NULL)
12161     {
12162       /* For pending locations, the output differs slightly based
12163          on b->extra_string.  If this is non-NULL, it contains either
12164          a condition or dprintf arguments.  */
12165       if (b->extra_string == NULL)
12166         {
12167           printf_filtered (_(" (%s) pending."),
12168                            event_location_to_string (b->location.get ()));
12169         }
12170       else if (b->type == bp_dprintf)
12171         {
12172           printf_filtered (_(" (%s,%s) pending."),
12173                            event_location_to_string (b->location.get ()),
12174                            b->extra_string);
12175         }
12176       else
12177         {
12178           printf_filtered (_(" (%s %s) pending."),
12179                            event_location_to_string (b->location.get ()),
12180                            b->extra_string);
12181         }
12182     }
12183   else
12184     {
12185       if (opts.addressprint || b->loc->symtab == NULL)
12186         {
12187           printf_filtered (" at ");
12188           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12189                           gdb_stdout);
12190         }
12191       if (b->loc->symtab != NULL)
12192         {
12193           /* If there is a single location, we can print the location
12194              more nicely.  */
12195           if (b->loc->next == NULL)
12196             printf_filtered (": file %s, line %d.",
12197                              symtab_to_filename_for_display (b->loc->symtab),
12198                              b->loc->line_number);
12199           else
12200             /* This is not ideal, but each location may have a
12201                different file name, and this at least reflects the
12202                real situation somewhat.  */
12203             printf_filtered (": %s.",
12204                              event_location_to_string (b->location.get ()));
12205         }
12206
12207       if (b->loc->next)
12208         {
12209           struct bp_location *loc = b->loc;
12210           int n = 0;
12211           for (; loc; loc = loc->next)
12212             ++n;
12213           printf_filtered (" (%d locations)", n);
12214         }
12215     }
12216 }
12217
12218 /* Default bp_location_ops methods.  */
12219
12220 static void
12221 bp_location_dtor (struct bp_location *self)
12222 {
12223   xfree (self->function_name);
12224 }
12225
12226 static const struct bp_location_ops bp_location_ops =
12227 {
12228   bp_location_dtor
12229 };
12230
12231 /* Destructor for the breakpoint base class.  */
12232
12233 breakpoint::~breakpoint ()
12234 {
12235   xfree (this->cond_string);
12236   xfree (this->extra_string);
12237   xfree (this->filter);
12238 }
12239
12240 static struct bp_location *
12241 base_breakpoint_allocate_location (struct breakpoint *self)
12242 {
12243   return new bp_location (&bp_location_ops, self);
12244 }
12245
12246 static void
12247 base_breakpoint_re_set (struct breakpoint *b)
12248 {
12249   /* Nothing to re-set. */
12250 }
12251
12252 #define internal_error_pure_virtual_called() \
12253   gdb_assert_not_reached ("pure virtual function called")
12254
12255 static int
12256 base_breakpoint_insert_location (struct bp_location *bl)
12257 {
12258   internal_error_pure_virtual_called ();
12259 }
12260
12261 static int
12262 base_breakpoint_remove_location (struct bp_location *bl,
12263                                  enum remove_bp_reason reason)
12264 {
12265   internal_error_pure_virtual_called ();
12266 }
12267
12268 static int
12269 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12270                                 const address_space *aspace,
12271                                 CORE_ADDR bp_addr,
12272                                 const struct target_waitstatus *ws)
12273 {
12274   internal_error_pure_virtual_called ();
12275 }
12276
12277 static void
12278 base_breakpoint_check_status (bpstat bs)
12279 {
12280   /* Always stop.   */
12281 }
12282
12283 /* A "works_in_software_mode" breakpoint_ops method that just internal
12284    errors.  */
12285
12286 static int
12287 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12288 {
12289   internal_error_pure_virtual_called ();
12290 }
12291
12292 /* A "resources_needed" breakpoint_ops method that just internal
12293    errors.  */
12294
12295 static int
12296 base_breakpoint_resources_needed (const struct bp_location *bl)
12297 {
12298   internal_error_pure_virtual_called ();
12299 }
12300
12301 static enum print_stop_action
12302 base_breakpoint_print_it (bpstat bs)
12303 {
12304   internal_error_pure_virtual_called ();
12305 }
12306
12307 static void
12308 base_breakpoint_print_one_detail (const struct breakpoint *self,
12309                                   struct ui_out *uiout)
12310 {
12311   /* nothing */
12312 }
12313
12314 static void
12315 base_breakpoint_print_mention (struct breakpoint *b)
12316 {
12317   internal_error_pure_virtual_called ();
12318 }
12319
12320 static void
12321 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12322 {
12323   internal_error_pure_virtual_called ();
12324 }
12325
12326 static void
12327 base_breakpoint_create_sals_from_location
12328   (const struct event_location *location,
12329    struct linespec_result *canonical,
12330    enum bptype type_wanted)
12331 {
12332   internal_error_pure_virtual_called ();
12333 }
12334
12335 static void
12336 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12337                                         struct linespec_result *c,
12338                                         gdb::unique_xmalloc_ptr<char> cond_string,
12339                                         gdb::unique_xmalloc_ptr<char> extra_string,
12340                                         enum bptype type_wanted,
12341                                         enum bpdisp disposition,
12342                                         int thread,
12343                                         int task, int ignore_count,
12344                                         const struct breakpoint_ops *o,
12345                                         int from_tty, int enabled,
12346                                         int internal, unsigned flags)
12347 {
12348   internal_error_pure_virtual_called ();
12349 }
12350
12351 static std::vector<symtab_and_line>
12352 base_breakpoint_decode_location (struct breakpoint *b,
12353                                  const struct event_location *location,
12354                                  struct program_space *search_pspace)
12355 {
12356   internal_error_pure_virtual_called ();
12357 }
12358
12359 /* The default 'explains_signal' method.  */
12360
12361 static int
12362 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12363 {
12364   return 1;
12365 }
12366
12367 /* The default "after_condition_true" method.  */
12368
12369 static void
12370 base_breakpoint_after_condition_true (struct bpstats *bs)
12371 {
12372   /* Nothing to do.   */
12373 }
12374
12375 struct breakpoint_ops base_breakpoint_ops =
12376 {
12377   base_breakpoint_allocate_location,
12378   base_breakpoint_re_set,
12379   base_breakpoint_insert_location,
12380   base_breakpoint_remove_location,
12381   base_breakpoint_breakpoint_hit,
12382   base_breakpoint_check_status,
12383   base_breakpoint_resources_needed,
12384   base_breakpoint_works_in_software_mode,
12385   base_breakpoint_print_it,
12386   NULL,
12387   base_breakpoint_print_one_detail,
12388   base_breakpoint_print_mention,
12389   base_breakpoint_print_recreate,
12390   base_breakpoint_create_sals_from_location,
12391   base_breakpoint_create_breakpoints_sal,
12392   base_breakpoint_decode_location,
12393   base_breakpoint_explains_signal,
12394   base_breakpoint_after_condition_true,
12395 };
12396
12397 /* Default breakpoint_ops methods.  */
12398
12399 static void
12400 bkpt_re_set (struct breakpoint *b)
12401 {
12402   /* FIXME: is this still reachable?  */
12403   if (breakpoint_event_location_empty_p (b))
12404     {
12405       /* Anything without a location can't be re-set.  */
12406       delete_breakpoint (b);
12407       return;
12408     }
12409
12410   breakpoint_re_set_default (b);
12411 }
12412
12413 static int
12414 bkpt_insert_location (struct bp_location *bl)
12415 {
12416   CORE_ADDR addr = bl->target_info.reqstd_address;
12417
12418   bl->target_info.kind = breakpoint_kind (bl, &addr);
12419   bl->target_info.placed_address = addr;
12420
12421   if (bl->loc_type == bp_loc_hardware_breakpoint)
12422     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12423   else
12424     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12425 }
12426
12427 static int
12428 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
12429 {
12430   if (bl->loc_type == bp_loc_hardware_breakpoint)
12431     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12432   else
12433     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12434 }
12435
12436 static int
12437 bkpt_breakpoint_hit (const struct bp_location *bl,
12438                      const address_space *aspace, CORE_ADDR bp_addr,
12439                      const struct target_waitstatus *ws)
12440 {
12441   if (ws->kind != TARGET_WAITKIND_STOPPED
12442       || ws->value.sig != GDB_SIGNAL_TRAP)
12443     return 0;
12444
12445   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12446                                  aspace, bp_addr))
12447     return 0;
12448
12449   if (overlay_debugging         /* unmapped overlay section */
12450       && section_is_overlay (bl->section)
12451       && !section_is_mapped (bl->section))
12452     return 0;
12453
12454   return 1;
12455 }
12456
12457 static int
12458 dprintf_breakpoint_hit (const struct bp_location *bl,
12459                         const address_space *aspace, CORE_ADDR bp_addr,
12460                         const struct target_waitstatus *ws)
12461 {
12462   if (dprintf_style == dprintf_style_agent
12463       && target_can_run_breakpoint_commands ())
12464     {
12465       /* An agent-style dprintf never causes a stop.  If we see a trap
12466          for this address it must be for a breakpoint that happens to
12467          be set at the same address.  */
12468       return 0;
12469     }
12470
12471   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12472 }
12473
12474 static int
12475 bkpt_resources_needed (const struct bp_location *bl)
12476 {
12477   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12478
12479   return 1;
12480 }
12481
12482 static enum print_stop_action
12483 bkpt_print_it (bpstat bs)
12484 {
12485   struct breakpoint *b;
12486   const struct bp_location *bl;
12487   int bp_temp;
12488   struct ui_out *uiout = current_uiout;
12489
12490   gdb_assert (bs->bp_location_at != NULL);
12491
12492   bl = bs->bp_location_at;
12493   b = bs->breakpoint_at;
12494
12495   bp_temp = b->disposition == disp_del;
12496   if (bl->address != bl->requested_address)
12497     breakpoint_adjustment_warning (bl->requested_address,
12498                                    bl->address,
12499                                    b->number, 1);
12500   annotate_breakpoint (b->number);
12501   maybe_print_thread_hit_breakpoint (uiout);
12502
12503   if (bp_temp)
12504     uiout->text ("Temporary breakpoint ");
12505   else
12506     uiout->text ("Breakpoint ");
12507   if (uiout->is_mi_like_p ())
12508     {
12509       uiout->field_string ("reason",
12510                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12511       uiout->field_string ("disp", bpdisp_text (b->disposition));
12512     }
12513   uiout->field_int ("bkptno", b->number);
12514   uiout->text (", ");
12515
12516   return PRINT_SRC_AND_LOC;
12517 }
12518
12519 static void
12520 bkpt_print_mention (struct breakpoint *b)
12521 {
12522   if (current_uiout->is_mi_like_p ())
12523     return;
12524
12525   switch (b->type)
12526     {
12527     case bp_breakpoint:
12528     case bp_gnu_ifunc_resolver:
12529       if (b->disposition == disp_del)
12530         printf_filtered (_("Temporary breakpoint"));
12531       else
12532         printf_filtered (_("Breakpoint"));
12533       printf_filtered (_(" %d"), b->number);
12534       if (b->type == bp_gnu_ifunc_resolver)
12535         printf_filtered (_(" at gnu-indirect-function resolver"));
12536       break;
12537     case bp_hardware_breakpoint:
12538       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12539       break;
12540     case bp_dprintf:
12541       printf_filtered (_("Dprintf %d"), b->number);
12542       break;
12543     }
12544
12545   say_where (b);
12546 }
12547
12548 static void
12549 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12550 {
12551   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12552     fprintf_unfiltered (fp, "tbreak");
12553   else if (tp->type == bp_breakpoint)
12554     fprintf_unfiltered (fp, "break");
12555   else if (tp->type == bp_hardware_breakpoint
12556            && tp->disposition == disp_del)
12557     fprintf_unfiltered (fp, "thbreak");
12558   else if (tp->type == bp_hardware_breakpoint)
12559     fprintf_unfiltered (fp, "hbreak");
12560   else
12561     internal_error (__FILE__, __LINE__,
12562                     _("unhandled breakpoint type %d"), (int) tp->type);
12563
12564   fprintf_unfiltered (fp, " %s",
12565                       event_location_to_string (tp->location.get ()));
12566
12567   /* Print out extra_string if this breakpoint is pending.  It might
12568      contain, for example, conditions that were set by the user.  */
12569   if (tp->loc == NULL && tp->extra_string != NULL)
12570     fprintf_unfiltered (fp, " %s", tp->extra_string);
12571
12572   print_recreate_thread (tp, fp);
12573 }
12574
12575 static void
12576 bkpt_create_sals_from_location (const struct event_location *location,
12577                                 struct linespec_result *canonical,
12578                                 enum bptype type_wanted)
12579 {
12580   create_sals_from_location_default (location, canonical, type_wanted);
12581 }
12582
12583 static void
12584 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12585                              struct linespec_result *canonical,
12586                              gdb::unique_xmalloc_ptr<char> cond_string,
12587                              gdb::unique_xmalloc_ptr<char> extra_string,
12588                              enum bptype type_wanted,
12589                              enum bpdisp disposition,
12590                              int thread,
12591                              int task, int ignore_count,
12592                              const struct breakpoint_ops *ops,
12593                              int from_tty, int enabled,
12594                              int internal, unsigned flags)
12595 {
12596   create_breakpoints_sal_default (gdbarch, canonical,
12597                                   std::move (cond_string),
12598                                   std::move (extra_string),
12599                                   type_wanted,
12600                                   disposition, thread, task,
12601                                   ignore_count, ops, from_tty,
12602                                   enabled, internal, flags);
12603 }
12604
12605 static std::vector<symtab_and_line>
12606 bkpt_decode_location (struct breakpoint *b,
12607                       const struct event_location *location,
12608                       struct program_space *search_pspace)
12609 {
12610   return decode_location_default (b, location, search_pspace);
12611 }
12612
12613 /* Virtual table for internal breakpoints.  */
12614
12615 static void
12616 internal_bkpt_re_set (struct breakpoint *b)
12617 {
12618   switch (b->type)
12619     {
12620       /* Delete overlay event and longjmp master breakpoints; they
12621          will be reset later by breakpoint_re_set.  */
12622     case bp_overlay_event:
12623     case bp_longjmp_master:
12624     case bp_std_terminate_master:
12625     case bp_exception_master:
12626       delete_breakpoint (b);
12627       break;
12628
12629       /* This breakpoint is special, it's set up when the inferior
12630          starts and we really don't want to touch it.  */
12631     case bp_shlib_event:
12632
12633       /* Like bp_shlib_event, this breakpoint type is special.  Once
12634          it is set up, we do not want to touch it.  */
12635     case bp_thread_event:
12636       break;
12637     }
12638 }
12639
12640 static void
12641 internal_bkpt_check_status (bpstat bs)
12642 {
12643   if (bs->breakpoint_at->type == bp_shlib_event)
12644     {
12645       /* If requested, stop when the dynamic linker notifies GDB of
12646          events.  This allows the user to get control and place
12647          breakpoints in initializer routines for dynamically loaded
12648          objects (among other things).  */
12649       bs->stop = stop_on_solib_events;
12650       bs->print = stop_on_solib_events;
12651     }
12652   else
12653     bs->stop = 0;
12654 }
12655
12656 static enum print_stop_action
12657 internal_bkpt_print_it (bpstat bs)
12658 {
12659   struct breakpoint *b;
12660
12661   b = bs->breakpoint_at;
12662
12663   switch (b->type)
12664     {
12665     case bp_shlib_event:
12666       /* Did we stop because the user set the stop_on_solib_events
12667          variable?  (If so, we report this as a generic, "Stopped due
12668          to shlib event" message.) */
12669       print_solib_event (0);
12670       break;
12671
12672     case bp_thread_event:
12673       /* Not sure how we will get here.
12674          GDB should not stop for these breakpoints.  */
12675       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12676       break;
12677
12678     case bp_overlay_event:
12679       /* By analogy with the thread event, GDB should not stop for these.  */
12680       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12681       break;
12682
12683     case bp_longjmp_master:
12684       /* These should never be enabled.  */
12685       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12686       break;
12687
12688     case bp_std_terminate_master:
12689       /* These should never be enabled.  */
12690       printf_filtered (_("std::terminate Master Breakpoint: "
12691                          "gdb should not stop!\n"));
12692       break;
12693
12694     case bp_exception_master:
12695       /* These should never be enabled.  */
12696       printf_filtered (_("Exception Master Breakpoint: "
12697                          "gdb should not stop!\n"));
12698       break;
12699     }
12700
12701   return PRINT_NOTHING;
12702 }
12703
12704 static void
12705 internal_bkpt_print_mention (struct breakpoint *b)
12706 {
12707   /* Nothing to mention.  These breakpoints are internal.  */
12708 }
12709
12710 /* Virtual table for momentary breakpoints  */
12711
12712 static void
12713 momentary_bkpt_re_set (struct breakpoint *b)
12714 {
12715   /* Keep temporary breakpoints, which can be encountered when we step
12716      over a dlopen call and solib_add is resetting the breakpoints.
12717      Otherwise these should have been blown away via the cleanup chain
12718      or by breakpoint_init_inferior when we rerun the executable.  */
12719 }
12720
12721 static void
12722 momentary_bkpt_check_status (bpstat bs)
12723 {
12724   /* Nothing.  The point of these breakpoints is causing a stop.  */
12725 }
12726
12727 static enum print_stop_action
12728 momentary_bkpt_print_it (bpstat bs)
12729 {
12730   return PRINT_UNKNOWN;
12731 }
12732
12733 static void
12734 momentary_bkpt_print_mention (struct breakpoint *b)
12735 {
12736   /* Nothing to mention.  These breakpoints are internal.  */
12737 }
12738
12739 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12740
12741    It gets cleared already on the removal of the first one of such placed
12742    breakpoints.  This is OK as they get all removed altogether.  */
12743
12744 longjmp_breakpoint::~longjmp_breakpoint ()
12745 {
12746   thread_info *tp = find_thread_global_id (this->thread);
12747
12748   if (tp != NULL)
12749     tp->initiating_frame = null_frame_id;
12750 }
12751
12752 /* Specific methods for probe breakpoints.  */
12753
12754 static int
12755 bkpt_probe_insert_location (struct bp_location *bl)
12756 {
12757   int v = bkpt_insert_location (bl);
12758
12759   if (v == 0)
12760     {
12761       /* The insertion was successful, now let's set the probe's semaphore
12762          if needed.  */
12763       bl->probe.prob->set_semaphore (bl->probe.objfile, bl->gdbarch);
12764     }
12765
12766   return v;
12767 }
12768
12769 static int
12770 bkpt_probe_remove_location (struct bp_location *bl,
12771                             enum remove_bp_reason reason)
12772 {
12773   /* Let's clear the semaphore before removing the location.  */
12774   bl->probe.prob->clear_semaphore (bl->probe.objfile, bl->gdbarch);
12775
12776   return bkpt_remove_location (bl, reason);
12777 }
12778
12779 static void
12780 bkpt_probe_create_sals_from_location (const struct event_location *location,
12781                                       struct linespec_result *canonical,
12782                                       enum bptype type_wanted)
12783 {
12784   struct linespec_sals lsal;
12785
12786   lsal.sals = parse_probes (location, NULL, canonical);
12787   lsal.canonical
12788     = xstrdup (event_location_to_string (canonical->location.get ()));
12789   canonical->lsals.push_back (std::move (lsal));
12790 }
12791
12792 static std::vector<symtab_and_line>
12793 bkpt_probe_decode_location (struct breakpoint *b,
12794                             const struct event_location *location,
12795                             struct program_space *search_pspace)
12796 {
12797   std::vector<symtab_and_line> sals = parse_probes (location, search_pspace, NULL);
12798   if (sals.empty ())
12799     error (_("probe not found"));
12800   return sals;
12801 }
12802
12803 /* The breakpoint_ops structure to be used in tracepoints.  */
12804
12805 static void
12806 tracepoint_re_set (struct breakpoint *b)
12807 {
12808   breakpoint_re_set_default (b);
12809 }
12810
12811 static int
12812 tracepoint_breakpoint_hit (const struct bp_location *bl,
12813                            const address_space *aspace, CORE_ADDR bp_addr,
12814                            const struct target_waitstatus *ws)
12815 {
12816   /* By definition, the inferior does not report stops at
12817      tracepoints.  */
12818   return 0;
12819 }
12820
12821 static void
12822 tracepoint_print_one_detail (const struct breakpoint *self,
12823                              struct ui_out *uiout)
12824 {
12825   struct tracepoint *tp = (struct tracepoint *) self;
12826   if (!tp->static_trace_marker_id.empty ())
12827     {
12828       gdb_assert (self->type == bp_static_tracepoint);
12829
12830       uiout->text ("\tmarker id is ");
12831       uiout->field_string ("static-tracepoint-marker-string-id",
12832                            tp->static_trace_marker_id);
12833       uiout->text ("\n");
12834     }
12835 }
12836
12837 static void
12838 tracepoint_print_mention (struct breakpoint *b)
12839 {
12840   if (current_uiout->is_mi_like_p ())
12841     return;
12842
12843   switch (b->type)
12844     {
12845     case bp_tracepoint:
12846       printf_filtered (_("Tracepoint"));
12847       printf_filtered (_(" %d"), b->number);
12848       break;
12849     case bp_fast_tracepoint:
12850       printf_filtered (_("Fast tracepoint"));
12851       printf_filtered (_(" %d"), b->number);
12852       break;
12853     case bp_static_tracepoint:
12854       printf_filtered (_("Static tracepoint"));
12855       printf_filtered (_(" %d"), b->number);
12856       break;
12857     default:
12858       internal_error (__FILE__, __LINE__,
12859                       _("unhandled tracepoint type %d"), (int) b->type);
12860     }
12861
12862   say_where (b);
12863 }
12864
12865 static void
12866 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
12867 {
12868   struct tracepoint *tp = (struct tracepoint *) self;
12869
12870   if (self->type == bp_fast_tracepoint)
12871     fprintf_unfiltered (fp, "ftrace");
12872   else if (self->type == bp_static_tracepoint)
12873     fprintf_unfiltered (fp, "strace");
12874   else if (self->type == bp_tracepoint)
12875     fprintf_unfiltered (fp, "trace");
12876   else
12877     internal_error (__FILE__, __LINE__,
12878                     _("unhandled tracepoint type %d"), (int) self->type);
12879
12880   fprintf_unfiltered (fp, " %s",
12881                       event_location_to_string (self->location.get ()));
12882   print_recreate_thread (self, fp);
12883
12884   if (tp->pass_count)
12885     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
12886 }
12887
12888 static void
12889 tracepoint_create_sals_from_location (const struct event_location *location,
12890                                       struct linespec_result *canonical,
12891                                       enum bptype type_wanted)
12892 {
12893   create_sals_from_location_default (location, canonical, type_wanted);
12894 }
12895
12896 static void
12897 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12898                                    struct linespec_result *canonical,
12899                                    gdb::unique_xmalloc_ptr<char> cond_string,
12900                                    gdb::unique_xmalloc_ptr<char> extra_string,
12901                                    enum bptype type_wanted,
12902                                    enum bpdisp disposition,
12903                                    int thread,
12904                                    int task, int ignore_count,
12905                                    const struct breakpoint_ops *ops,
12906                                    int from_tty, int enabled,
12907                                    int internal, unsigned flags)
12908 {
12909   create_breakpoints_sal_default (gdbarch, canonical,
12910                                   std::move (cond_string),
12911                                   std::move (extra_string),
12912                                   type_wanted,
12913                                   disposition, thread, task,
12914                                   ignore_count, ops, from_tty,
12915                                   enabled, internal, flags);
12916 }
12917
12918 static std::vector<symtab_and_line>
12919 tracepoint_decode_location (struct breakpoint *b,
12920                             const struct event_location *location,
12921                             struct program_space *search_pspace)
12922 {
12923   return decode_location_default (b, location, search_pspace);
12924 }
12925
12926 struct breakpoint_ops tracepoint_breakpoint_ops;
12927
12928 /* The breakpoint_ops structure to be use on tracepoints placed in a
12929    static probe.  */
12930
12931 static void
12932 tracepoint_probe_create_sals_from_location
12933   (const struct event_location *location,
12934    struct linespec_result *canonical,
12935    enum bptype type_wanted)
12936 {
12937   /* We use the same method for breakpoint on probes.  */
12938   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
12939 }
12940
12941 static std::vector<symtab_and_line>
12942 tracepoint_probe_decode_location (struct breakpoint *b,
12943                                   const struct event_location *location,
12944                                   struct program_space *search_pspace)
12945 {
12946   /* We use the same method for breakpoint on probes.  */
12947   return bkpt_probe_decode_location (b, location, search_pspace);
12948 }
12949
12950 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
12951
12952 /* Dprintf breakpoint_ops methods.  */
12953
12954 static void
12955 dprintf_re_set (struct breakpoint *b)
12956 {
12957   breakpoint_re_set_default (b);
12958
12959   /* extra_string should never be non-NULL for dprintf.  */
12960   gdb_assert (b->extra_string != NULL);
12961
12962   /* 1 - connect to target 1, that can run breakpoint commands.
12963      2 - create a dprintf, which resolves fine.
12964      3 - disconnect from target 1
12965      4 - connect to target 2, that can NOT run breakpoint commands.
12966
12967      After steps #3/#4, you'll want the dprintf command list to
12968      be updated, because target 1 and 2 may well return different
12969      answers for target_can_run_breakpoint_commands().
12970      Given absence of finer grained resetting, we get to do
12971      it all the time.  */
12972   if (b->extra_string != NULL)
12973     update_dprintf_command_list (b);
12974 }
12975
12976 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
12977
12978 static void
12979 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12980 {
12981   fprintf_unfiltered (fp, "dprintf %s,%s",
12982                       event_location_to_string (tp->location.get ()),
12983                       tp->extra_string);
12984   print_recreate_thread (tp, fp);
12985 }
12986
12987 /* Implement the "after_condition_true" breakpoint_ops method for
12988    dprintf.
12989
12990    dprintf's are implemented with regular commands in their command
12991    list, but we run the commands here instead of before presenting the
12992    stop to the user, as dprintf's don't actually cause a stop.  This
12993    also makes it so that the commands of multiple dprintfs at the same
12994    address are all handled.  */
12995
12996 static void
12997 dprintf_after_condition_true (struct bpstats *bs)
12998 {
12999   struct bpstats tmp_bs;
13000   struct bpstats *tmp_bs_p = &tmp_bs;
13001
13002   /* dprintf's never cause a stop.  This wasn't set in the
13003      check_status hook instead because that would make the dprintf's
13004      condition not be evaluated.  */
13005   bs->stop = 0;
13006
13007   /* Run the command list here.  Take ownership of it instead of
13008      copying.  We never want these commands to run later in
13009      bpstat_do_actions, if a breakpoint that causes a stop happens to
13010      be set at same address as this dprintf, or even if running the
13011      commands here throws.  */
13012   tmp_bs.commands = bs->commands;
13013   bs->commands = NULL;
13014
13015   bpstat_do_actions_1 (&tmp_bs_p);
13016
13017   /* 'tmp_bs.commands' will usually be NULL by now, but
13018      bpstat_do_actions_1 may return early without processing the whole
13019      list.  */
13020 }
13021
13022 /* The breakpoint_ops structure to be used on static tracepoints with
13023    markers (`-m').  */
13024
13025 static void
13026 strace_marker_create_sals_from_location (const struct event_location *location,
13027                                          struct linespec_result *canonical,
13028                                          enum bptype type_wanted)
13029 {
13030   struct linespec_sals lsal;
13031   const char *arg_start, *arg;
13032
13033   arg = arg_start = get_linespec_location (location)->spec_string;
13034   lsal.sals = decode_static_tracepoint_spec (&arg);
13035
13036   std::string str (arg_start, arg - arg_start);
13037   const char *ptr = str.c_str ();
13038   canonical->location
13039     = new_linespec_location (&ptr, symbol_name_match_type::FULL);
13040
13041   lsal.canonical
13042     = xstrdup (event_location_to_string (canonical->location.get ()));
13043   canonical->lsals.push_back (std::move (lsal));
13044 }
13045
13046 static void
13047 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13048                                       struct linespec_result *canonical,
13049                                       gdb::unique_xmalloc_ptr<char> cond_string,
13050                                       gdb::unique_xmalloc_ptr<char> extra_string,
13051                                       enum bptype type_wanted,
13052                                       enum bpdisp disposition,
13053                                       int thread,
13054                                       int task, int ignore_count,
13055                                       const struct breakpoint_ops *ops,
13056                                       int from_tty, int enabled,
13057                                       int internal, unsigned flags)
13058 {
13059   const linespec_sals &lsal = canonical->lsals[0];
13060
13061   /* If the user is creating a static tracepoint by marker id
13062      (strace -m MARKER_ID), then store the sals index, so that
13063      breakpoint_re_set can try to match up which of the newly
13064      found markers corresponds to this one, and, don't try to
13065      expand multiple locations for each sal, given than SALS
13066      already should contain all sals for MARKER_ID.  */
13067
13068   for (size_t i = 0; i < lsal.sals.size (); i++)
13069     {
13070       event_location_up location
13071         = copy_event_location (canonical->location.get ());
13072
13073       std::unique_ptr<tracepoint> tp (new tracepoint ());
13074       init_breakpoint_sal (tp.get (), gdbarch, lsal.sals[i],
13075                            std::move (location), NULL,
13076                            std::move (cond_string),
13077                            std::move (extra_string),
13078                            type_wanted, disposition,
13079                            thread, task, ignore_count, ops,
13080                            from_tty, enabled, internal, flags,
13081                            canonical->special_display);
13082       /* Given that its possible to have multiple markers with
13083          the same string id, if the user is creating a static
13084          tracepoint by marker id ("strace -m MARKER_ID"), then
13085          store the sals index, so that breakpoint_re_set can
13086          try to match up which of the newly found markers
13087          corresponds to this one  */
13088       tp->static_trace_marker_id_idx = i;
13089
13090       install_breakpoint (internal, std::move (tp), 0);
13091     }
13092 }
13093
13094 static std::vector<symtab_and_line>
13095 strace_marker_decode_location (struct breakpoint *b,
13096                                const struct event_location *location,
13097                                struct program_space *search_pspace)
13098 {
13099   struct tracepoint *tp = (struct tracepoint *) b;
13100   const char *s = get_linespec_location (location)->spec_string;
13101
13102   std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
13103   if (sals.size () > tp->static_trace_marker_id_idx)
13104     {
13105       sals[0] = sals[tp->static_trace_marker_id_idx];
13106       sals.resize (1);
13107       return sals;
13108     }
13109   else
13110     error (_("marker %s not found"), tp->static_trace_marker_id.c_str ());
13111 }
13112
13113 static struct breakpoint_ops strace_marker_breakpoint_ops;
13114
13115 static int
13116 strace_marker_p (struct breakpoint *b)
13117 {
13118   return b->ops == &strace_marker_breakpoint_ops;
13119 }
13120
13121 /* Delete a breakpoint and clean up all traces of it in the data
13122    structures.  */
13123
13124 void
13125 delete_breakpoint (struct breakpoint *bpt)
13126 {
13127   struct breakpoint *b;
13128
13129   gdb_assert (bpt != NULL);
13130
13131   /* Has this bp already been deleted?  This can happen because
13132      multiple lists can hold pointers to bp's.  bpstat lists are
13133      especial culprits.
13134
13135      One example of this happening is a watchpoint's scope bp.  When
13136      the scope bp triggers, we notice that the watchpoint is out of
13137      scope, and delete it.  We also delete its scope bp.  But the
13138      scope bp is marked "auto-deleting", and is already on a bpstat.
13139      That bpstat is then checked for auto-deleting bp's, which are
13140      deleted.
13141
13142      A real solution to this problem might involve reference counts in
13143      bp's, and/or giving them pointers back to their referencing
13144      bpstat's, and teaching delete_breakpoint to only free a bp's
13145      storage when no more references were extent.  A cheaper bandaid
13146      was chosen.  */
13147   if (bpt->type == bp_none)
13148     return;
13149
13150   /* At least avoid this stale reference until the reference counting
13151      of breakpoints gets resolved.  */
13152   if (bpt->related_breakpoint != bpt)
13153     {
13154       struct breakpoint *related;
13155       struct watchpoint *w;
13156
13157       if (bpt->type == bp_watchpoint_scope)
13158         w = (struct watchpoint *) bpt->related_breakpoint;
13159       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13160         w = (struct watchpoint *) bpt;
13161       else
13162         w = NULL;
13163       if (w != NULL)
13164         watchpoint_del_at_next_stop (w);
13165
13166       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13167       for (related = bpt; related->related_breakpoint != bpt;
13168            related = related->related_breakpoint);
13169       related->related_breakpoint = bpt->related_breakpoint;
13170       bpt->related_breakpoint = bpt;
13171     }
13172
13173   /* watch_command_1 creates a watchpoint but only sets its number if
13174      update_watchpoint succeeds in creating its bp_locations.  If there's
13175      a problem in that process, we'll be asked to delete the half-created
13176      watchpoint.  In that case, don't announce the deletion.  */
13177   if (bpt->number)
13178     gdb::observers::breakpoint_deleted.notify (bpt);
13179
13180   if (breakpoint_chain == bpt)
13181     breakpoint_chain = bpt->next;
13182
13183   ALL_BREAKPOINTS (b)
13184     if (b->next == bpt)
13185     {
13186       b->next = bpt->next;
13187       break;
13188     }
13189
13190   /* Be sure no bpstat's are pointing at the breakpoint after it's
13191      been freed.  */
13192   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13193      in all threads for now.  Note that we cannot just remove bpstats
13194      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13195      commands are associated with the bpstat; if we remove it here,
13196      then the later call to bpstat_do_actions (&stop_bpstat); in
13197      event-top.c won't do anything, and temporary breakpoints with
13198      commands won't work.  */
13199
13200   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13201
13202   /* Now that breakpoint is removed from breakpoint list, update the
13203      global location list.  This will remove locations that used to
13204      belong to this breakpoint.  Do this before freeing the breakpoint
13205      itself, since remove_breakpoint looks at location's owner.  It
13206      might be better design to have location completely
13207      self-contained, but it's not the case now.  */
13208   update_global_location_list (UGLL_DONT_INSERT);
13209
13210   /* On the chance that someone will soon try again to delete this
13211      same bp, we mark it as deleted before freeing its storage.  */
13212   bpt->type = bp_none;
13213   delete bpt;
13214 }
13215
13216 /* Iterator function to call a user-provided callback function once
13217    for each of B and its related breakpoints.  */
13218
13219 static void
13220 iterate_over_related_breakpoints (struct breakpoint *b,
13221                                   gdb::function_view<void (breakpoint *)> function)
13222 {
13223   struct breakpoint *related;
13224
13225   related = b;
13226   do
13227     {
13228       struct breakpoint *next;
13229
13230       /* FUNCTION may delete RELATED.  */
13231       next = related->related_breakpoint;
13232
13233       if (next == related)
13234         {
13235           /* RELATED is the last ring entry.  */
13236           function (related);
13237
13238           /* FUNCTION may have deleted it, so we'd never reach back to
13239              B.  There's nothing left to do anyway, so just break
13240              out.  */
13241           break;
13242         }
13243       else
13244         function (related);
13245
13246       related = next;
13247     }
13248   while (related != b);
13249 }
13250
13251 static void
13252 delete_command (const char *arg, int from_tty)
13253 {
13254   struct breakpoint *b, *b_tmp;
13255
13256   dont_repeat ();
13257
13258   if (arg == 0)
13259     {
13260       int breaks_to_delete = 0;
13261
13262       /* Delete all breakpoints if no argument.  Do not delete
13263          internal breakpoints, these have to be deleted with an
13264          explicit breakpoint number argument.  */
13265       ALL_BREAKPOINTS (b)
13266         if (user_breakpoint_p (b))
13267           {
13268             breaks_to_delete = 1;
13269             break;
13270           }
13271
13272       /* Ask user only if there are some breakpoints to delete.  */
13273       if (!from_tty
13274           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13275         {
13276           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13277             if (user_breakpoint_p (b))
13278               delete_breakpoint (b);
13279         }
13280     }
13281   else
13282     map_breakpoint_numbers
13283       (arg, [&] (breakpoint *br)
13284        {
13285          iterate_over_related_breakpoints (br, delete_breakpoint);
13286        });
13287 }
13288
13289 /* Return true if all locations of B bound to PSPACE are pending.  If
13290    PSPACE is NULL, all locations of all program spaces are
13291    considered.  */
13292
13293 static int
13294 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13295 {
13296   struct bp_location *loc;
13297
13298   for (loc = b->loc; loc != NULL; loc = loc->next)
13299     if ((pspace == NULL
13300          || loc->pspace == pspace)
13301         && !loc->shlib_disabled
13302         && !loc->pspace->executing_startup)
13303       return 0;
13304   return 1;
13305 }
13306
13307 /* Subroutine of update_breakpoint_locations to simplify it.
13308    Return non-zero if multiple fns in list LOC have the same name.
13309    Null names are ignored.  */
13310
13311 static int
13312 ambiguous_names_p (struct bp_location *loc)
13313 {
13314   struct bp_location *l;
13315   htab_t htab = htab_create_alloc (13, htab_hash_string, streq_hash, NULL,
13316                                    xcalloc, xfree);
13317
13318   for (l = loc; l != NULL; l = l->next)
13319     {
13320       const char **slot;
13321       const char *name = l->function_name;
13322
13323       /* Allow for some names to be NULL, ignore them.  */
13324       if (name == NULL)
13325         continue;
13326
13327       slot = (const char **) htab_find_slot (htab, (const void *) name,
13328                                              INSERT);
13329       /* NOTE: We can assume slot != NULL here because xcalloc never
13330          returns NULL.  */
13331       if (*slot != NULL)
13332         {
13333           htab_delete (htab);
13334           return 1;
13335         }
13336       *slot = name;
13337     }
13338
13339   htab_delete (htab);
13340   return 0;
13341 }
13342
13343 /* When symbols change, it probably means the sources changed as well,
13344    and it might mean the static tracepoint markers are no longer at
13345    the same address or line numbers they used to be at last we
13346    checked.  Losing your static tracepoints whenever you rebuild is
13347    undesirable.  This function tries to resync/rematch gdb static
13348    tracepoints with the markers on the target, for static tracepoints
13349    that have not been set by marker id.  Static tracepoint that have
13350    been set by marker id are reset by marker id in breakpoint_re_set.
13351    The heuristic is:
13352
13353    1) For a tracepoint set at a specific address, look for a marker at
13354    the old PC.  If one is found there, assume to be the same marker.
13355    If the name / string id of the marker found is different from the
13356    previous known name, assume that means the user renamed the marker
13357    in the sources, and output a warning.
13358
13359    2) For a tracepoint set at a given line number, look for a marker
13360    at the new address of the old line number.  If one is found there,
13361    assume to be the same marker.  If the name / string id of the
13362    marker found is different from the previous known name, assume that
13363    means the user renamed the marker in the sources, and output a
13364    warning.
13365
13366    3) If a marker is no longer found at the same address or line, it
13367    may mean the marker no longer exists.  But it may also just mean
13368    the code changed a bit.  Maybe the user added a few lines of code
13369    that made the marker move up or down (in line number terms).  Ask
13370    the target for info about the marker with the string id as we knew
13371    it.  If found, update line number and address in the matching
13372    static tracepoint.  This will get confused if there's more than one
13373    marker with the same ID (possible in UST, although unadvised
13374    precisely because it confuses tools).  */
13375
13376 static struct symtab_and_line
13377 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13378 {
13379   struct tracepoint *tp = (struct tracepoint *) b;
13380   struct static_tracepoint_marker marker;
13381   CORE_ADDR pc;
13382
13383   pc = sal.pc;
13384   if (sal.line)
13385     find_line_pc (sal.symtab, sal.line, &pc);
13386
13387   if (target_static_tracepoint_marker_at (pc, &marker))
13388     {
13389       if (tp->static_trace_marker_id != marker.str_id)
13390         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13391                  b->number, tp->static_trace_marker_id.c_str (),
13392                  marker.str_id.c_str ());
13393
13394       tp->static_trace_marker_id = std::move (marker.str_id);
13395
13396       return sal;
13397     }
13398
13399   /* Old marker wasn't found on target at lineno.  Try looking it up
13400      by string ID.  */
13401   if (!sal.explicit_pc
13402       && sal.line != 0
13403       && sal.symtab != NULL
13404       && !tp->static_trace_marker_id.empty ())
13405     {
13406       std::vector<static_tracepoint_marker> markers
13407         = target_static_tracepoint_markers_by_strid
13408             (tp->static_trace_marker_id.c_str ());
13409
13410       if (!markers.empty ())
13411         {
13412           struct symbol *sym;
13413           struct static_tracepoint_marker *tpmarker;
13414           struct ui_out *uiout = current_uiout;
13415           struct explicit_location explicit_loc;
13416
13417           tpmarker = &markers[0];
13418
13419           tp->static_trace_marker_id = std::move (tpmarker->str_id);
13420
13421           warning (_("marker for static tracepoint %d (%s) not "
13422                      "found at previous line number"),
13423                    b->number, tp->static_trace_marker_id.c_str ());
13424
13425           symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
13426           sym = find_pc_sect_function (tpmarker->address, NULL);
13427           uiout->text ("Now in ");
13428           if (sym)
13429             {
13430               uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
13431               uiout->text (" at ");
13432             }
13433           uiout->field_string ("file",
13434                                symtab_to_filename_for_display (sal2.symtab));
13435           uiout->text (":");
13436
13437           if (uiout->is_mi_like_p ())
13438             {
13439               const char *fullname = symtab_to_fullname (sal2.symtab);
13440
13441               uiout->field_string ("fullname", fullname);
13442             }
13443
13444           uiout->field_int ("line", sal2.line);
13445           uiout->text ("\n");
13446
13447           b->loc->line_number = sal2.line;
13448           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13449
13450           b->location.reset (NULL);
13451           initialize_explicit_location (&explicit_loc);
13452           explicit_loc.source_filename
13453             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
13454           explicit_loc.line_offset.offset = b->loc->line_number;
13455           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
13456           b->location = new_explicit_location (&explicit_loc);
13457
13458           /* Might be nice to check if function changed, and warn if
13459              so.  */
13460         }
13461     }
13462   return sal;
13463 }
13464
13465 /* Returns 1 iff locations A and B are sufficiently same that
13466    we don't need to report breakpoint as changed.  */
13467
13468 static int
13469 locations_are_equal (struct bp_location *a, struct bp_location *b)
13470 {
13471   while (a && b)
13472     {
13473       if (a->address != b->address)
13474         return 0;
13475
13476       if (a->shlib_disabled != b->shlib_disabled)
13477         return 0;
13478
13479       if (a->enabled != b->enabled)
13480         return 0;
13481
13482       a = a->next;
13483       b = b->next;
13484     }
13485
13486   if ((a == NULL) != (b == NULL))
13487     return 0;
13488
13489   return 1;
13490 }
13491
13492 /* Split all locations of B that are bound to PSPACE out of B's
13493    location list to a separate list and return that list's head.  If
13494    PSPACE is NULL, hoist out all locations of B.  */
13495
13496 static struct bp_location *
13497 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
13498 {
13499   struct bp_location head;
13500   struct bp_location *i = b->loc;
13501   struct bp_location **i_link = &b->loc;
13502   struct bp_location *hoisted = &head;
13503
13504   if (pspace == NULL)
13505     {
13506       i = b->loc;
13507       b->loc = NULL;
13508       return i;
13509     }
13510
13511   head.next = NULL;
13512
13513   while (i != NULL)
13514     {
13515       if (i->pspace == pspace)
13516         {
13517           *i_link = i->next;
13518           i->next = NULL;
13519           hoisted->next = i;
13520           hoisted = i;
13521         }
13522       else
13523         i_link = &i->next;
13524       i = *i_link;
13525     }
13526
13527   return head.next;
13528 }
13529
13530 /* Create new breakpoint locations for B (a hardware or software
13531    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
13532    zero, then B is a ranged breakpoint.  Only recreates locations for
13533    FILTER_PSPACE.  Locations of other program spaces are left
13534    untouched.  */
13535
13536 void
13537 update_breakpoint_locations (struct breakpoint *b,
13538                              struct program_space *filter_pspace,
13539                              gdb::array_view<const symtab_and_line> sals,
13540                              gdb::array_view<const symtab_and_line> sals_end)
13541 {
13542   struct bp_location *existing_locations;
13543
13544   if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
13545     {
13546       /* Ranged breakpoints have only one start location and one end
13547          location.  */
13548       b->enable_state = bp_disabled;
13549       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13550                            "multiple locations found\n"),
13551                          b->number);
13552       return;
13553     }
13554
13555   /* If there's no new locations, and all existing locations are
13556      pending, don't do anything.  This optimizes the common case where
13557      all locations are in the same shared library, that was unloaded.
13558      We'd like to retain the location, so that when the library is
13559      loaded again, we don't loose the enabled/disabled status of the
13560      individual locations.  */
13561   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
13562     return;
13563
13564   existing_locations = hoist_existing_locations (b, filter_pspace);
13565
13566   for (const auto &sal : sals)
13567     {
13568       struct bp_location *new_loc;
13569
13570       switch_to_program_space_and_thread (sal.pspace);
13571
13572       new_loc = add_location_to_breakpoint (b, &sal);
13573
13574       /* Reparse conditions, they might contain references to the
13575          old symtab.  */
13576       if (b->cond_string != NULL)
13577         {
13578           const char *s;
13579
13580           s = b->cond_string;
13581           TRY
13582             {
13583               new_loc->cond = parse_exp_1 (&s, sal.pc,
13584                                            block_for_pc (sal.pc),
13585                                            0);
13586             }
13587           CATCH (e, RETURN_MASK_ERROR)
13588             {
13589               warning (_("failed to reevaluate condition "
13590                          "for breakpoint %d: %s"), 
13591                        b->number, e.message);
13592               new_loc->enabled = 0;
13593             }
13594           END_CATCH
13595         }
13596
13597       if (!sals_end.empty ())
13598         {
13599           CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13600
13601           new_loc->length = end - sals[0].pc + 1;
13602         }
13603     }
13604
13605   /* If possible, carry over 'disable' status from existing
13606      breakpoints.  */
13607   {
13608     struct bp_location *e = existing_locations;
13609     /* If there are multiple breakpoints with the same function name,
13610        e.g. for inline functions, comparing function names won't work.
13611        Instead compare pc addresses; this is just a heuristic as things
13612        may have moved, but in practice it gives the correct answer
13613        often enough until a better solution is found.  */
13614     int have_ambiguous_names = ambiguous_names_p (b->loc);
13615
13616     for (; e; e = e->next)
13617       {
13618         if (!e->enabled && e->function_name)
13619           {
13620             struct bp_location *l = b->loc;
13621             if (have_ambiguous_names)
13622               {
13623                 for (; l; l = l->next)
13624                   if (breakpoint_locations_match (e, l))
13625                     {
13626                       l->enabled = 0;
13627                       break;
13628                     }
13629               }
13630             else
13631               {
13632                 for (; l; l = l->next)
13633                   if (l->function_name
13634                       && strcmp (e->function_name, l->function_name) == 0)
13635                     {
13636                       l->enabled = 0;
13637                       break;
13638                     }
13639               }
13640           }
13641       }
13642   }
13643
13644   if (!locations_are_equal (existing_locations, b->loc))
13645     gdb::observers::breakpoint_modified.notify (b);
13646 }
13647
13648 /* Find the SaL locations corresponding to the given LOCATION.
13649    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13650
13651 static std::vector<symtab_and_line>
13652 location_to_sals (struct breakpoint *b, struct event_location *location,
13653                   struct program_space *search_pspace, int *found)
13654 {
13655   struct gdb_exception exception = exception_none;
13656
13657   gdb_assert (b->ops != NULL);
13658
13659   std::vector<symtab_and_line> sals;
13660
13661   TRY
13662     {
13663       sals = b->ops->decode_location (b, location, search_pspace);
13664     }
13665   CATCH (e, RETURN_MASK_ERROR)
13666     {
13667       int not_found_and_ok = 0;
13668
13669       exception = e;
13670
13671       /* For pending breakpoints, it's expected that parsing will
13672          fail until the right shared library is loaded.  User has
13673          already told to create pending breakpoints and don't need
13674          extra messages.  If breakpoint is in bp_shlib_disabled
13675          state, then user already saw the message about that
13676          breakpoint being disabled, and don't want to see more
13677          errors.  */
13678       if (e.error == NOT_FOUND_ERROR
13679           && (b->condition_not_parsed
13680               || (b->loc != NULL
13681                   && search_pspace != NULL
13682                   && b->loc->pspace != search_pspace)
13683               || (b->loc && b->loc->shlib_disabled)
13684               || (b->loc && b->loc->pspace->executing_startup)
13685               || b->enable_state == bp_disabled))
13686         not_found_and_ok = 1;
13687
13688       if (!not_found_and_ok)
13689         {
13690           /* We surely don't want to warn about the same breakpoint
13691              10 times.  One solution, implemented here, is disable
13692              the breakpoint on error.  Another solution would be to
13693              have separate 'warning emitted' flag.  Since this
13694              happens only when a binary has changed, I don't know
13695              which approach is better.  */
13696           b->enable_state = bp_disabled;
13697           throw_exception (e);
13698         }
13699     }
13700   END_CATCH
13701
13702   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13703     {
13704       for (auto &sal : sals)
13705         resolve_sal_pc (&sal);
13706       if (b->condition_not_parsed && b->extra_string != NULL)
13707         {
13708           char *cond_string, *extra_string;
13709           int thread, task;
13710
13711           find_condition_and_thread (b->extra_string, sals[0].pc,
13712                                      &cond_string, &thread, &task,
13713                                      &extra_string);
13714           gdb_assert (b->cond_string == NULL);
13715           if (cond_string)
13716             b->cond_string = cond_string;
13717           b->thread = thread;
13718           b->task = task;
13719           if (extra_string)
13720             {
13721               xfree (b->extra_string);
13722               b->extra_string = extra_string;
13723             }
13724           b->condition_not_parsed = 0;
13725         }
13726
13727       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13728         sals[0] = update_static_tracepoint (b, sals[0]);
13729
13730       *found = 1;
13731     }
13732   else
13733     *found = 0;
13734
13735   return sals;
13736 }
13737
13738 /* The default re_set method, for typical hardware or software
13739    breakpoints.  Reevaluate the breakpoint and recreate its
13740    locations.  */
13741
13742 static void
13743 breakpoint_re_set_default (struct breakpoint *b)
13744 {
13745   struct program_space *filter_pspace = current_program_space;
13746   std::vector<symtab_and_line> expanded, expanded_end;
13747
13748   int found;
13749   std::vector<symtab_and_line> sals = location_to_sals (b, b->location.get (),
13750                                                         filter_pspace, &found);
13751   if (found)
13752     expanded = std::move (sals);
13753
13754   if (b->location_range_end != NULL)
13755     {
13756       std::vector<symtab_and_line> sals_end
13757         = location_to_sals (b, b->location_range_end.get (),
13758                             filter_pspace, &found);
13759       if (found)
13760         expanded_end = std::move (sals_end);
13761     }
13762
13763   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
13764 }
13765
13766 /* Default method for creating SALs from an address string.  It basically
13767    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13768
13769 static void
13770 create_sals_from_location_default (const struct event_location *location,
13771                                    struct linespec_result *canonical,
13772                                    enum bptype type_wanted)
13773 {
13774   parse_breakpoint_sals (location, canonical);
13775 }
13776
13777 /* Call create_breakpoints_sal for the given arguments.  This is the default
13778    function for the `create_breakpoints_sal' method of
13779    breakpoint_ops.  */
13780
13781 static void
13782 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13783                                 struct linespec_result *canonical,
13784                                 gdb::unique_xmalloc_ptr<char> cond_string,
13785                                 gdb::unique_xmalloc_ptr<char> extra_string,
13786                                 enum bptype type_wanted,
13787                                 enum bpdisp disposition,
13788                                 int thread,
13789                                 int task, int ignore_count,
13790                                 const struct breakpoint_ops *ops,
13791                                 int from_tty, int enabled,
13792                                 int internal, unsigned flags)
13793 {
13794   create_breakpoints_sal (gdbarch, canonical,
13795                           std::move (cond_string),
13796                           std::move (extra_string),
13797                           type_wanted, disposition,
13798                           thread, task, ignore_count, ops, from_tty,
13799                           enabled, internal, flags);
13800 }
13801
13802 /* Decode the line represented by S by calling decode_line_full.  This is the
13803    default function for the `decode_location' method of breakpoint_ops.  */
13804
13805 static std::vector<symtab_and_line>
13806 decode_location_default (struct breakpoint *b,
13807                          const struct event_location *location,
13808                          struct program_space *search_pspace)
13809 {
13810   struct linespec_result canonical;
13811
13812   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
13813                     (struct symtab *) NULL, 0,
13814                     &canonical, multiple_symbols_all,
13815                     b->filter);
13816
13817   /* We should get 0 or 1 resulting SALs.  */
13818   gdb_assert (canonical.lsals.size () < 2);
13819
13820   if (!canonical.lsals.empty ())
13821     {
13822       const linespec_sals &lsal = canonical.lsals[0];
13823       return std::move (lsal.sals);
13824     }
13825   return {};
13826 }
13827
13828 /* Reset a breakpoint.  */
13829
13830 static void
13831 breakpoint_re_set_one (breakpoint *b)
13832 {
13833   input_radix = b->input_radix;
13834   set_language (b->language);
13835
13836   b->ops->re_set (b);
13837 }
13838
13839 /* Re-set breakpoint locations for the current program space.
13840    Locations bound to other program spaces are left untouched.  */
13841
13842 void
13843 breakpoint_re_set (void)
13844 {
13845   struct breakpoint *b, *b_tmp;
13846
13847   {
13848     scoped_restore_current_language save_language;
13849     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
13850     scoped_restore_current_pspace_and_thread restore_pspace_thread;
13851
13852     /* breakpoint_re_set_one sets the current_language to the language
13853        of the breakpoint it is resetting (see prepare_re_set_context)
13854        before re-evaluating the breakpoint's location.  This change can
13855        unfortunately get undone by accident if the language_mode is set
13856        to auto, and we either switch frames, or more likely in this context,
13857        we select the current frame.
13858
13859        We prevent this by temporarily turning the language_mode to
13860        language_mode_manual.  We restore it once all breakpoints
13861        have been reset.  */
13862     scoped_restore save_language_mode = make_scoped_restore (&language_mode);
13863     language_mode = language_mode_manual;
13864
13865     /* Note: we must not try to insert locations until after all
13866        breakpoints have been re-set.  Otherwise, e.g., when re-setting
13867        breakpoint 1, we'd insert the locations of breakpoint 2, which
13868        hadn't been re-set yet, and thus may have stale locations.  */
13869
13870     ALL_BREAKPOINTS_SAFE (b, b_tmp)
13871       {
13872         TRY
13873           {
13874             breakpoint_re_set_one (b);
13875           }
13876         CATCH (ex, RETURN_MASK_ALL)
13877           {
13878             exception_fprintf (gdb_stderr, ex,
13879                                "Error in re-setting breakpoint %d: ",
13880                                b->number);
13881           }
13882         END_CATCH
13883       }
13884
13885     jit_breakpoint_re_set ();
13886   }
13887
13888   create_overlay_event_breakpoint ();
13889   create_longjmp_master_breakpoint ();
13890   create_std_terminate_master_breakpoint ();
13891   create_exception_master_breakpoint ();
13892
13893   /* Now we can insert.  */
13894   update_global_location_list (UGLL_MAY_INSERT);
13895 }
13896 \f
13897 /* Reset the thread number of this breakpoint:
13898
13899    - If the breakpoint is for all threads, leave it as-is.
13900    - Else, reset it to the current thread for inferior_ptid.  */
13901 void
13902 breakpoint_re_set_thread (struct breakpoint *b)
13903 {
13904   if (b->thread != -1)
13905     {
13906       b->thread = inferior_thread ()->global_num;
13907
13908       /* We're being called after following a fork.  The new fork is
13909          selected as current, and unless this was a vfork will have a
13910          different program space from the original thread.  Reset that
13911          as well.  */
13912       b->loc->pspace = current_program_space;
13913     }
13914 }
13915
13916 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13917    If from_tty is nonzero, it prints a message to that effect,
13918    which ends with a period (no newline).  */
13919
13920 void
13921 set_ignore_count (int bptnum, int count, int from_tty)
13922 {
13923   struct breakpoint *b;
13924
13925   if (count < 0)
13926     count = 0;
13927
13928   ALL_BREAKPOINTS (b)
13929     if (b->number == bptnum)
13930     {
13931       if (is_tracepoint (b))
13932         {
13933           if (from_tty && count != 0)
13934             printf_filtered (_("Ignore count ignored for tracepoint %d."),
13935                              bptnum);
13936           return;
13937         }
13938       
13939       b->ignore_count = count;
13940       if (from_tty)
13941         {
13942           if (count == 0)
13943             printf_filtered (_("Will stop next time "
13944                                "breakpoint %d is reached."),
13945                              bptnum);
13946           else if (count == 1)
13947             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
13948                              bptnum);
13949           else
13950             printf_filtered (_("Will ignore next %d "
13951                                "crossings of breakpoint %d."),
13952                              count, bptnum);
13953         }
13954       gdb::observers::breakpoint_modified.notify (b);
13955       return;
13956     }
13957
13958   error (_("No breakpoint number %d."), bptnum);
13959 }
13960
13961 /* Command to set ignore-count of breakpoint N to COUNT.  */
13962
13963 static void
13964 ignore_command (const char *args, int from_tty)
13965 {
13966   const char *p = args;
13967   int num;
13968
13969   if (p == 0)
13970     error_no_arg (_("a breakpoint number"));
13971
13972   num = get_number (&p);
13973   if (num == 0)
13974     error (_("bad breakpoint number: '%s'"), args);
13975   if (*p == 0)
13976     error (_("Second argument (specified ignore-count) is missing."));
13977
13978   set_ignore_count (num,
13979                     longest_to_int (value_as_long (parse_and_eval (p))),
13980                     from_tty);
13981   if (from_tty)
13982     printf_filtered ("\n");
13983 }
13984 \f
13985
13986 /* Call FUNCTION on each of the breakpoints with numbers in the range
13987    defined by BP_NUM_RANGE (an inclusive range).  */
13988
13989 static void
13990 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
13991                              gdb::function_view<void (breakpoint *)> function)
13992 {
13993   if (bp_num_range.first == 0)
13994     {
13995       warning (_("bad breakpoint number at or near '%d'"),
13996                bp_num_range.first);
13997     }
13998   else
13999     {
14000       struct breakpoint *b, *tmp;
14001
14002       for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
14003         {
14004           bool match = false;
14005
14006           ALL_BREAKPOINTS_SAFE (b, tmp)
14007             if (b->number == i)
14008               {
14009                 match = true;
14010                 function (b);
14011                 break;
14012               }
14013           if (!match)
14014             printf_unfiltered (_("No breakpoint number %d.\n"), i);
14015         }
14016     }
14017 }
14018
14019 /* Call FUNCTION on each of the breakpoints whose numbers are given in
14020    ARGS.  */
14021
14022 static void
14023 map_breakpoint_numbers (const char *args,
14024                         gdb::function_view<void (breakpoint *)> function)
14025 {
14026   if (args == NULL || *args == '\0')
14027     error_no_arg (_("one or more breakpoint numbers"));
14028
14029   number_or_range_parser parser (args);
14030
14031   while (!parser.finished ())
14032     {
14033       int num = parser.get_number ();
14034       map_breakpoint_number_range (std::make_pair (num, num), function);
14035     }
14036 }
14037
14038 /* Return the breakpoint location structure corresponding to the
14039    BP_NUM and LOC_NUM values.  */
14040
14041 static struct bp_location *
14042 find_location_by_number (int bp_num, int loc_num)
14043 {
14044   struct breakpoint *b;
14045
14046   ALL_BREAKPOINTS (b)
14047     if (b->number == bp_num)
14048       {
14049         break;
14050       }
14051
14052   if (!b || b->number != bp_num)
14053     error (_("Bad breakpoint number '%d'"), bp_num);
14054   
14055   if (loc_num == 0)
14056     error (_("Bad breakpoint location number '%d'"), loc_num);
14057
14058   int n = 0;
14059   for (bp_location *loc = b->loc; loc != NULL; loc = loc->next)
14060     if (++n == loc_num)
14061       return loc;
14062
14063   error (_("Bad breakpoint location number '%d'"), loc_num);
14064 }
14065
14066 /* Modes of operation for extract_bp_num.  */
14067 enum class extract_bp_kind
14068 {
14069   /* Extracting a breakpoint number.  */
14070   bp,
14071
14072   /* Extracting a location number.  */
14073   loc,
14074 };
14075
14076 /* Extract a breakpoint or location number (as determined by KIND)
14077    from the string starting at START.  TRAILER is a character which
14078    can be found after the number.  If you don't want a trailer, use
14079    '\0'.  If END_OUT is not NULL, it is set to point after the parsed
14080    string.  This always returns a positive integer.  */
14081
14082 static int
14083 extract_bp_num (extract_bp_kind kind, const char *start,
14084                 int trailer, const char **end_out = NULL)
14085 {
14086   const char *end = start;
14087   int num = get_number_trailer (&end, trailer);
14088   if (num < 0)
14089     error (kind == extract_bp_kind::bp
14090            ? _("Negative breakpoint number '%.*s'")
14091            : _("Negative breakpoint location number '%.*s'"),
14092            int (end - start), start);
14093   if (num == 0)
14094     error (kind == extract_bp_kind::bp
14095            ? _("Bad breakpoint number '%.*s'")
14096            : _("Bad breakpoint location number '%.*s'"),
14097            int (end - start), start);
14098
14099   if (end_out != NULL)
14100     *end_out = end;
14101   return num;
14102 }
14103
14104 /* Extract a breakpoint or location range (as determined by KIND) in
14105    the form NUM1-NUM2 stored at &ARG[arg_offset].  Returns a std::pair
14106    representing the (inclusive) range.  The returned pair's elements
14107    are always positive integers.  */
14108
14109 static std::pair<int, int>
14110 extract_bp_or_bp_range (extract_bp_kind kind,
14111                         const std::string &arg,
14112                         std::string::size_type arg_offset)
14113 {
14114   std::pair<int, int> range;
14115   const char *bp_loc = &arg[arg_offset];
14116   std::string::size_type dash = arg.find ('-', arg_offset);
14117   if (dash != std::string::npos)
14118     {
14119       /* bp_loc is a range (x-z).  */
14120       if (arg.length () == dash + 1)
14121         error (kind == extract_bp_kind::bp
14122                ? _("Bad breakpoint number at or near: '%s'")
14123                : _("Bad breakpoint location number at or near: '%s'"),
14124                bp_loc);
14125
14126       const char *end;
14127       const char *start_first = bp_loc;
14128       const char *start_second = &arg[dash + 1];
14129       range.first = extract_bp_num (kind, start_first, '-');
14130       range.second = extract_bp_num (kind, start_second, '\0', &end);
14131
14132       if (range.first > range.second)
14133         error (kind == extract_bp_kind::bp
14134                ? _("Inverted breakpoint range at '%.*s'")
14135                : _("Inverted breakpoint location range at '%.*s'"),
14136                int (end - start_first), start_first);
14137     }
14138   else
14139     {
14140       /* bp_loc is a single value.  */
14141       range.first = extract_bp_num (kind, bp_loc, '\0');
14142       range.second = range.first;
14143     }
14144   return range;
14145 }
14146
14147 /* Extract the breakpoint/location range specified by ARG.  Returns
14148    the breakpoint range in BP_NUM_RANGE, and the location range in
14149    BP_LOC_RANGE.
14150
14151    ARG may be in any of the following forms:
14152
14153    x     where 'x' is a breakpoint number.
14154    x-y   where 'x' and 'y' specify a breakpoint numbers range.
14155    x.y   where 'x' is a breakpoint number and 'y' a location number.
14156    x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
14157          location number range.
14158 */
14159
14160 static void
14161 extract_bp_number_and_location (const std::string &arg,
14162                                 std::pair<int, int> &bp_num_range,
14163                                 std::pair<int, int> &bp_loc_range)
14164 {
14165   std::string::size_type dot = arg.find ('.');
14166
14167   if (dot != std::string::npos)
14168     {
14169       /* Handle 'x.y' and 'x.y-z' cases.  */
14170
14171       if (arg.length () == dot + 1 || dot == 0)
14172         error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
14173
14174       bp_num_range.first
14175         = extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
14176       bp_num_range.second = bp_num_range.first;
14177
14178       bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
14179                                              arg, dot + 1);
14180     }
14181   else
14182     {
14183       /* Handle x and x-y cases.  */
14184
14185       bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
14186       bp_loc_range.first = 0;
14187       bp_loc_range.second = 0;
14188     }
14189 }
14190
14191 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM.  ENABLE
14192    specifies whether to enable or disable.  */
14193
14194 static void
14195 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
14196 {
14197   struct bp_location *loc = find_location_by_number (bp_num, loc_num);
14198   if (loc != NULL)
14199     {
14200       if (loc->enabled != enable)
14201         {
14202           loc->enabled = enable;
14203           mark_breakpoint_location_modified (loc);
14204         }
14205       if (target_supports_enable_disable_tracepoint ()
14206           && current_trace_status ()->running && loc->owner
14207           && is_tracepoint (loc->owner))
14208         target_disable_tracepoint (loc);
14209     }
14210   update_global_location_list (UGLL_DONT_INSERT);
14211
14212   gdb::observers::breakpoint_modified.notify (loc->owner);
14213 }
14214
14215 /* Enable or disable a range of breakpoint locations.  BP_NUM is the
14216    number of the breakpoint, and BP_LOC_RANGE specifies the
14217    (inclusive) range of location numbers of that breakpoint to
14218    enable/disable.  ENABLE specifies whether to enable or disable the
14219    location.  */
14220
14221 static void
14222 enable_disable_breakpoint_location_range (int bp_num,
14223                                           std::pair<int, int> &bp_loc_range,
14224                                           bool enable)
14225 {
14226   for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
14227     enable_disable_bp_num_loc (bp_num, i, enable);
14228 }
14229
14230 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14231    If from_tty is nonzero, it prints a message to that effect,
14232    which ends with a period (no newline).  */
14233
14234 void
14235 disable_breakpoint (struct breakpoint *bpt)
14236 {
14237   /* Never disable a watchpoint scope breakpoint; we want to
14238      hit them when we leave scope so we can delete both the
14239      watchpoint and its scope breakpoint at that time.  */
14240   if (bpt->type == bp_watchpoint_scope)
14241     return;
14242
14243   bpt->enable_state = bp_disabled;
14244
14245   /* Mark breakpoint locations modified.  */
14246   mark_breakpoint_modified (bpt);
14247
14248   if (target_supports_enable_disable_tracepoint ()
14249       && current_trace_status ()->running && is_tracepoint (bpt))
14250     {
14251       struct bp_location *location;
14252      
14253       for (location = bpt->loc; location; location = location->next)
14254         target_disable_tracepoint (location);
14255     }
14256
14257   update_global_location_list (UGLL_DONT_INSERT);
14258
14259   gdb::observers::breakpoint_modified.notify (bpt);
14260 }
14261
14262 /* Enable or disable the breakpoint(s) or breakpoint location(s)
14263    specified in ARGS.  ARGS may be in any of the formats handled by
14264    extract_bp_number_and_location.  ENABLE specifies whether to enable
14265    or disable the breakpoints/locations.  */
14266
14267 static void
14268 enable_disable_command (const char *args, int from_tty, bool enable)
14269 {
14270   if (args == 0)
14271     {
14272       struct breakpoint *bpt;
14273
14274       ALL_BREAKPOINTS (bpt)
14275         if (user_breakpoint_p (bpt))
14276           {
14277             if (enable)
14278               enable_breakpoint (bpt);
14279             else
14280               disable_breakpoint (bpt);
14281           }
14282     }
14283   else
14284     {
14285       std::string num = extract_arg (&args);
14286
14287       while (!num.empty ())
14288         {
14289           std::pair<int, int> bp_num_range, bp_loc_range;
14290
14291           extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
14292
14293           if (bp_loc_range.first == bp_loc_range.second
14294               && bp_loc_range.first == 0)
14295             {
14296               /* Handle breakpoint ids with formats 'x' or 'x-z'.  */
14297               map_breakpoint_number_range (bp_num_range,
14298                                            enable
14299                                            ? enable_breakpoint
14300                                            : disable_breakpoint);
14301             }
14302           else
14303             {
14304               /* Handle breakpoint ids with formats 'x.y' or
14305                  'x.y-z'.  */
14306               enable_disable_breakpoint_location_range
14307                 (bp_num_range.first, bp_loc_range, enable);
14308             }
14309           num = extract_arg (&args);
14310         }
14311     }
14312 }
14313
14314 /* The disable command disables the specified breakpoints/locations
14315    (or all defined breakpoints) so they're no longer effective in
14316    stopping the inferior.  ARGS may be in any of the forms defined in
14317    extract_bp_number_and_location.  */
14318
14319 static void
14320 disable_command (const char *args, int from_tty)
14321 {
14322   enable_disable_command (args, from_tty, false);
14323 }
14324
14325 static void
14326 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14327                         int count)
14328 {
14329   int target_resources_ok;
14330
14331   if (bpt->type == bp_hardware_breakpoint)
14332     {
14333       int i;
14334       i = hw_breakpoint_used_count ();
14335       target_resources_ok = 
14336         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14337                                             i + 1, 0);
14338       if (target_resources_ok == 0)
14339         error (_("No hardware breakpoint support in the target."));
14340       else if (target_resources_ok < 0)
14341         error (_("Hardware breakpoints used exceeds limit."));
14342     }
14343
14344   if (is_watchpoint (bpt))
14345     {
14346       /* Initialize it just to avoid a GCC false warning.  */
14347       enum enable_state orig_enable_state = bp_disabled;
14348
14349       TRY
14350         {
14351           struct watchpoint *w = (struct watchpoint *) bpt;
14352
14353           orig_enable_state = bpt->enable_state;
14354           bpt->enable_state = bp_enabled;
14355           update_watchpoint (w, 1 /* reparse */);
14356         }
14357       CATCH (e, RETURN_MASK_ALL)
14358         {
14359           bpt->enable_state = orig_enable_state;
14360           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14361                              bpt->number);
14362           return;
14363         }
14364       END_CATCH
14365     }
14366
14367   bpt->enable_state = bp_enabled;
14368
14369   /* Mark breakpoint locations modified.  */
14370   mark_breakpoint_modified (bpt);
14371
14372   if (target_supports_enable_disable_tracepoint ()
14373       && current_trace_status ()->running && is_tracepoint (bpt))
14374     {
14375       struct bp_location *location;
14376
14377       for (location = bpt->loc; location; location = location->next)
14378         target_enable_tracepoint (location);
14379     }
14380
14381   bpt->disposition = disposition;
14382   bpt->enable_count = count;
14383   update_global_location_list (UGLL_MAY_INSERT);
14384
14385   gdb::observers::breakpoint_modified.notify (bpt);
14386 }
14387
14388
14389 void
14390 enable_breakpoint (struct breakpoint *bpt)
14391 {
14392   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14393 }
14394
14395 /* The enable command enables the specified breakpoints/locations (or
14396    all defined breakpoints) so they once again become (or continue to
14397    be) effective in stopping the inferior.  ARGS may be in any of the
14398    forms defined in extract_bp_number_and_location.  */
14399
14400 static void
14401 enable_command (const char *args, int from_tty)
14402 {
14403   enable_disable_command (args, from_tty, true);
14404 }
14405
14406 static void
14407 enable_once_command (const char *args, int from_tty)
14408 {
14409   map_breakpoint_numbers
14410     (args, [&] (breakpoint *b)
14411      {
14412        iterate_over_related_breakpoints
14413          (b, [&] (breakpoint *bpt)
14414           {
14415             enable_breakpoint_disp (bpt, disp_disable, 1);
14416           });
14417      });
14418 }
14419
14420 static void
14421 enable_count_command (const char *args, int from_tty)
14422 {
14423   int count;
14424
14425   if (args == NULL)
14426     error_no_arg (_("hit count"));
14427
14428   count = get_number (&args);
14429
14430   map_breakpoint_numbers
14431     (args, [&] (breakpoint *b)
14432      {
14433        iterate_over_related_breakpoints
14434          (b, [&] (breakpoint *bpt)
14435           {
14436             enable_breakpoint_disp (bpt, disp_disable, count);
14437           });
14438      });
14439 }
14440
14441 static void
14442 enable_delete_command (const char *args, int from_tty)
14443 {
14444   map_breakpoint_numbers
14445     (args, [&] (breakpoint *b)
14446      {
14447        iterate_over_related_breakpoints
14448          (b, [&] (breakpoint *bpt)
14449           {
14450             enable_breakpoint_disp (bpt, disp_del, 1);
14451           });
14452      });
14453 }
14454 \f
14455 static void
14456 set_breakpoint_cmd (const char *args, int from_tty)
14457 {
14458 }
14459
14460 static void
14461 show_breakpoint_cmd (const char *args, int from_tty)
14462 {
14463 }
14464
14465 /* Invalidate last known value of any hardware watchpoint if
14466    the memory which that value represents has been written to by
14467    GDB itself.  */
14468
14469 static void
14470 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14471                                       CORE_ADDR addr, ssize_t len,
14472                                       const bfd_byte *data)
14473 {
14474   struct breakpoint *bp;
14475
14476   ALL_BREAKPOINTS (bp)
14477     if (bp->enable_state == bp_enabled
14478         && bp->type == bp_hardware_watchpoint)
14479       {
14480         struct watchpoint *wp = (struct watchpoint *) bp;
14481
14482         if (wp->val_valid && wp->val != nullptr)
14483           {
14484             struct bp_location *loc;
14485
14486             for (loc = bp->loc; loc != NULL; loc = loc->next)
14487               if (loc->loc_type == bp_loc_hardware_watchpoint
14488                   && loc->address + loc->length > addr
14489                   && addr + len > loc->address)
14490                 {
14491                   wp->val = NULL;
14492                   wp->val_valid = 0;
14493                 }
14494           }
14495       }
14496 }
14497
14498 /* Create and insert a breakpoint for software single step.  */
14499
14500 void
14501 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14502                                const address_space *aspace,
14503                                CORE_ADDR next_pc)
14504 {
14505   struct thread_info *tp = inferior_thread ();
14506   struct symtab_and_line sal;
14507   CORE_ADDR pc = next_pc;
14508
14509   if (tp->control.single_step_breakpoints == NULL)
14510     {
14511       tp->control.single_step_breakpoints
14512         = new_single_step_breakpoint (tp->global_num, gdbarch);
14513     }
14514
14515   sal = find_pc_line (pc, 0);
14516   sal.pc = pc;
14517   sal.section = find_pc_overlay (pc);
14518   sal.explicit_pc = 1;
14519   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14520
14521   update_global_location_list (UGLL_INSERT);
14522 }
14523
14524 /* Insert single step breakpoints according to the current state.  */
14525
14526 int
14527 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14528 {
14529   struct regcache *regcache = get_current_regcache ();
14530   std::vector<CORE_ADDR> next_pcs;
14531
14532   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14533
14534   if (!next_pcs.empty ())
14535     {
14536       struct frame_info *frame = get_current_frame ();
14537       const address_space *aspace = get_frame_address_space (frame);
14538
14539       for (CORE_ADDR pc : next_pcs)
14540         insert_single_step_breakpoint (gdbarch, aspace, pc);
14541
14542       return 1;
14543     }
14544   else
14545     return 0;
14546 }
14547
14548 /* See breakpoint.h.  */
14549
14550 int
14551 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14552                                        const address_space *aspace,
14553                                        CORE_ADDR pc)
14554 {
14555   struct bp_location *loc;
14556
14557   for (loc = bp->loc; loc != NULL; loc = loc->next)
14558     if (loc->inserted
14559         && breakpoint_location_address_match (loc, aspace, pc))
14560       return 1;
14561
14562   return 0;
14563 }
14564
14565 /* Check whether a software single-step breakpoint is inserted at
14566    PC.  */
14567
14568 int
14569 single_step_breakpoint_inserted_here_p (const address_space *aspace,
14570                                         CORE_ADDR pc)
14571 {
14572   struct breakpoint *bpt;
14573
14574   ALL_BREAKPOINTS (bpt)
14575     {
14576       if (bpt->type == bp_single_step
14577           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
14578         return 1;
14579     }
14580   return 0;
14581 }
14582
14583 /* Tracepoint-specific operations.  */
14584
14585 /* Set tracepoint count to NUM.  */
14586 static void
14587 set_tracepoint_count (int num)
14588 {
14589   tracepoint_count = num;
14590   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14591 }
14592
14593 static void
14594 trace_command (const char *arg, int from_tty)
14595 {
14596   struct breakpoint_ops *ops;
14597
14598   event_location_up location = string_to_event_location (&arg,
14599                                                          current_language);
14600   if (location != NULL
14601       && event_location_type (location.get ()) == PROBE_LOCATION)
14602     ops = &tracepoint_probe_breakpoint_ops;
14603   else
14604     ops = &tracepoint_breakpoint_ops;
14605
14606   create_breakpoint (get_current_arch (),
14607                      location.get (),
14608                      NULL, 0, arg, 1 /* parse arg */,
14609                      0 /* tempflag */,
14610                      bp_tracepoint /* type_wanted */,
14611                      0 /* Ignore count */,
14612                      pending_break_support,
14613                      ops,
14614                      from_tty,
14615                      1 /* enabled */,
14616                      0 /* internal */, 0);
14617 }
14618
14619 static void
14620 ftrace_command (const char *arg, int from_tty)
14621 {
14622   event_location_up location = string_to_event_location (&arg,
14623                                                          current_language);
14624   create_breakpoint (get_current_arch (),
14625                      location.get (),
14626                      NULL, 0, arg, 1 /* parse arg */,
14627                      0 /* tempflag */,
14628                      bp_fast_tracepoint /* type_wanted */,
14629                      0 /* Ignore count */,
14630                      pending_break_support,
14631                      &tracepoint_breakpoint_ops,
14632                      from_tty,
14633                      1 /* enabled */,
14634                      0 /* internal */, 0);
14635 }
14636
14637 /* strace command implementation.  Creates a static tracepoint.  */
14638
14639 static void
14640 strace_command (const char *arg, int from_tty)
14641 {
14642   struct breakpoint_ops *ops;
14643   event_location_up location;
14644
14645   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14646      or with a normal static tracepoint.  */
14647   if (arg && startswith (arg, "-m") && isspace (arg[2]))
14648     {
14649       ops = &strace_marker_breakpoint_ops;
14650       location = new_linespec_location (&arg, symbol_name_match_type::FULL);
14651     }
14652   else
14653     {
14654       ops = &tracepoint_breakpoint_ops;
14655       location = string_to_event_location (&arg, current_language);
14656     }
14657
14658   create_breakpoint (get_current_arch (),
14659                      location.get (),
14660                      NULL, 0, arg, 1 /* parse arg */,
14661                      0 /* tempflag */,
14662                      bp_static_tracepoint /* type_wanted */,
14663                      0 /* Ignore count */,
14664                      pending_break_support,
14665                      ops,
14666                      from_tty,
14667                      1 /* enabled */,
14668                      0 /* internal */, 0);
14669 }
14670
14671 /* Set up a fake reader function that gets command lines from a linked
14672    list that was acquired during tracepoint uploading.  */
14673
14674 static struct uploaded_tp *this_utp;
14675 static int next_cmd;
14676
14677 static char *
14678 read_uploaded_action (void)
14679 {
14680   char *rslt = nullptr;
14681
14682   if (next_cmd < this_utp->cmd_strings.size ())
14683     {
14684       rslt = this_utp->cmd_strings[next_cmd];
14685       next_cmd++;
14686     }
14687
14688   return rslt;
14689 }
14690
14691 /* Given information about a tracepoint as recorded on a target (which
14692    can be either a live system or a trace file), attempt to create an
14693    equivalent GDB tracepoint.  This is not a reliable process, since
14694    the target does not necessarily have all the information used when
14695    the tracepoint was originally defined.  */
14696   
14697 struct tracepoint *
14698 create_tracepoint_from_upload (struct uploaded_tp *utp)
14699 {
14700   const char *addr_str;
14701   char small_buf[100];
14702   struct tracepoint *tp;
14703
14704   if (utp->at_string)
14705     addr_str = utp->at_string;
14706   else
14707     {
14708       /* In the absence of a source location, fall back to raw
14709          address.  Since there is no way to confirm that the address
14710          means the same thing as when the trace was started, warn the
14711          user.  */
14712       warning (_("Uploaded tracepoint %d has no "
14713                  "source location, using raw address"),
14714                utp->number);
14715       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14716       addr_str = small_buf;
14717     }
14718
14719   /* There's not much we can do with a sequence of bytecodes.  */
14720   if (utp->cond && !utp->cond_string)
14721     warning (_("Uploaded tracepoint %d condition "
14722                "has no source form, ignoring it"),
14723              utp->number);
14724
14725   event_location_up location = string_to_event_location (&addr_str,
14726                                                          current_language);
14727   if (!create_breakpoint (get_current_arch (),
14728                           location.get (),
14729                           utp->cond_string, -1, addr_str,
14730                           0 /* parse cond/thread */,
14731                           0 /* tempflag */,
14732                           utp->type /* type_wanted */,
14733                           0 /* Ignore count */,
14734                           pending_break_support,
14735                           &tracepoint_breakpoint_ops,
14736                           0 /* from_tty */,
14737                           utp->enabled /* enabled */,
14738                           0 /* internal */,
14739                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14740     return NULL;
14741
14742   /* Get the tracepoint we just created.  */
14743   tp = get_tracepoint (tracepoint_count);
14744   gdb_assert (tp != NULL);
14745
14746   if (utp->pass > 0)
14747     {
14748       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14749                  tp->number);
14750
14751       trace_pass_command (small_buf, 0);
14752     }
14753
14754   /* If we have uploaded versions of the original commands, set up a
14755      special-purpose "reader" function and call the usual command line
14756      reader, then pass the result to the breakpoint command-setting
14757      function.  */
14758   if (!utp->cmd_strings.empty ())
14759     {
14760       counted_command_line cmd_list;
14761
14762       this_utp = utp;
14763       next_cmd = 0;
14764
14765       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL);
14766
14767       breakpoint_set_commands (tp, std::move (cmd_list));
14768     }
14769   else if (!utp->actions.empty ()
14770            || !utp->step_actions.empty ())
14771     warning (_("Uploaded tracepoint %d actions "
14772                "have no source form, ignoring them"),
14773              utp->number);
14774
14775   /* Copy any status information that might be available.  */
14776   tp->hit_count = utp->hit_count;
14777   tp->traceframe_usage = utp->traceframe_usage;
14778
14779   return tp;
14780 }
14781   
14782 /* Print information on tracepoint number TPNUM_EXP, or all if
14783    omitted.  */
14784
14785 static void
14786 info_tracepoints_command (const char *args, int from_tty)
14787 {
14788   struct ui_out *uiout = current_uiout;
14789   int num_printed;
14790
14791   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14792
14793   if (num_printed == 0)
14794     {
14795       if (args == NULL || *args == '\0')
14796         uiout->message ("No tracepoints.\n");
14797       else
14798         uiout->message ("No tracepoint matching '%s'.\n", args);
14799     }
14800
14801   default_collect_info ();
14802 }
14803
14804 /* The 'enable trace' command enables tracepoints.
14805    Not supported by all targets.  */
14806 static void
14807 enable_trace_command (const char *args, int from_tty)
14808 {
14809   enable_command (args, from_tty);
14810 }
14811
14812 /* The 'disable trace' command disables tracepoints.
14813    Not supported by all targets.  */
14814 static void
14815 disable_trace_command (const char *args, int from_tty)
14816 {
14817   disable_command (args, from_tty);
14818 }
14819
14820 /* Remove a tracepoint (or all if no argument).  */
14821 static void
14822 delete_trace_command (const char *arg, int from_tty)
14823 {
14824   struct breakpoint *b, *b_tmp;
14825
14826   dont_repeat ();
14827
14828   if (arg == 0)
14829     {
14830       int breaks_to_delete = 0;
14831
14832       /* Delete all breakpoints if no argument.
14833          Do not delete internal or call-dummy breakpoints, these
14834          have to be deleted with an explicit breakpoint number 
14835          argument.  */
14836       ALL_TRACEPOINTS (b)
14837         if (is_tracepoint (b) && user_breakpoint_p (b))
14838           {
14839             breaks_to_delete = 1;
14840             break;
14841           }
14842
14843       /* Ask user only if there are some breakpoints to delete.  */
14844       if (!from_tty
14845           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14846         {
14847           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14848             if (is_tracepoint (b) && user_breakpoint_p (b))
14849               delete_breakpoint (b);
14850         }
14851     }
14852   else
14853     map_breakpoint_numbers
14854       (arg, [&] (breakpoint *br)
14855        {
14856          iterate_over_related_breakpoints (br, delete_breakpoint);
14857        });
14858 }
14859
14860 /* Helper function for trace_pass_command.  */
14861
14862 static void
14863 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14864 {
14865   tp->pass_count = count;
14866   gdb::observers::breakpoint_modified.notify (tp);
14867   if (from_tty)
14868     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
14869                      tp->number, count);
14870 }
14871
14872 /* Set passcount for tracepoint.
14873
14874    First command argument is passcount, second is tracepoint number.
14875    If tracepoint number omitted, apply to most recently defined.
14876    Also accepts special argument "all".  */
14877
14878 static void
14879 trace_pass_command (const char *args, int from_tty)
14880 {
14881   struct tracepoint *t1;
14882   ULONGEST count;
14883
14884   if (args == 0 || *args == 0)
14885     error (_("passcount command requires an "
14886              "argument (count + optional TP num)"));
14887
14888   count = strtoulst (args, &args, 10);  /* Count comes first, then TP num.  */
14889
14890   args = skip_spaces (args);
14891   if (*args && strncasecmp (args, "all", 3) == 0)
14892     {
14893       struct breakpoint *b;
14894
14895       args += 3;                        /* Skip special argument "all".  */
14896       if (*args)
14897         error (_("Junk at end of arguments."));
14898
14899       ALL_TRACEPOINTS (b)
14900       {
14901         t1 = (struct tracepoint *) b;
14902         trace_pass_set_count (t1, count, from_tty);
14903       }
14904     }
14905   else if (*args == '\0')
14906     {
14907       t1 = get_tracepoint_by_number (&args, NULL);
14908       if (t1)
14909         trace_pass_set_count (t1, count, from_tty);
14910     }
14911   else
14912     {
14913       number_or_range_parser parser (args);
14914       while (!parser.finished ())
14915         {
14916           t1 = get_tracepoint_by_number (&args, &parser);
14917           if (t1)
14918             trace_pass_set_count (t1, count, from_tty);
14919         }
14920     }
14921 }
14922
14923 struct tracepoint *
14924 get_tracepoint (int num)
14925 {
14926   struct breakpoint *t;
14927
14928   ALL_TRACEPOINTS (t)
14929     if (t->number == num)
14930       return (struct tracepoint *) t;
14931
14932   return NULL;
14933 }
14934
14935 /* Find the tracepoint with the given target-side number (which may be
14936    different from the tracepoint number after disconnecting and
14937    reconnecting).  */
14938
14939 struct tracepoint *
14940 get_tracepoint_by_number_on_target (int num)
14941 {
14942   struct breakpoint *b;
14943
14944   ALL_TRACEPOINTS (b)
14945     {
14946       struct tracepoint *t = (struct tracepoint *) b;
14947
14948       if (t->number_on_target == num)
14949         return t;
14950     }
14951
14952   return NULL;
14953 }
14954
14955 /* Utility: parse a tracepoint number and look it up in the list.
14956    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14957    If the argument is missing, the most recent tracepoint
14958    (tracepoint_count) is returned.  */
14959
14960 struct tracepoint *
14961 get_tracepoint_by_number (const char **arg,
14962                           number_or_range_parser *parser)
14963 {
14964   struct breakpoint *t;
14965   int tpnum;
14966   const char *instring = arg == NULL ? NULL : *arg;
14967
14968   if (parser != NULL)
14969     {
14970       gdb_assert (!parser->finished ());
14971       tpnum = parser->get_number ();
14972     }
14973   else if (arg == NULL || *arg == NULL || ! **arg)
14974     tpnum = tracepoint_count;
14975   else
14976     tpnum = get_number (arg);
14977
14978   if (tpnum <= 0)
14979     {
14980       if (instring && *instring)
14981         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
14982                          instring);
14983       else
14984         printf_filtered (_("No previous tracepoint\n"));
14985       return NULL;
14986     }
14987
14988   ALL_TRACEPOINTS (t)
14989     if (t->number == tpnum)
14990     {
14991       return (struct tracepoint *) t;
14992     }
14993
14994   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
14995   return NULL;
14996 }
14997
14998 void
14999 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15000 {
15001   if (b->thread != -1)
15002     fprintf_unfiltered (fp, " thread %d", b->thread);
15003
15004   if (b->task != 0)
15005     fprintf_unfiltered (fp, " task %d", b->task);
15006
15007   fprintf_unfiltered (fp, "\n");
15008 }
15009
15010 /* Save information on user settable breakpoints (watchpoints, etc) to
15011    a new script file named FILENAME.  If FILTER is non-NULL, call it
15012    on each breakpoint and only include the ones for which it returns
15013    non-zero.  */
15014
15015 static void
15016 save_breakpoints (const char *filename, int from_tty,
15017                   int (*filter) (const struct breakpoint *))
15018 {
15019   struct breakpoint *tp;
15020   int any = 0;
15021   int extra_trace_bits = 0;
15022
15023   if (filename == 0 || *filename == 0)
15024     error (_("Argument required (file name in which to save)"));
15025
15026   /* See if we have anything to save.  */
15027   ALL_BREAKPOINTS (tp)
15028   {
15029     /* Skip internal and momentary breakpoints.  */
15030     if (!user_breakpoint_p (tp))
15031       continue;
15032
15033     /* If we have a filter, only save the breakpoints it accepts.  */
15034     if (filter && !filter (tp))
15035       continue;
15036
15037     any = 1;
15038
15039     if (is_tracepoint (tp))
15040       {
15041         extra_trace_bits = 1;
15042
15043         /* We can stop searching.  */
15044         break;
15045       }
15046   }
15047
15048   if (!any)
15049     {
15050       warning (_("Nothing to save."));
15051       return;
15052     }
15053
15054   gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
15055
15056   stdio_file fp;
15057
15058   if (!fp.open (expanded_filename.get (), "w"))
15059     error (_("Unable to open file '%s' for saving (%s)"),
15060            expanded_filename.get (), safe_strerror (errno));
15061
15062   if (extra_trace_bits)
15063     save_trace_state_variables (&fp);
15064
15065   ALL_BREAKPOINTS (tp)
15066   {
15067     /* Skip internal and momentary breakpoints.  */
15068     if (!user_breakpoint_p (tp))
15069       continue;
15070
15071     /* If we have a filter, only save the breakpoints it accepts.  */
15072     if (filter && !filter (tp))
15073       continue;
15074
15075     tp->ops->print_recreate (tp, &fp);
15076
15077     /* Note, we can't rely on tp->number for anything, as we can't
15078        assume the recreated breakpoint numbers will match.  Use $bpnum
15079        instead.  */
15080
15081     if (tp->cond_string)
15082       fp.printf ("  condition $bpnum %s\n", tp->cond_string);
15083
15084     if (tp->ignore_count)
15085       fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15086
15087     if (tp->type != bp_dprintf && tp->commands)
15088       {
15089         fp.puts ("  commands\n");
15090         
15091         current_uiout->redirect (&fp);
15092         TRY
15093           {
15094             print_command_lines (current_uiout, tp->commands.get (), 2);
15095           }
15096         CATCH (ex, RETURN_MASK_ALL)
15097           {
15098           current_uiout->redirect (NULL);
15099             throw_exception (ex);
15100           }
15101         END_CATCH
15102
15103         current_uiout->redirect (NULL);
15104         fp.puts ("  end\n");
15105       }
15106
15107     if (tp->enable_state == bp_disabled)
15108       fp.puts ("disable $bpnum\n");
15109
15110     /* If this is a multi-location breakpoint, check if the locations
15111        should be individually disabled.  Watchpoint locations are
15112        special, and not user visible.  */
15113     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15114       {
15115         struct bp_location *loc;
15116         int n = 1;
15117
15118         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15119           if (!loc->enabled)
15120             fp.printf ("disable $bpnum.%d\n", n);
15121       }
15122   }
15123
15124   if (extra_trace_bits && *default_collect)
15125     fp.printf ("set default-collect %s\n", default_collect);
15126
15127   if (from_tty)
15128     printf_filtered (_("Saved to file '%s'.\n"), expanded_filename.get ());
15129 }
15130
15131 /* The `save breakpoints' command.  */
15132
15133 static void
15134 save_breakpoints_command (const char *args, int from_tty)
15135 {
15136   save_breakpoints (args, from_tty, NULL);
15137 }
15138
15139 /* The `save tracepoints' command.  */
15140
15141 static void
15142 save_tracepoints_command (const char *args, int from_tty)
15143 {
15144   save_breakpoints (args, from_tty, is_tracepoint);
15145 }
15146
15147 /* Create a vector of all tracepoints.  */
15148
15149 std::vector<breakpoint *>
15150 all_tracepoints (void)
15151 {
15152   std::vector<breakpoint *> tp_vec;
15153   struct breakpoint *tp;
15154
15155   ALL_TRACEPOINTS (tp)
15156   {
15157     tp_vec.push_back (tp);
15158   }
15159
15160   return tp_vec;
15161 }
15162
15163 \f
15164 /* This help string is used to consolidate all the help string for specifying
15165    locations used by several commands.  */
15166
15167 #define LOCATION_HELP_STRING \
15168 "Linespecs are colon-separated lists of location parameters, such as\n\
15169 source filename, function name, label name, and line number.\n\
15170 Example: To specify the start of a label named \"the_top\" in the\n\
15171 function \"fact\" in the file \"factorial.c\", use\n\
15172 \"factorial.c:fact:the_top\".\n\
15173 \n\
15174 Address locations begin with \"*\" and specify an exact address in the\n\
15175 program.  Example: To specify the fourth byte past the start function\n\
15176 \"main\", use \"*main + 4\".\n\
15177 \n\
15178 Explicit locations are similar to linespecs but use an option/argument\n\
15179 syntax to specify location parameters.\n\
15180 Example: To specify the start of the label named \"the_top\" in the\n\
15181 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15182 -function fact -label the_top\".\n\
15183 \n\
15184 By default, a specified function is matched against the program's\n\
15185 functions in all scopes.  For C++, this means in all namespaces and\n\
15186 classes.  For Ada, this means in all packages.  E.g., in C++,\n\
15187 \"func()\" matches \"A::func()\", \"A::B::func()\", etc.  The\n\
15188 \"-qualified\" flag overrides this behavior, making GDB interpret the\n\
15189 specified name as a complete fully-qualified name instead.\n"
15190
15191 /* This help string is used for the break, hbreak, tbreak and thbreak
15192    commands.  It is defined as a macro to prevent duplication.
15193    COMMAND should be a string constant containing the name of the
15194    command.  */
15195
15196 #define BREAK_ARGS_HELP(command) \
15197 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15198 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15199 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15200 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15201 `-probe-dtrace' (for a DTrace probe).\n\
15202 LOCATION may be a linespec, address, or explicit location as described\n\
15203 below.\n\
15204 \n\
15205 With no LOCATION, uses current execution address of the selected\n\
15206 stack frame.  This is useful for breaking on return to a stack frame.\n\
15207 \n\
15208 THREADNUM is the number from \"info threads\".\n\
15209 CONDITION is a boolean expression.\n\
15210 \n" LOCATION_HELP_STRING "\n\
15211 Multiple breakpoints at one place are permitted, and useful if their\n\
15212 conditions are different.\n\
15213 \n\
15214 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15215
15216 /* List of subcommands for "catch".  */
15217 static struct cmd_list_element *catch_cmdlist;
15218
15219 /* List of subcommands for "tcatch".  */
15220 static struct cmd_list_element *tcatch_cmdlist;
15221
15222 void
15223 add_catch_command (const char *name, const char *docstring,
15224                    cmd_const_sfunc_ftype *sfunc,
15225                    completer_ftype *completer,
15226                    void *user_data_catch,
15227                    void *user_data_tcatch)
15228 {
15229   struct cmd_list_element *command;
15230
15231   command = add_cmd (name, class_breakpoint, docstring,
15232                      &catch_cmdlist);
15233   set_cmd_sfunc (command, sfunc);
15234   set_cmd_context (command, user_data_catch);
15235   set_cmd_completer (command, completer);
15236
15237   command = add_cmd (name, class_breakpoint, docstring,
15238                      &tcatch_cmdlist);
15239   set_cmd_sfunc (command, sfunc);
15240   set_cmd_context (command, user_data_tcatch);
15241   set_cmd_completer (command, completer);
15242 }
15243
15244 static void
15245 save_command (const char *arg, int from_tty)
15246 {
15247   printf_unfiltered (_("\"save\" must be followed by "
15248                        "the name of a save subcommand.\n"));
15249   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15250 }
15251
15252 struct breakpoint *
15253 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15254                           void *data)
15255 {
15256   struct breakpoint *b, *b_tmp;
15257
15258   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15259     {
15260       if ((*callback) (b, data))
15261         return b;
15262     }
15263
15264   return NULL;
15265 }
15266
15267 /* Zero if any of the breakpoint's locations could be a location where
15268    functions have been inlined, nonzero otherwise.  */
15269
15270 static int
15271 is_non_inline_function (struct breakpoint *b)
15272 {
15273   /* The shared library event breakpoint is set on the address of a
15274      non-inline function.  */
15275   if (b->type == bp_shlib_event)
15276     return 1;
15277
15278   return 0;
15279 }
15280
15281 /* Nonzero if the specified PC cannot be a location where functions
15282    have been inlined.  */
15283
15284 int
15285 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
15286                            const struct target_waitstatus *ws)
15287 {
15288   struct breakpoint *b;
15289   struct bp_location *bl;
15290
15291   ALL_BREAKPOINTS (b)
15292     {
15293       if (!is_non_inline_function (b))
15294         continue;
15295
15296       for (bl = b->loc; bl != NULL; bl = bl->next)
15297         {
15298           if (!bl->shlib_disabled
15299               && bpstat_check_location (bl, aspace, pc, ws))
15300             return 1;
15301         }
15302     }
15303
15304   return 0;
15305 }
15306
15307 /* Remove any references to OBJFILE which is going to be freed.  */
15308
15309 void
15310 breakpoint_free_objfile (struct objfile *objfile)
15311 {
15312   struct bp_location **locp, *loc;
15313
15314   ALL_BP_LOCATIONS (loc, locp)
15315     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15316       loc->symtab = NULL;
15317 }
15318
15319 void
15320 initialize_breakpoint_ops (void)
15321 {
15322   static int initialized = 0;
15323
15324   struct breakpoint_ops *ops;
15325
15326   if (initialized)
15327     return;
15328   initialized = 1;
15329
15330   /* The breakpoint_ops structure to be inherit by all kinds of
15331      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15332      internal and momentary breakpoints, etc.).  */
15333   ops = &bkpt_base_breakpoint_ops;
15334   *ops = base_breakpoint_ops;
15335   ops->re_set = bkpt_re_set;
15336   ops->insert_location = bkpt_insert_location;
15337   ops->remove_location = bkpt_remove_location;
15338   ops->breakpoint_hit = bkpt_breakpoint_hit;
15339   ops->create_sals_from_location = bkpt_create_sals_from_location;
15340   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15341   ops->decode_location = bkpt_decode_location;
15342
15343   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15344   ops = &bkpt_breakpoint_ops;
15345   *ops = bkpt_base_breakpoint_ops;
15346   ops->re_set = bkpt_re_set;
15347   ops->resources_needed = bkpt_resources_needed;
15348   ops->print_it = bkpt_print_it;
15349   ops->print_mention = bkpt_print_mention;
15350   ops->print_recreate = bkpt_print_recreate;
15351
15352   /* Ranged breakpoints.  */
15353   ops = &ranged_breakpoint_ops;
15354   *ops = bkpt_breakpoint_ops;
15355   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15356   ops->resources_needed = resources_needed_ranged_breakpoint;
15357   ops->print_it = print_it_ranged_breakpoint;
15358   ops->print_one = print_one_ranged_breakpoint;
15359   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15360   ops->print_mention = print_mention_ranged_breakpoint;
15361   ops->print_recreate = print_recreate_ranged_breakpoint;
15362
15363   /* Internal breakpoints.  */
15364   ops = &internal_breakpoint_ops;
15365   *ops = bkpt_base_breakpoint_ops;
15366   ops->re_set = internal_bkpt_re_set;
15367   ops->check_status = internal_bkpt_check_status;
15368   ops->print_it = internal_bkpt_print_it;
15369   ops->print_mention = internal_bkpt_print_mention;
15370
15371   /* Momentary breakpoints.  */
15372   ops = &momentary_breakpoint_ops;
15373   *ops = bkpt_base_breakpoint_ops;
15374   ops->re_set = momentary_bkpt_re_set;
15375   ops->check_status = momentary_bkpt_check_status;
15376   ops->print_it = momentary_bkpt_print_it;
15377   ops->print_mention = momentary_bkpt_print_mention;
15378
15379   /* Probe breakpoints.  */
15380   ops = &bkpt_probe_breakpoint_ops;
15381   *ops = bkpt_breakpoint_ops;
15382   ops->insert_location = bkpt_probe_insert_location;
15383   ops->remove_location = bkpt_probe_remove_location;
15384   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15385   ops->decode_location = bkpt_probe_decode_location;
15386
15387   /* Watchpoints.  */
15388   ops = &watchpoint_breakpoint_ops;
15389   *ops = base_breakpoint_ops;
15390   ops->re_set = re_set_watchpoint;
15391   ops->insert_location = insert_watchpoint;
15392   ops->remove_location = remove_watchpoint;
15393   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15394   ops->check_status = check_status_watchpoint;
15395   ops->resources_needed = resources_needed_watchpoint;
15396   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15397   ops->print_it = print_it_watchpoint;
15398   ops->print_mention = print_mention_watchpoint;
15399   ops->print_recreate = print_recreate_watchpoint;
15400   ops->explains_signal = explains_signal_watchpoint;
15401
15402   /* Masked watchpoints.  */
15403   ops = &masked_watchpoint_breakpoint_ops;
15404   *ops = watchpoint_breakpoint_ops;
15405   ops->insert_location = insert_masked_watchpoint;
15406   ops->remove_location = remove_masked_watchpoint;
15407   ops->resources_needed = resources_needed_masked_watchpoint;
15408   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15409   ops->print_it = print_it_masked_watchpoint;
15410   ops->print_one_detail = print_one_detail_masked_watchpoint;
15411   ops->print_mention = print_mention_masked_watchpoint;
15412   ops->print_recreate = print_recreate_masked_watchpoint;
15413
15414   /* Tracepoints.  */
15415   ops = &tracepoint_breakpoint_ops;
15416   *ops = base_breakpoint_ops;
15417   ops->re_set = tracepoint_re_set;
15418   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15419   ops->print_one_detail = tracepoint_print_one_detail;
15420   ops->print_mention = tracepoint_print_mention;
15421   ops->print_recreate = tracepoint_print_recreate;
15422   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15423   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15424   ops->decode_location = tracepoint_decode_location;
15425
15426   /* Probe tracepoints.  */
15427   ops = &tracepoint_probe_breakpoint_ops;
15428   *ops = tracepoint_breakpoint_ops;
15429   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15430   ops->decode_location = tracepoint_probe_decode_location;
15431
15432   /* Static tracepoints with marker (`-m').  */
15433   ops = &strace_marker_breakpoint_ops;
15434   *ops = tracepoint_breakpoint_ops;
15435   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15436   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15437   ops->decode_location = strace_marker_decode_location;
15438
15439   /* Fork catchpoints.  */
15440   ops = &catch_fork_breakpoint_ops;
15441   *ops = base_breakpoint_ops;
15442   ops->insert_location = insert_catch_fork;
15443   ops->remove_location = remove_catch_fork;
15444   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15445   ops->print_it = print_it_catch_fork;
15446   ops->print_one = print_one_catch_fork;
15447   ops->print_mention = print_mention_catch_fork;
15448   ops->print_recreate = print_recreate_catch_fork;
15449
15450   /* Vfork catchpoints.  */
15451   ops = &catch_vfork_breakpoint_ops;
15452   *ops = base_breakpoint_ops;
15453   ops->insert_location = insert_catch_vfork;
15454   ops->remove_location = remove_catch_vfork;
15455   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15456   ops->print_it = print_it_catch_vfork;
15457   ops->print_one = print_one_catch_vfork;
15458   ops->print_mention = print_mention_catch_vfork;
15459   ops->print_recreate = print_recreate_catch_vfork;
15460
15461   /* Exec catchpoints.  */
15462   ops = &catch_exec_breakpoint_ops;
15463   *ops = base_breakpoint_ops;
15464   ops->insert_location = insert_catch_exec;
15465   ops->remove_location = remove_catch_exec;
15466   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15467   ops->print_it = print_it_catch_exec;
15468   ops->print_one = print_one_catch_exec;
15469   ops->print_mention = print_mention_catch_exec;
15470   ops->print_recreate = print_recreate_catch_exec;
15471
15472   /* Solib-related catchpoints.  */
15473   ops = &catch_solib_breakpoint_ops;
15474   *ops = base_breakpoint_ops;
15475   ops->insert_location = insert_catch_solib;
15476   ops->remove_location = remove_catch_solib;
15477   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15478   ops->check_status = check_status_catch_solib;
15479   ops->print_it = print_it_catch_solib;
15480   ops->print_one = print_one_catch_solib;
15481   ops->print_mention = print_mention_catch_solib;
15482   ops->print_recreate = print_recreate_catch_solib;
15483
15484   ops = &dprintf_breakpoint_ops;
15485   *ops = bkpt_base_breakpoint_ops;
15486   ops->re_set = dprintf_re_set;
15487   ops->resources_needed = bkpt_resources_needed;
15488   ops->print_it = bkpt_print_it;
15489   ops->print_mention = bkpt_print_mention;
15490   ops->print_recreate = dprintf_print_recreate;
15491   ops->after_condition_true = dprintf_after_condition_true;
15492   ops->breakpoint_hit = dprintf_breakpoint_hit;
15493 }
15494
15495 /* Chain containing all defined "enable breakpoint" subcommands.  */
15496
15497 static struct cmd_list_element *enablebreaklist = NULL;
15498
15499 /* See breakpoint.h.  */
15500
15501 cmd_list_element *commands_cmd_element = nullptr;
15502
15503 void
15504 _initialize_breakpoint (void)
15505 {
15506   struct cmd_list_element *c;
15507
15508   initialize_breakpoint_ops ();
15509
15510   gdb::observers::solib_unloaded.attach (disable_breakpoints_in_unloaded_shlib);
15511   gdb::observers::free_objfile.attach (disable_breakpoints_in_freed_objfile);
15512   gdb::observers::memory_changed.attach (invalidate_bp_value_on_memory_change);
15513
15514   breakpoint_objfile_key
15515     = register_objfile_data_with_cleanup (NULL, free_breakpoint_objfile_data);
15516
15517   breakpoint_chain = 0;
15518   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15519      before a breakpoint is set.  */
15520   breakpoint_count = 0;
15521
15522   tracepoint_count = 0;
15523
15524   add_com ("ignore", class_breakpoint, ignore_command, _("\
15525 Set ignore-count of breakpoint number N to COUNT.\n\
15526 Usage is `ignore N COUNT'."));
15527
15528   commands_cmd_element = add_com ("commands", class_breakpoint,
15529                                   commands_command, _("\
15530 Set commands to be executed when the given breakpoints are hit.\n\
15531 Give a space-separated breakpoint list as argument after \"commands\".\n\
15532 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
15533 (e.g. `5-7').\n\
15534 With no argument, the targeted breakpoint is the last one set.\n\
15535 The commands themselves follow starting on the next line.\n\
15536 Type a line containing \"end\" to indicate the end of them.\n\
15537 Give \"silent\" as the first line to make the breakpoint silent;\n\
15538 then no output is printed when it is hit, except what the commands print."));
15539
15540   c = add_com ("condition", class_breakpoint, condition_command, _("\
15541 Specify breakpoint number N to break only if COND is true.\n\
15542 Usage is `condition N COND', where N is an integer and COND is an\n\
15543 expression to be evaluated whenever breakpoint N is reached."));
15544   set_cmd_completer (c, condition_completer);
15545
15546   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15547 Set a temporary breakpoint.\n\
15548 Like \"break\" except the breakpoint is only temporary,\n\
15549 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15550 by using \"enable delete\" on the breakpoint number.\n\
15551 \n"
15552 BREAK_ARGS_HELP ("tbreak")));
15553   set_cmd_completer (c, location_completer);
15554
15555   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15556 Set a hardware assisted breakpoint.\n\
15557 Like \"break\" except the breakpoint requires hardware support,\n\
15558 some target hardware may not have this support.\n\
15559 \n"
15560 BREAK_ARGS_HELP ("hbreak")));
15561   set_cmd_completer (c, location_completer);
15562
15563   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15564 Set a temporary hardware assisted breakpoint.\n\
15565 Like \"hbreak\" except the breakpoint is only temporary,\n\
15566 so it will be deleted when hit.\n\
15567 \n"
15568 BREAK_ARGS_HELP ("thbreak")));
15569   set_cmd_completer (c, location_completer);
15570
15571   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15572 Enable some breakpoints.\n\
15573 Give breakpoint numbers (separated by spaces) as arguments.\n\
15574 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15575 This is used to cancel the effect of the \"disable\" command.\n\
15576 With a subcommand you can enable temporarily."),
15577                   &enablelist, "enable ", 1, &cmdlist);
15578
15579   add_com_alias ("en", "enable", class_breakpoint, 1);
15580
15581   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15582 Enable some breakpoints.\n\
15583 Give breakpoint numbers (separated by spaces) as arguments.\n\
15584 This is used to cancel the effect of the \"disable\" command.\n\
15585 May be abbreviated to simply \"enable\".\n"),
15586                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15587
15588   add_cmd ("once", no_class, enable_once_command, _("\
15589 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15590 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15591            &enablebreaklist);
15592
15593   add_cmd ("delete", no_class, enable_delete_command, _("\
15594 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15595 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15596            &enablebreaklist);
15597
15598   add_cmd ("count", no_class, enable_count_command, _("\
15599 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15600 If a breakpoint is hit while enabled in this fashion,\n\
15601 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15602            &enablebreaklist);
15603
15604   add_cmd ("delete", no_class, enable_delete_command, _("\
15605 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15606 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15607            &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            &enablelist);
15613
15614   add_cmd ("count", no_class, enable_count_command, _("\
15615 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15616 If a breakpoint is hit while enabled in this fashion,\n\
15617 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15618            &enablelist);
15619
15620   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15621 Disable some breakpoints.\n\
15622 Arguments are breakpoint numbers with spaces in between.\n\
15623 To disable all breakpoints, give no argument.\n\
15624 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15625                   &disablelist, "disable ", 1, &cmdlist);
15626   add_com_alias ("dis", "disable", class_breakpoint, 1);
15627   add_com_alias ("disa", "disable", class_breakpoint, 1);
15628
15629   add_cmd ("breakpoints", class_alias, disable_command, _("\
15630 Disable some breakpoints.\n\
15631 Arguments are breakpoint numbers with spaces in between.\n\
15632 To disable all breakpoints, give no argument.\n\
15633 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15634 This command may be abbreviated \"disable\"."),
15635            &disablelist);
15636
15637   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15638 Delete some breakpoints or auto-display expressions.\n\
15639 Arguments are breakpoint numbers with spaces in between.\n\
15640 To delete all breakpoints, give no argument.\n\
15641 \n\
15642 Also a prefix command for deletion of other GDB objects.\n\
15643 The \"unset\" command is also an alias for \"delete\"."),
15644                   &deletelist, "delete ", 1, &cmdlist);
15645   add_com_alias ("d", "delete", class_breakpoint, 1);
15646   add_com_alias ("del", "delete", class_breakpoint, 1);
15647
15648   add_cmd ("breakpoints", class_alias, delete_command, _("\
15649 Delete some breakpoints or auto-display expressions.\n\
15650 Arguments are breakpoint numbers with spaces in between.\n\
15651 To delete all breakpoints, give no argument.\n\
15652 This command may be abbreviated \"delete\"."),
15653            &deletelist);
15654
15655   add_com ("clear", class_breakpoint, clear_command, _("\
15656 Clear breakpoint at specified location.\n\
15657 Argument may be a linespec, explicit, or address location as described below.\n\
15658 \n\
15659 With no argument, clears all breakpoints in the line that the selected frame\n\
15660 is executing in.\n"
15661 "\n" LOCATION_HELP_STRING "\n\
15662 See also the \"delete\" command which clears breakpoints by number."));
15663   add_com_alias ("cl", "clear", class_breakpoint, 1);
15664
15665   c = add_com ("break", class_breakpoint, break_command, _("\
15666 Set breakpoint at specified location.\n"
15667 BREAK_ARGS_HELP ("break")));
15668   set_cmd_completer (c, location_completer);
15669
15670   add_com_alias ("b", "break", class_run, 1);
15671   add_com_alias ("br", "break", class_run, 1);
15672   add_com_alias ("bre", "break", class_run, 1);
15673   add_com_alias ("brea", "break", class_run, 1);
15674
15675   if (dbx_commands)
15676     {
15677       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15678 Break in function/address or break at a line in the current file."),
15679                              &stoplist, "stop ", 1, &cmdlist);
15680       add_cmd ("in", class_breakpoint, stopin_command,
15681                _("Break in function or address."), &stoplist);
15682       add_cmd ("at", class_breakpoint, stopat_command,
15683                _("Break at a line in the current file."), &stoplist);
15684       add_com ("status", class_info, info_breakpoints_command, _("\
15685 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15686 The \"Type\" column indicates one of:\n\
15687 \tbreakpoint     - normal breakpoint\n\
15688 \twatchpoint     - watchpoint\n\
15689 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15690 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15691 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15692 address and file/line number respectively.\n\
15693 \n\
15694 Convenience variable \"$_\" and default examine address for \"x\"\n\
15695 are set to the address of the last breakpoint listed unless the command\n\
15696 is prefixed with \"server \".\n\n\
15697 Convenience variable \"$bpnum\" contains the number of the last\n\
15698 breakpoint set."));
15699     }
15700
15701   add_info ("breakpoints", info_breakpoints_command, _("\
15702 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15703 The \"Type\" column indicates one of:\n\
15704 \tbreakpoint     - normal breakpoint\n\
15705 \twatchpoint     - watchpoint\n\
15706 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15707 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15708 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15709 address and file/line number respectively.\n\
15710 \n\
15711 Convenience variable \"$_\" and default examine address for \"x\"\n\
15712 are set to the address of the last breakpoint listed unless the command\n\
15713 is prefixed with \"server \".\n\n\
15714 Convenience variable \"$bpnum\" contains the number of the last\n\
15715 breakpoint set."));
15716
15717   add_info_alias ("b", "breakpoints", 1);
15718
15719   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15720 Status of all breakpoints, or breakpoint number NUMBER.\n\
15721 The \"Type\" column indicates one of:\n\
15722 \tbreakpoint     - normal breakpoint\n\
15723 \twatchpoint     - watchpoint\n\
15724 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15725 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15726 \tuntil          - internal breakpoint used by the \"until\" command\n\
15727 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15728 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15729 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15730 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15731 address and file/line number respectively.\n\
15732 \n\
15733 Convenience variable \"$_\" and default examine address for \"x\"\n\
15734 are set to the address of the last breakpoint listed unless the command\n\
15735 is prefixed with \"server \".\n\n\
15736 Convenience variable \"$bpnum\" contains the number of the last\n\
15737 breakpoint set."),
15738            &maintenanceinfolist);
15739
15740   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15741 Set catchpoints to catch events."),
15742                   &catch_cmdlist, "catch ",
15743                   0/*allow-unknown*/, &cmdlist);
15744
15745   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15746 Set temporary catchpoints to catch events."),
15747                   &tcatch_cmdlist, "tcatch ",
15748                   0/*allow-unknown*/, &cmdlist);
15749
15750   add_catch_command ("fork", _("Catch calls to fork."),
15751                      catch_fork_command_1,
15752                      NULL,
15753                      (void *) (uintptr_t) catch_fork_permanent,
15754                      (void *) (uintptr_t) catch_fork_temporary);
15755   add_catch_command ("vfork", _("Catch calls to vfork."),
15756                      catch_fork_command_1,
15757                      NULL,
15758                      (void *) (uintptr_t) catch_vfork_permanent,
15759                      (void *) (uintptr_t) catch_vfork_temporary);
15760   add_catch_command ("exec", _("Catch calls to exec."),
15761                      catch_exec_command_1,
15762                      NULL,
15763                      CATCH_PERMANENT,
15764                      CATCH_TEMPORARY);
15765   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15766 Usage: catch load [REGEX]\n\
15767 If REGEX is given, only stop for libraries matching the regular expression."),
15768                      catch_load_command_1,
15769                      NULL,
15770                      CATCH_PERMANENT,
15771                      CATCH_TEMPORARY);
15772   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15773 Usage: catch unload [REGEX]\n\
15774 If REGEX is given, only stop for libraries matching the regular expression."),
15775                      catch_unload_command_1,
15776                      NULL,
15777                      CATCH_PERMANENT,
15778                      CATCH_TEMPORARY);
15779
15780   c = add_com ("watch", class_breakpoint, watch_command, _("\
15781 Set a watchpoint for an expression.\n\
15782 Usage: watch [-l|-location] EXPRESSION\n\
15783 A watchpoint stops execution of your program whenever the value of\n\
15784 an expression changes.\n\
15785 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15786 the memory to which it refers."));
15787   set_cmd_completer (c, expression_completer);
15788
15789   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15790 Set a read watchpoint for an expression.\n\
15791 Usage: rwatch [-l|-location] EXPRESSION\n\
15792 A watchpoint stops execution of your program whenever the value of\n\
15793 an expression is read.\n\
15794 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15795 the memory to which it refers."));
15796   set_cmd_completer (c, expression_completer);
15797
15798   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15799 Set a watchpoint for an expression.\n\
15800 Usage: awatch [-l|-location] EXPRESSION\n\
15801 A watchpoint stops execution of your program whenever the value of\n\
15802 an expression is either read or written.\n\
15803 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15804 the memory to which it refers."));
15805   set_cmd_completer (c, expression_completer);
15806
15807   add_info ("watchpoints", info_watchpoints_command, _("\
15808 Status of specified watchpoints (all watchpoints if no argument)."));
15809
15810   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15811      respond to changes - contrary to the description.  */
15812   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15813                             &can_use_hw_watchpoints, _("\
15814 Set debugger's willingness to use watchpoint hardware."), _("\
15815 Show debugger's willingness to use watchpoint hardware."), _("\
15816 If zero, gdb will not use hardware for new watchpoints, even if\n\
15817 such is available.  (However, any hardware watchpoints that were\n\
15818 created before setting this to nonzero, will continue to use watchpoint\n\
15819 hardware.)"),
15820                             NULL,
15821                             show_can_use_hw_watchpoints,
15822                             &setlist, &showlist);
15823
15824   can_use_hw_watchpoints = 1;
15825
15826   /* Tracepoint manipulation commands.  */
15827
15828   c = add_com ("trace", class_breakpoint, trace_command, _("\
15829 Set a tracepoint at specified location.\n\
15830 \n"
15831 BREAK_ARGS_HELP ("trace") "\n\
15832 Do \"help tracepoints\" for info on other tracepoint commands."));
15833   set_cmd_completer (c, location_completer);
15834
15835   add_com_alias ("tp", "trace", class_alias, 0);
15836   add_com_alias ("tr", "trace", class_alias, 1);
15837   add_com_alias ("tra", "trace", class_alias, 1);
15838   add_com_alias ("trac", "trace", class_alias, 1);
15839
15840   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15841 Set a fast tracepoint at specified location.\n\
15842 \n"
15843 BREAK_ARGS_HELP ("ftrace") "\n\
15844 Do \"help tracepoints\" for info on other tracepoint commands."));
15845   set_cmd_completer (c, location_completer);
15846
15847   c = add_com ("strace", class_breakpoint, strace_command, _("\
15848 Set a static tracepoint at location or marker.\n\
15849 \n\
15850 strace [LOCATION] [if CONDITION]\n\
15851 LOCATION may be a linespec, explicit, or address location (described below) \n\
15852 or -m MARKER_ID.\n\n\
15853 If a marker id is specified, probe the marker with that name.  With\n\
15854 no LOCATION, uses current execution address of the selected stack frame.\n\
15855 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15856 This collects arbitrary user data passed in the probe point call to the\n\
15857 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15858 by printing the $_sdata variable like any other convenience variable.\n\
15859 \n\
15860 CONDITION is a boolean expression.\n\
15861 \n" LOCATION_HELP_STRING "\n\
15862 Multiple tracepoints at one place are permitted, and useful if their\n\
15863 conditions are different.\n\
15864 \n\
15865 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15866 Do \"help tracepoints\" for info on other tracepoint commands."));
15867   set_cmd_completer (c, location_completer);
15868
15869   add_info ("tracepoints", info_tracepoints_command, _("\
15870 Status of specified tracepoints (all tracepoints if no argument).\n\
15871 Convenience variable \"$tpnum\" contains the number of the\n\
15872 last tracepoint set."));
15873
15874   add_info_alias ("tp", "tracepoints", 1);
15875
15876   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15877 Delete specified tracepoints.\n\
15878 Arguments are tracepoint numbers, separated by spaces.\n\
15879 No argument means delete all tracepoints."),
15880            &deletelist);
15881   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
15882
15883   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15884 Disable specified tracepoints.\n\
15885 Arguments are tracepoint numbers, separated by spaces.\n\
15886 No argument means disable all tracepoints."),
15887            &disablelist);
15888   deprecate_cmd (c, "disable");
15889
15890   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15891 Enable specified tracepoints.\n\
15892 Arguments are tracepoint numbers, separated by spaces.\n\
15893 No argument means enable all tracepoints."),
15894            &enablelist);
15895   deprecate_cmd (c, "enable");
15896
15897   add_com ("passcount", class_trace, trace_pass_command, _("\
15898 Set the passcount for a tracepoint.\n\
15899 The trace will end when the tracepoint has been passed 'count' times.\n\
15900 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15901 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
15902
15903   add_prefix_cmd ("save", class_breakpoint, save_command,
15904                   _("Save breakpoint definitions as a script."),
15905                   &save_cmdlist, "save ",
15906                   0/*allow-unknown*/, &cmdlist);
15907
15908   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
15909 Save current breakpoint definitions as a script.\n\
15910 This includes all types of breakpoints (breakpoints, watchpoints,\n\
15911 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
15912 session to restore them."),
15913                &save_cmdlist);
15914   set_cmd_completer (c, filename_completer);
15915
15916   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
15917 Save current tracepoint definitions as a script.\n\
15918 Use the 'source' command in another debug session to restore them."),
15919                &save_cmdlist);
15920   set_cmd_completer (c, filename_completer);
15921
15922   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
15923   deprecate_cmd (c, "save tracepoints");
15924
15925   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
15926 Breakpoint specific settings\n\
15927 Configure various breakpoint-specific variables such as\n\
15928 pending breakpoint behavior"),
15929                   &breakpoint_set_cmdlist, "set breakpoint ",
15930                   0/*allow-unknown*/, &setlist);
15931   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
15932 Breakpoint specific settings\n\
15933 Configure various breakpoint-specific variables such as\n\
15934 pending breakpoint behavior"),
15935                   &breakpoint_show_cmdlist, "show breakpoint ",
15936                   0/*allow-unknown*/, &showlist);
15937
15938   add_setshow_auto_boolean_cmd ("pending", no_class,
15939                                 &pending_break_support, _("\
15940 Set debugger's behavior regarding pending breakpoints."), _("\
15941 Show debugger's behavior regarding pending breakpoints."), _("\
15942 If on, an unrecognized breakpoint location will cause gdb to create a\n\
15943 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
15944 an error.  If auto, an unrecognized breakpoint location results in a\n\
15945 user-query to see if a pending breakpoint should be created."),
15946                                 NULL,
15947                                 show_pending_break_support,
15948                                 &breakpoint_set_cmdlist,
15949                                 &breakpoint_show_cmdlist);
15950
15951   pending_break_support = AUTO_BOOLEAN_AUTO;
15952
15953   add_setshow_boolean_cmd ("auto-hw", no_class,
15954                            &automatic_hardware_breakpoints, _("\
15955 Set automatic usage of hardware breakpoints."), _("\
15956 Show automatic usage of hardware breakpoints."), _("\
15957 If set, the debugger will automatically use hardware breakpoints for\n\
15958 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
15959 a warning will be emitted for such breakpoints."),
15960                            NULL,
15961                            show_automatic_hardware_breakpoints,
15962                            &breakpoint_set_cmdlist,
15963                            &breakpoint_show_cmdlist);
15964
15965   add_setshow_boolean_cmd ("always-inserted", class_support,
15966                            &always_inserted_mode, _("\
15967 Set mode for inserting breakpoints."), _("\
15968 Show mode for inserting breakpoints."), _("\
15969 When this mode is on, breakpoints are inserted immediately as soon as\n\
15970 they're created, kept inserted even when execution stops, and removed\n\
15971 only when the user deletes them.  When this mode is off (the default),\n\
15972 breakpoints are inserted only when execution continues, and removed\n\
15973 when execution stops."),
15974                                 NULL,
15975                                 &show_always_inserted_mode,
15976                                 &breakpoint_set_cmdlist,
15977                                 &breakpoint_show_cmdlist);
15978
15979   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
15980                         condition_evaluation_enums,
15981                         &condition_evaluation_mode_1, _("\
15982 Set mode of breakpoint condition evaluation."), _("\
15983 Show mode of breakpoint condition evaluation."), _("\
15984 When this is set to \"host\", breakpoint conditions will be\n\
15985 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
15986 breakpoint conditions will be downloaded to the target (if the target\n\
15987 supports such feature) and conditions will be evaluated on the target's side.\n\
15988 If this is set to \"auto\" (default), this will be automatically set to\n\
15989 \"target\" if it supports condition evaluation, otherwise it will\n\
15990 be set to \"gdb\""),
15991                            &set_condition_evaluation_mode,
15992                            &show_condition_evaluation_mode,
15993                            &breakpoint_set_cmdlist,
15994                            &breakpoint_show_cmdlist);
15995
15996   add_com ("break-range", class_breakpoint, break_range_command, _("\
15997 Set a breakpoint for an address range.\n\
15998 break-range START-LOCATION, END-LOCATION\n\
15999 where START-LOCATION and END-LOCATION can be one of the following:\n\
16000   LINENUM, for that line in the current file,\n\
16001   FILE:LINENUM, for that line in that file,\n\
16002   +OFFSET, for that number of lines after the current line\n\
16003            or the start of the range\n\
16004   FUNCTION, for the first line in that function,\n\
16005   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16006   *ADDRESS, for the instruction at that address.\n\
16007 \n\
16008 The breakpoint will stop execution of the inferior whenever it executes\n\
16009 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16010 range (including START-LOCATION and END-LOCATION)."));
16011
16012   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16013 Set a dynamic printf at specified location.\n\
16014 dprintf location,format string,arg1,arg2,...\n\
16015 location may be a linespec, explicit, or address location.\n"
16016 "\n" LOCATION_HELP_STRING));
16017   set_cmd_completer (c, location_completer);
16018
16019   add_setshow_enum_cmd ("dprintf-style", class_support,
16020                         dprintf_style_enums, &dprintf_style, _("\
16021 Set the style of usage for dynamic printf."), _("\
16022 Show the style of usage for dynamic printf."), _("\
16023 This setting chooses how GDB will do a dynamic printf.\n\
16024 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16025 console, as with the \"printf\" command.\n\
16026 If the value is \"call\", the print is done by calling a function in your\n\
16027 program; by default printf(), but you can choose a different function or\n\
16028 output stream by setting dprintf-function and dprintf-channel."),
16029                         update_dprintf_commands, NULL,
16030                         &setlist, &showlist);
16031
16032   dprintf_function = xstrdup ("printf");
16033   add_setshow_string_cmd ("dprintf-function", class_support,
16034                           &dprintf_function, _("\
16035 Set the function to use for dynamic printf"), _("\
16036 Show the function to use for dynamic printf"), NULL,
16037                           update_dprintf_commands, NULL,
16038                           &setlist, &showlist);
16039
16040   dprintf_channel = xstrdup ("");
16041   add_setshow_string_cmd ("dprintf-channel", class_support,
16042                           &dprintf_channel, _("\
16043 Set the channel to use for dynamic printf"), _("\
16044 Show the channel to use for dynamic printf"), NULL,
16045                           update_dprintf_commands, NULL,
16046                           &setlist, &showlist);
16047
16048   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16049                            &disconnected_dprintf, _("\
16050 Set whether dprintf continues after GDB disconnects."), _("\
16051 Show whether dprintf continues after GDB disconnects."), _("\
16052 Use this to let dprintf commands continue to hit and produce output\n\
16053 even if GDB disconnects or detaches from the target."),
16054                            NULL,
16055                            NULL,
16056                            &setlist, &showlist);
16057
16058   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16059 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16060 (target agent only) This is useful for formatted output in user-defined commands."));
16061
16062   automatic_hardware_breakpoints = 1;
16063
16064   gdb::observers::about_to_proceed.attach (breakpoint_about_to_proceed);
16065   gdb::observers::thread_exit.attach (remove_threaded_breakpoints);
16066 }