Remove return value from remove_breakpoints_inf
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2019 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #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 "common/format.h"
69 #include "thread-fsm.h"
70 #include "tid-parse.h"
71 #include "cli/cli-style.h"
72 #include "mi/mi-main.h"
73
74 /* readline include files */
75 #include "readline/readline.h"
76 #include "readline/history.h"
77
78 /* readline defines this.  */
79 #undef savestring
80
81 #include "mi/mi-common.h"
82 #include "extension.h"
83 #include <algorithm>
84 #include "progspace-and-thread.h"
85 #include "common/array-view.h"
86 #include "common/gdb_optional.h"
87
88 /* Prototypes for local functions.  */
89
90 static void map_breakpoint_numbers (const char *,
91                                     gdb::function_view<void (breakpoint *)>);
92
93 static void breakpoint_re_set_default (struct breakpoint *);
94
95 static void
96   create_sals_from_location_default (const struct event_location *location,
97                                      struct linespec_result *canonical,
98                                      enum bptype type_wanted);
99
100 static void create_breakpoints_sal_default (struct gdbarch *,
101                                             struct linespec_result *,
102                                             gdb::unique_xmalloc_ptr<char>,
103                                             gdb::unique_xmalloc_ptr<char>,
104                                             enum bptype,
105                                             enum bpdisp, int, int,
106                                             int,
107                                             const struct breakpoint_ops *,
108                                             int, int, int, unsigned);
109
110 static std::vector<symtab_and_line> decode_location_default
111   (struct breakpoint *b, const struct event_location *location,
112    struct program_space *search_pspace);
113
114 static int can_use_hardware_watchpoint
115     (const std::vector<value_ref_ptr> &vals);
116
117 static void mention (struct breakpoint *);
118
119 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
120                                                                enum bptype,
121                                                                const struct breakpoint_ops *);
122 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
123                                                        const struct symtab_and_line *);
124
125 /* This function is used in gdbtk sources and thus can not be made
126    static.  */
127 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
128                                        struct symtab_and_line,
129                                        enum bptype,
130                                        const struct breakpoint_ops *);
131
132 static struct breakpoint *
133   momentary_breakpoint_from_master (struct breakpoint *orig,
134                                     enum bptype type,
135                                     const struct breakpoint_ops *ops,
136                                     int loc_enabled);
137
138 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
139
140 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
141                                             CORE_ADDR bpaddr,
142                                             enum bptype bptype);
143
144 static void describe_other_breakpoints (struct gdbarch *,
145                                         struct program_space *, CORE_ADDR,
146                                         struct obj_section *, int);
147
148 static int watchpoint_locations_match (struct bp_location *loc1,
149                                        struct bp_location *loc2);
150
151 static int breakpoint_location_address_match (struct bp_location *bl,
152                                               const struct address_space *aspace,
153                                               CORE_ADDR addr);
154
155 static int breakpoint_location_address_range_overlap (struct bp_location *,
156                                                       const address_space *,
157                                                       CORE_ADDR, int);
158
159 static int remove_breakpoint (struct bp_location *);
160 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
161
162 static enum print_stop_action print_bp_stop_message (bpstat bs);
163
164 static int hw_breakpoint_used_count (void);
165
166 static int hw_watchpoint_use_count (struct breakpoint *);
167
168 static int hw_watchpoint_used_count_others (struct breakpoint *except,
169                                             enum bptype type,
170                                             int *other_type_used);
171
172 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
173                                     int count);
174
175 static void free_bp_location (struct bp_location *loc);
176 static void incref_bp_location (struct bp_location *loc);
177 static void decref_bp_location (struct bp_location **loc);
178
179 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
180
181 /* update_global_location_list's modes of operation wrt to whether to
182    insert locations now.  */
183 enum ugll_insert_mode
184 {
185   /* Don't insert any breakpoint locations into the inferior, only
186      remove already-inserted locations that no longer should be
187      inserted.  Functions that delete a breakpoint or breakpoints
188      should specify this mode, so that deleting a breakpoint doesn't
189      have the side effect of inserting the locations of other
190      breakpoints that are marked not-inserted, but should_be_inserted
191      returns true on them.
192
193      This behavior is useful is situations close to tear-down -- e.g.,
194      after an exec, while the target still has execution, but
195      breakpoint shadows of the previous executable image should *NOT*
196      be restored to the new image; or before detaching, where the
197      target still has execution and wants to delete breakpoints from
198      GDB's lists, and all breakpoints had already been removed from
199      the inferior.  */
200   UGLL_DONT_INSERT,
201
202   /* May insert breakpoints iff breakpoints_should_be_inserted_now
203      claims breakpoints should be inserted now.  */
204   UGLL_MAY_INSERT,
205
206   /* Insert locations now, irrespective of
207      breakpoints_should_be_inserted_now.  E.g., say all threads are
208      stopped right now, and the user did "continue".  We need to
209      insert breakpoints _before_ resuming the target, but
210      UGLL_MAY_INSERT wouldn't insert them, because
211      breakpoints_should_be_inserted_now returns false at that point,
212      as no thread is running yet.  */
213   UGLL_INSERT
214 };
215
216 static void update_global_location_list (enum ugll_insert_mode);
217
218 static void update_global_location_list_nothrow (enum ugll_insert_mode);
219
220 static int is_hardware_watchpoint (const struct breakpoint *bpt);
221
222 static void insert_breakpoint_locations (void);
223
224 static void trace_pass_command (const char *, int);
225
226 static void set_tracepoint_count (int num);
227
228 static int is_masked_watchpoint (const struct breakpoint *b);
229
230 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
231
232 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
233    otherwise.  */
234
235 static int strace_marker_p (struct breakpoint *b);
236
237 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
238    that are implemented on top of software or hardware breakpoints
239    (user breakpoints, internal and momentary breakpoints, etc.).  */
240 static struct breakpoint_ops bkpt_base_breakpoint_ops;
241
242 /* Internal breakpoints class type.  */
243 static struct breakpoint_ops internal_breakpoint_ops;
244
245 /* Momentary breakpoints class type.  */
246 static struct breakpoint_ops momentary_breakpoint_ops;
247
248 /* The breakpoint_ops structure to be used in regular user created
249    breakpoints.  */
250 struct breakpoint_ops bkpt_breakpoint_ops;
251
252 /* Breakpoints set on probes.  */
253 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
254
255 /* Dynamic printf class type.  */
256 struct breakpoint_ops dprintf_breakpoint_ops;
257
258 /* The style in which to perform a dynamic printf.  This is a user
259    option because different output options have different tradeoffs;
260    if GDB does the printing, there is better error handling if there
261    is a problem with any of the arguments, but using an inferior
262    function lets you have special-purpose printers and sending of
263    output to the same place as compiled-in print functions.  */
264
265 static const char dprintf_style_gdb[] = "gdb";
266 static const char dprintf_style_call[] = "call";
267 static const char dprintf_style_agent[] = "agent";
268 static const char *const dprintf_style_enums[] = {
269   dprintf_style_gdb,
270   dprintf_style_call,
271   dprintf_style_agent,
272   NULL
273 };
274 static const char *dprintf_style = dprintf_style_gdb;
275
276 /* The function to use for dynamic printf if the preferred style is to
277    call into the inferior.  The value is simply a string that is
278    copied into the command, so it can be anything that GDB can
279    evaluate to a callable address, not necessarily a function name.  */
280
281 static char *dprintf_function;
282
283 /* The channel to use for dynamic printf if the preferred style is to
284    call into the inferior; if a nonempty string, it will be passed to
285    the call as the first argument, with the format string as the
286    second.  As with the dprintf function, this can be anything that
287    GDB knows how to evaluate, so in addition to common choices like
288    "stderr", this could be an app-specific expression like
289    "mystreams[curlogger]".  */
290
291 static char *dprintf_channel;
292
293 /* True if dprintf commands should continue to operate even if GDB
294    has disconnected.  */
295 static int disconnected_dprintf = 1;
296
297 struct command_line *
298 breakpoint_commands (struct breakpoint *b)
299 {
300   return b->commands ? b->commands.get () : NULL;
301 }
302
303 /* Flag indicating that a command has proceeded the inferior past the
304    current breakpoint.  */
305
306 static int breakpoint_proceeded;
307
308 const char *
309 bpdisp_text (enum bpdisp disp)
310 {
311   /* NOTE: the following values are a part of MI protocol and
312      represent values of 'disp' field returned when inferior stops at
313      a breakpoint.  */
314   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
315
316   return bpdisps[(int) disp];
317 }
318
319 /* Prototypes for exported functions.  */
320 /* If FALSE, gdb will not use hardware support for watchpoints, even
321    if such is available.  */
322 static int can_use_hw_watchpoints;
323
324 static void
325 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
326                              struct cmd_list_element *c,
327                              const char *value)
328 {
329   fprintf_filtered (file,
330                     _("Debugger's willingness to use "
331                       "watchpoint hardware is %s.\n"),
332                     value);
333 }
334
335 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
336    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
337    for unrecognized breakpoint locations.
338    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
339 static enum auto_boolean pending_break_support;
340 static void
341 show_pending_break_support (struct ui_file *file, int from_tty,
342                             struct cmd_list_element *c,
343                             const char *value)
344 {
345   fprintf_filtered (file,
346                     _("Debugger's behavior regarding "
347                       "pending breakpoints is %s.\n"),
348                     value);
349 }
350
351 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
352    set with "break" but falling in read-only memory.
353    If 0, gdb will warn about such breakpoints, but won't automatically
354    use hardware breakpoints.  */
355 static int automatic_hardware_breakpoints;
356 static void
357 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
358                                      struct cmd_list_element *c,
359                                      const char *value)
360 {
361   fprintf_filtered (file,
362                     _("Automatic usage of hardware breakpoints is %s.\n"),
363                     value);
364 }
365
366 /* If on, GDB keeps breakpoints inserted even if the inferior is
367    stopped, and immediately inserts any new breakpoints as soon as
368    they're created.  If off (default), GDB keeps breakpoints off of
369    the target as long as possible.  That is, it delays inserting
370    breakpoints until the next resume, and removes them again when the
371    target fully stops.  This is a bit safer in case GDB crashes while
372    processing user input.  */
373 static int always_inserted_mode = 0;
374
375 static void
376 show_always_inserted_mode (struct ui_file *file, int from_tty,
377                      struct cmd_list_element *c, const char *value)
378 {
379   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
380                     value);
381 }
382
383 /* See breakpoint.h.  */
384
385 int
386 breakpoints_should_be_inserted_now (void)
387 {
388   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
389     {
390       /* If breakpoints are global, they should be inserted even if no
391          thread under gdb's control is running, or even if there are
392          no threads under GDB's control yet.  */
393       return 1;
394     }
395   else if (target_has_execution)
396     {
397       if (always_inserted_mode)
398         {
399           /* The user wants breakpoints inserted even if all threads
400              are stopped.  */
401           return 1;
402         }
403
404       if (threads_are_executing ())
405         return 1;
406
407       /* Don't remove breakpoints yet if, even though all threads are
408          stopped, we still have events to process.  */
409       for (thread_info *tp : all_non_exited_threads ())
410         if (tp->resumed
411             && tp->suspend.waitstatus_pending_p)
412           return 1;
413     }
414   return 0;
415 }
416
417 static const char condition_evaluation_both[] = "host or target";
418
419 /* Modes for breakpoint condition evaluation.  */
420 static const char condition_evaluation_auto[] = "auto";
421 static const char condition_evaluation_host[] = "host";
422 static const char condition_evaluation_target[] = "target";
423 static const char *const condition_evaluation_enums[] = {
424   condition_evaluation_auto,
425   condition_evaluation_host,
426   condition_evaluation_target,
427   NULL
428 };
429
430 /* Global that holds the current mode for breakpoint condition evaluation.  */
431 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
432
433 /* Global that we use to display information to the user (gets its value from
434    condition_evaluation_mode_1.  */
435 static const char *condition_evaluation_mode = condition_evaluation_auto;
436
437 /* Translate a condition evaluation mode MODE into either "host"
438    or "target".  This is used mostly to translate from "auto" to the
439    real setting that is being used.  It returns the translated
440    evaluation mode.  */
441
442 static const char *
443 translate_condition_evaluation_mode (const char *mode)
444 {
445   if (mode == condition_evaluation_auto)
446     {
447       if (target_supports_evaluation_of_breakpoint_conditions ())
448         return condition_evaluation_target;
449       else
450         return condition_evaluation_host;
451     }
452   else
453     return mode;
454 }
455
456 /* Discovers what condition_evaluation_auto translates to.  */
457
458 static const char *
459 breakpoint_condition_evaluation_mode (void)
460 {
461   return translate_condition_evaluation_mode (condition_evaluation_mode);
462 }
463
464 /* Return true if GDB should evaluate breakpoint conditions or false
465    otherwise.  */
466
467 static int
468 gdb_evaluates_breakpoint_condition_p (void)
469 {
470   const char *mode = breakpoint_condition_evaluation_mode ();
471
472   return (mode == condition_evaluation_host);
473 }
474
475 /* Are we executing breakpoint commands?  */
476 static int executing_breakpoint_commands;
477
478 /* Are overlay event breakpoints enabled? */
479 static int overlay_events_enabled;
480
481 /* See description in breakpoint.h. */
482 int target_exact_watchpoints = 0;
483
484 /* Walk the following statement or block through all breakpoints.
485    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
486    current breakpoint.  */
487
488 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
489
490 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
491         for (B = breakpoint_chain;      \
492              B ? (TMP=B->next, 1): 0;   \
493              B = TMP)
494
495 /* Similar iterator for the low-level breakpoints.  SAFE variant is
496    not provided so update_global_location_list must not be called
497    while executing the block of ALL_BP_LOCATIONS.  */
498
499 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
500         for (BP_TMP = bp_locations;                                     \
501              BP_TMP < bp_locations + bp_locations_count && (B = *BP_TMP);\
502              BP_TMP++)
503
504 /* Iterates through locations with address ADDRESS for the currently selected
505    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
506    to where the loop should start from.
507    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
508    appropriate location to start with.  */
509
510 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
511         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
512              BP_LOCP_TMP = BP_LOCP_START;                               \
513              BP_LOCP_START                                              \
514              && (BP_LOCP_TMP < bp_locations + bp_locations_count        \
515              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
516              BP_LOCP_TMP++)
517
518 /* Iterator for tracepoints only.  */
519
520 #define ALL_TRACEPOINTS(B)  \
521   for (B = breakpoint_chain; B; B = B->next)  \
522     if (is_tracepoint (B))
523
524 /* Chains of all breakpoints defined.  */
525
526 struct breakpoint *breakpoint_chain;
527
528 /* Array is sorted by bp_locations_compare - primarily by the ADDRESS.  */
529
530 static struct bp_location **bp_locations;
531
532 /* Number of elements of BP_LOCATIONS.  */
533
534 static unsigned bp_locations_count;
535
536 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
537    ADDRESS for the current elements of BP_LOCATIONS which get a valid
538    result from bp_location_has_shadow.  You can use it for roughly
539    limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
540    an address you need to read.  */
541
542 static CORE_ADDR bp_locations_placed_address_before_address_max;
543
544 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
545    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
546    BP_LOCATIONS which get a valid result from bp_location_has_shadow.
547    You can use it for roughly limiting the subrange of BP_LOCATIONS to
548    scan for shadow bytes for an address you need to read.  */
549
550 static CORE_ADDR bp_locations_shadow_len_after_address_max;
551
552 /* The locations that no longer correspond to any breakpoint, unlinked
553    from the bp_locations array, but for which a hit may still be
554    reported by a target.  */
555 static std::vector<bp_location *> moribund_locations;
556
557 /* Number of last breakpoint made.  */
558
559 static int breakpoint_count;
560
561 /* The value of `breakpoint_count' before the last command that
562    created breakpoints.  If the last (break-like) command created more
563    than one breakpoint, then the difference between BREAKPOINT_COUNT
564    and PREV_BREAKPOINT_COUNT is more than one.  */
565 static int prev_breakpoint_count;
566
567 /* Number of last tracepoint made.  */
568
569 static int tracepoint_count;
570
571 static struct cmd_list_element *breakpoint_set_cmdlist;
572 static struct cmd_list_element *breakpoint_show_cmdlist;
573 struct cmd_list_element *save_cmdlist;
574
575 /* See declaration at breakpoint.h.  */
576
577 struct breakpoint *
578 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
579                     void *user_data)
580 {
581   struct breakpoint *b = NULL;
582
583   ALL_BREAKPOINTS (b)
584     {
585       if (func (b, user_data) != 0)
586         break;
587     }
588
589   return b;
590 }
591
592 /* Return whether a breakpoint is an active enabled breakpoint.  */
593 static int
594 breakpoint_enabled (struct breakpoint *b)
595 {
596   return (b->enable_state == bp_enabled);
597 }
598
599 /* Set breakpoint count to NUM.  */
600
601 static void
602 set_breakpoint_count (int num)
603 {
604   prev_breakpoint_count = breakpoint_count;
605   breakpoint_count = num;
606   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
607 }
608
609 /* Used by `start_rbreak_breakpoints' below, to record the current
610    breakpoint count before "rbreak" creates any breakpoint.  */
611 static int rbreak_start_breakpoint_count;
612
613 /* Called at the start an "rbreak" command to record the first
614    breakpoint made.  */
615
616 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
617 {
618   rbreak_start_breakpoint_count = breakpoint_count;
619 }
620
621 /* Called at the end of an "rbreak" command to record the last
622    breakpoint made.  */
623
624 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
625 {
626   prev_breakpoint_count = rbreak_start_breakpoint_count;
627 }
628
629 /* Used in run_command to zero the hit count when a new run starts.  */
630
631 void
632 clear_breakpoint_hit_counts (void)
633 {
634   struct breakpoint *b;
635
636   ALL_BREAKPOINTS (b)
637     b->hit_count = 0;
638 }
639
640 \f
641 /* Return the breakpoint with the specified number, or NULL
642    if the number does not refer to an existing breakpoint.  */
643
644 struct breakpoint *
645 get_breakpoint (int num)
646 {
647   struct breakpoint *b;
648
649   ALL_BREAKPOINTS (b)
650     if (b->number == num)
651       return b;
652   
653   return NULL;
654 }
655
656 \f
657
658 /* Mark locations as "conditions have changed" in case the target supports
659    evaluating conditions on its side.  */
660
661 static void
662 mark_breakpoint_modified (struct breakpoint *b)
663 {
664   struct bp_location *loc;
665
666   /* This is only meaningful if the target is
667      evaluating conditions and if the user has
668      opted for condition evaluation on the target's
669      side.  */
670   if (gdb_evaluates_breakpoint_condition_p ()
671       || !target_supports_evaluation_of_breakpoint_conditions ())
672     return;
673
674   if (!is_breakpoint (b))
675     return;
676
677   for (loc = b->loc; loc; loc = loc->next)
678     loc->condition_changed = condition_modified;
679 }
680
681 /* Mark location as "conditions have changed" in case the target supports
682    evaluating conditions on its side.  */
683
684 static void
685 mark_breakpoint_location_modified (struct bp_location *loc)
686 {
687   /* This is only meaningful if the target is
688      evaluating conditions and if the user has
689      opted for condition evaluation on the target's
690      side.  */
691   if (gdb_evaluates_breakpoint_condition_p ()
692       || !target_supports_evaluation_of_breakpoint_conditions ())
693
694     return;
695
696   if (!is_breakpoint (loc->owner))
697     return;
698
699   loc->condition_changed = condition_modified;
700 }
701
702 /* Sets the condition-evaluation mode using the static global
703    condition_evaluation_mode.  */
704
705 static void
706 set_condition_evaluation_mode (const char *args, int from_tty,
707                                struct cmd_list_element *c)
708 {
709   const char *old_mode, *new_mode;
710
711   if ((condition_evaluation_mode_1 == condition_evaluation_target)
712       && !target_supports_evaluation_of_breakpoint_conditions ())
713     {
714       condition_evaluation_mode_1 = condition_evaluation_mode;
715       warning (_("Target does not support breakpoint condition evaluation.\n"
716                  "Using host evaluation mode instead."));
717       return;
718     }
719
720   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
721   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
722
723   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
724      settings was "auto".  */
725   condition_evaluation_mode = condition_evaluation_mode_1;
726
727   /* Only update the mode if the user picked a different one.  */
728   if (new_mode != old_mode)
729     {
730       struct bp_location *loc, **loc_tmp;
731       /* If the user switched to a different evaluation mode, we
732          need to synch the changes with the target as follows:
733
734          "host" -> "target": Send all (valid) conditions to the target.
735          "target" -> "host": Remove all the conditions from the target.
736       */
737
738       if (new_mode == condition_evaluation_target)
739         {
740           /* Mark everything modified and synch conditions with the
741              target.  */
742           ALL_BP_LOCATIONS (loc, loc_tmp)
743             mark_breakpoint_location_modified (loc);
744         }
745       else
746         {
747           /* Manually mark non-duplicate locations to synch conditions
748              with the target.  We do this to remove all the conditions the
749              target knows about.  */
750           ALL_BP_LOCATIONS (loc, loc_tmp)
751             if (is_breakpoint (loc->owner) && loc->inserted)
752               loc->needs_update = 1;
753         }
754
755       /* Do the update.  */
756       update_global_location_list (UGLL_MAY_INSERT);
757     }
758
759   return;
760 }
761
762 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
763    what "auto" is translating to.  */
764
765 static void
766 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
767                                 struct cmd_list_element *c, const char *value)
768 {
769   if (condition_evaluation_mode == condition_evaluation_auto)
770     fprintf_filtered (file,
771                       _("Breakpoint condition evaluation "
772                         "mode is %s (currently %s).\n"),
773                       value,
774                       breakpoint_condition_evaluation_mode ());
775   else
776     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
777                       value);
778 }
779
780 /* A comparison function for bp_location AP and BP that is used by
781    bsearch.  This comparison function only cares about addresses, unlike
782    the more general bp_locations_compare function.  */
783
784 static int
785 bp_locations_compare_addrs (const void *ap, const void *bp)
786 {
787   const struct bp_location *a = *(const struct bp_location **) ap;
788   const struct bp_location *b = *(const struct bp_location **) bp;
789
790   if (a->address == b->address)
791     return 0;
792   else
793     return ((a->address > b->address) - (a->address < b->address));
794 }
795
796 /* Helper function to skip all bp_locations with addresses
797    less than ADDRESS.  It returns the first bp_location that
798    is greater than or equal to ADDRESS.  If none is found, just
799    return NULL.  */
800
801 static struct bp_location **
802 get_first_locp_gte_addr (CORE_ADDR address)
803 {
804   struct bp_location dummy_loc;
805   struct bp_location *dummy_locp = &dummy_loc;
806   struct bp_location **locp_found = NULL;
807
808   /* Initialize the dummy location's address field.  */
809   dummy_loc.address = address;
810
811   /* Find a close match to the first location at ADDRESS.  */
812   locp_found = ((struct bp_location **)
813                 bsearch (&dummy_locp, bp_locations, bp_locations_count,
814                          sizeof (struct bp_location **),
815                          bp_locations_compare_addrs));
816
817   /* Nothing was found, nothing left to do.  */
818   if (locp_found == NULL)
819     return NULL;
820
821   /* We may have found a location that is at ADDRESS but is not the first in the
822      location's list.  Go backwards (if possible) and locate the first one.  */
823   while ((locp_found - 1) >= bp_locations
824          && (*(locp_found - 1))->address == address)
825     locp_found--;
826
827   return locp_found;
828 }
829
830 void
831 set_breakpoint_condition (struct breakpoint *b, const char *exp,
832                           int from_tty)
833 {
834   xfree (b->cond_string);
835   b->cond_string = NULL;
836
837   if (is_watchpoint (b))
838     {
839       struct watchpoint *w = (struct watchpoint *) b;
840
841       w->cond_exp.reset ();
842     }
843   else
844     {
845       struct bp_location *loc;
846
847       for (loc = b->loc; loc; loc = loc->next)
848         {
849           loc->cond.reset ();
850
851           /* No need to free the condition agent expression
852              bytecode (if we have one).  We will handle this
853              when we go through update_global_location_list.  */
854         }
855     }
856
857   if (*exp == 0)
858     {
859       if (from_tty)
860         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
861     }
862   else
863     {
864       const char *arg = exp;
865
866       /* I don't know if it matters whether this is the string the user
867          typed in or the decompiled expression.  */
868       b->cond_string = xstrdup (arg);
869       b->condition_not_parsed = 0;
870
871       if (is_watchpoint (b))
872         {
873           struct watchpoint *w = (struct watchpoint *) b;
874
875           innermost_block_tracker tracker;
876           arg = exp;
877           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
878           if (*arg)
879             error (_("Junk at end of expression"));
880           w->cond_exp_valid_block = tracker.block ();
881         }
882       else
883         {
884           struct bp_location *loc;
885
886           for (loc = b->loc; loc; loc = loc->next)
887             {
888               arg = exp;
889               loc->cond =
890                 parse_exp_1 (&arg, loc->address,
891                              block_for_pc (loc->address), 0);
892               if (*arg)
893                 error (_("Junk at end of expression"));
894             }
895         }
896     }
897   mark_breakpoint_modified (b);
898
899   gdb::observers::breakpoint_modified.notify (b);
900 }
901
902 /* Completion for the "condition" command.  */
903
904 static void
905 condition_completer (struct cmd_list_element *cmd,
906                      completion_tracker &tracker,
907                      const char *text, const char *word)
908 {
909   const char *space;
910
911   text = skip_spaces (text);
912   space = skip_to_space (text);
913   if (*space == '\0')
914     {
915       int len;
916       struct breakpoint *b;
917
918       if (text[0] == '$')
919         {
920           /* We don't support completion of history indices.  */
921           if (!isdigit (text[1]))
922             complete_internalvar (tracker, &text[1]);
923           return;
924         }
925
926       /* We're completing the breakpoint number.  */
927       len = strlen (text);
928
929       ALL_BREAKPOINTS (b)
930         {
931           char number[50];
932
933           xsnprintf (number, sizeof (number), "%d", b->number);
934
935           if (strncmp (number, text, len) == 0)
936             tracker.add_completion (make_unique_xstrdup (number));
937         }
938
939       return;
940     }
941
942   /* We're completing the expression part.  */
943   text = skip_spaces (space);
944   expression_completer (cmd, tracker, text, word);
945 }
946
947 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
948
949 static void
950 condition_command (const char *arg, int from_tty)
951 {
952   struct breakpoint *b;
953   const char *p;
954   int bnum;
955
956   if (arg == 0)
957     error_no_arg (_("breakpoint number"));
958
959   p = arg;
960   bnum = get_number (&p);
961   if (bnum == 0)
962     error (_("Bad breakpoint argument: '%s'"), arg);
963
964   ALL_BREAKPOINTS (b)
965     if (b->number == bnum)
966       {
967         /* Check if this breakpoint has a "stop" method implemented in an
968            extension language.  This method and conditions entered into GDB
969            from the CLI are mutually exclusive.  */
970         const struct extension_language_defn *extlang
971           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
972
973         if (extlang != NULL)
974           {
975             error (_("Only one stop condition allowed.  There is currently"
976                      " a %s stop condition defined for this breakpoint."),
977                    ext_lang_capitalized_name (extlang));
978           }
979         set_breakpoint_condition (b, p, from_tty);
980
981         if (is_breakpoint (b))
982           update_global_location_list (UGLL_MAY_INSERT);
983
984         return;
985       }
986
987   error (_("No breakpoint number %d."), bnum);
988 }
989
990 /* Check that COMMAND do not contain commands that are suitable
991    only for tracepoints and not suitable for ordinary breakpoints.
992    Throw if any such commands is found.  */
993
994 static void
995 check_no_tracepoint_commands (struct command_line *commands)
996 {
997   struct command_line *c;
998
999   for (c = commands; c; c = c->next)
1000     {
1001       if (c->control_type == while_stepping_control)
1002         error (_("The 'while-stepping' command can "
1003                  "only be used for tracepoints"));
1004
1005       check_no_tracepoint_commands (c->body_list_0.get ());
1006       check_no_tracepoint_commands (c->body_list_1.get ());
1007
1008       /* Not that command parsing removes leading whitespace and comment
1009          lines and also empty lines.  So, we only need to check for
1010          command directly.  */
1011       if (strstr (c->line, "collect ") == c->line)
1012         error (_("The 'collect' command can only be used for tracepoints"));
1013
1014       if (strstr (c->line, "teval ") == c->line)
1015         error (_("The 'teval' command can only be used for tracepoints"));
1016     }
1017 }
1018
1019 struct longjmp_breakpoint : public breakpoint
1020 {
1021   ~longjmp_breakpoint () override;
1022 };
1023
1024 /* Encapsulate tests for different types of tracepoints.  */
1025
1026 static bool
1027 is_tracepoint_type (bptype type)
1028 {
1029   return (type == bp_tracepoint
1030           || type == bp_fast_tracepoint
1031           || type == bp_static_tracepoint);
1032 }
1033
1034 static bool
1035 is_longjmp_type (bptype type)
1036 {
1037   return type == bp_longjmp || type == bp_exception;
1038 }
1039
1040 int
1041 is_tracepoint (const struct breakpoint *b)
1042 {
1043   return is_tracepoint_type (b->type);
1044 }
1045
1046 /* Factory function to create an appropriate instance of breakpoint given
1047    TYPE.  */
1048
1049 static std::unique_ptr<breakpoint>
1050 new_breakpoint_from_type (bptype type)
1051 {
1052   breakpoint *b;
1053
1054   if (is_tracepoint_type (type))
1055     b = new tracepoint ();
1056   else if (is_longjmp_type (type))
1057     b = new longjmp_breakpoint ();
1058   else
1059     b = new breakpoint ();
1060
1061   return std::unique_ptr<breakpoint> (b);
1062 }
1063
1064 /* A helper function that validates that COMMANDS are valid for a
1065    breakpoint.  This function will throw an exception if a problem is
1066    found.  */
1067
1068 static void
1069 validate_commands_for_breakpoint (struct breakpoint *b,
1070                                   struct command_line *commands)
1071 {
1072   if (is_tracepoint (b))
1073     {
1074       struct tracepoint *t = (struct tracepoint *) b;
1075       struct command_line *c;
1076       struct command_line *while_stepping = 0;
1077
1078       /* Reset the while-stepping step count.  The previous commands
1079          might have included a while-stepping action, while the new
1080          ones might not.  */
1081       t->step_count = 0;
1082
1083       /* We need to verify that each top-level element of commands is
1084          valid for tracepoints, that there's at most one
1085          while-stepping element, and that the while-stepping's body
1086          has valid tracing commands excluding nested while-stepping.
1087          We also need to validate the tracepoint action line in the
1088          context of the tracepoint --- validate_actionline actually
1089          has side effects, like setting the tracepoint's
1090          while-stepping STEP_COUNT, in addition to checking if the
1091          collect/teval actions parse and make sense in the
1092          tracepoint's context.  */
1093       for (c = commands; c; c = c->next)
1094         {
1095           if (c->control_type == while_stepping_control)
1096             {
1097               if (b->type == bp_fast_tracepoint)
1098                 error (_("The 'while-stepping' command "
1099                          "cannot be used for fast tracepoint"));
1100               else if (b->type == bp_static_tracepoint)
1101                 error (_("The 'while-stepping' command "
1102                          "cannot be used for static tracepoint"));
1103
1104               if (while_stepping)
1105                 error (_("The 'while-stepping' command "
1106                          "can be used only once"));
1107               else
1108                 while_stepping = c;
1109             }
1110
1111           validate_actionline (c->line, b);
1112         }
1113       if (while_stepping)
1114         {
1115           struct command_line *c2;
1116
1117           gdb_assert (while_stepping->body_list_1 == nullptr);
1118           c2 = while_stepping->body_list_0.get ();
1119           for (; c2; c2 = c2->next)
1120             {
1121               if (c2->control_type == while_stepping_control)
1122                 error (_("The 'while-stepping' command cannot be nested"));
1123             }
1124         }
1125     }
1126   else
1127     {
1128       check_no_tracepoint_commands (commands);
1129     }
1130 }
1131
1132 /* Return a vector of all the static tracepoints set at ADDR.  The
1133    caller is responsible for releasing the vector.  */
1134
1135 std::vector<breakpoint *>
1136 static_tracepoints_here (CORE_ADDR addr)
1137 {
1138   struct breakpoint *b;
1139   std::vector<breakpoint *> found;
1140   struct bp_location *loc;
1141
1142   ALL_BREAKPOINTS (b)
1143     if (b->type == bp_static_tracepoint)
1144       {
1145         for (loc = b->loc; loc; loc = loc->next)
1146           if (loc->address == addr)
1147             found.push_back (b);
1148       }
1149
1150   return found;
1151 }
1152
1153 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1154    validate that only allowed commands are included.  */
1155
1156 void
1157 breakpoint_set_commands (struct breakpoint *b, 
1158                          counted_command_line &&commands)
1159 {
1160   validate_commands_for_breakpoint (b, commands.get ());
1161
1162   b->commands = std::move (commands);
1163   gdb::observers::breakpoint_modified.notify (b);
1164 }
1165
1166 /* Set the internal `silent' flag on the breakpoint.  Note that this
1167    is not the same as the "silent" that may appear in the breakpoint's
1168    commands.  */
1169
1170 void
1171 breakpoint_set_silent (struct breakpoint *b, int silent)
1172 {
1173   int old_silent = b->silent;
1174
1175   b->silent = silent;
1176   if (old_silent != silent)
1177     gdb::observers::breakpoint_modified.notify (b);
1178 }
1179
1180 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1181    breakpoint work for any thread.  */
1182
1183 void
1184 breakpoint_set_thread (struct breakpoint *b, int thread)
1185 {
1186   int old_thread = b->thread;
1187
1188   b->thread = thread;
1189   if (old_thread != thread)
1190     gdb::observers::breakpoint_modified.notify (b);
1191 }
1192
1193 /* Set the task for this breakpoint.  If TASK is 0, make the
1194    breakpoint work for any task.  */
1195
1196 void
1197 breakpoint_set_task (struct breakpoint *b, int task)
1198 {
1199   int old_task = b->task;
1200
1201   b->task = task;
1202   if (old_task != task)
1203     gdb::observers::breakpoint_modified.notify (b);
1204 }
1205
1206 static void
1207 commands_command_1 (const char *arg, int from_tty,
1208                     struct command_line *control)
1209 {
1210   counted_command_line cmd;
1211   /* cmd_read will be true once we have read cmd.  Note that cmd might still be
1212      NULL after the call to read_command_lines if the user provides an empty
1213      list of command by just typing "end".  */
1214   bool cmd_read = false;
1215
1216   std::string new_arg;
1217
1218   if (arg == NULL || !*arg)
1219     {
1220       if (breakpoint_count - prev_breakpoint_count > 1)
1221         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1222                                  breakpoint_count);
1223       else if (breakpoint_count > 0)
1224         new_arg = string_printf ("%d", breakpoint_count);
1225       arg = new_arg.c_str ();
1226     }
1227
1228   map_breakpoint_numbers
1229     (arg, [&] (breakpoint *b)
1230      {
1231        if (!cmd_read)
1232          {
1233            gdb_assert (cmd == NULL);
1234            if (control != NULL)
1235              cmd = control->body_list_0;
1236            else
1237              {
1238                std::string str
1239                  = string_printf (_("Type commands for breakpoint(s) "
1240                                     "%s, one per line."),
1241                                   arg);
1242
1243                auto do_validate = [=] (const char *line)
1244                                   {
1245                                     validate_actionline (line, b);
1246                                   };
1247                gdb::function_view<void (const char *)> validator;
1248                if (is_tracepoint (b))
1249                  validator = do_validate;
1250
1251                cmd = read_command_lines (str.c_str (), from_tty, 1, validator);
1252              }
1253            cmd_read = true;
1254          }
1255
1256        /* If a breakpoint was on the list more than once, we don't need to
1257           do anything.  */
1258        if (b->commands != cmd)
1259          {
1260            validate_commands_for_breakpoint (b, cmd.get ());
1261            b->commands = cmd;
1262            gdb::observers::breakpoint_modified.notify (b);
1263          }
1264      });
1265 }
1266
1267 static void
1268 commands_command (const char *arg, int from_tty)
1269 {
1270   commands_command_1 (arg, from_tty, NULL);
1271 }
1272
1273 /* Like commands_command, but instead of reading the commands from
1274    input stream, takes them from an already parsed command structure.
1275
1276    This is used by cli-script.c to DTRT with breakpoint commands
1277    that are part of if and while bodies.  */
1278 enum command_control_type
1279 commands_from_control_command (const char *arg, struct command_line *cmd)
1280 {
1281   commands_command_1 (arg, 0, cmd);
1282   return simple_control;
1283 }
1284
1285 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1286
1287 static int
1288 bp_location_has_shadow (struct bp_location *bl)
1289 {
1290   if (bl->loc_type != bp_loc_software_breakpoint)
1291     return 0;
1292   if (!bl->inserted)
1293     return 0;
1294   if (bl->target_info.shadow_len == 0)
1295     /* BL isn't valid, or doesn't shadow memory.  */
1296     return 0;
1297   return 1;
1298 }
1299
1300 /* Update BUF, which is LEN bytes read from the target address
1301    MEMADDR, by replacing a memory breakpoint with its shadowed
1302    contents.
1303
1304    If READBUF is not NULL, this buffer must not overlap with the of
1305    the breakpoint location's shadow_contents buffer.  Otherwise, a
1306    failed assertion internal error will be raised.  */
1307
1308 static void
1309 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1310                             const gdb_byte *writebuf_org,
1311                             ULONGEST memaddr, LONGEST len,
1312                             struct bp_target_info *target_info,
1313                             struct gdbarch *gdbarch)
1314 {
1315   /* Now do full processing of the found relevant range of elements.  */
1316   CORE_ADDR bp_addr = 0;
1317   int bp_size = 0;
1318   int bptoffset = 0;
1319
1320   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1321                                  current_program_space->aspace, 0))
1322     {
1323       /* The breakpoint is inserted in a different address space.  */
1324       return;
1325     }
1326
1327   /* Addresses and length of the part of the breakpoint that
1328      we need to copy.  */
1329   bp_addr = target_info->placed_address;
1330   bp_size = target_info->shadow_len;
1331
1332   if (bp_addr + bp_size <= memaddr)
1333     {
1334       /* The breakpoint is entirely before the chunk of memory we are
1335          reading.  */
1336       return;
1337     }
1338
1339   if (bp_addr >= memaddr + len)
1340     {
1341       /* The breakpoint is entirely after the chunk of memory we are
1342          reading.  */
1343       return;
1344     }
1345
1346   /* Offset within shadow_contents.  */
1347   if (bp_addr < memaddr)
1348     {
1349       /* Only copy the second part of the breakpoint.  */
1350       bp_size -= memaddr - bp_addr;
1351       bptoffset = memaddr - bp_addr;
1352       bp_addr = memaddr;
1353     }
1354
1355   if (bp_addr + bp_size > memaddr + len)
1356     {
1357       /* Only copy the first part of the breakpoint.  */
1358       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1359     }
1360
1361   if (readbuf != NULL)
1362     {
1363       /* Verify that the readbuf buffer does not overlap with the
1364          shadow_contents buffer.  */
1365       gdb_assert (target_info->shadow_contents >= readbuf + len
1366                   || readbuf >= (target_info->shadow_contents
1367                                  + target_info->shadow_len));
1368
1369       /* Update the read buffer with this inserted breakpoint's
1370          shadow.  */
1371       memcpy (readbuf + bp_addr - memaddr,
1372               target_info->shadow_contents + bptoffset, bp_size);
1373     }
1374   else
1375     {
1376       const unsigned char *bp;
1377       CORE_ADDR addr = target_info->reqstd_address;
1378       int placed_size;
1379
1380       /* Update the shadow with what we want to write to memory.  */
1381       memcpy (target_info->shadow_contents + bptoffset,
1382               writebuf_org + bp_addr - memaddr, bp_size);
1383
1384       /* Determine appropriate breakpoint contents and size for this
1385          address.  */
1386       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1387
1388       /* Update the final write buffer with this inserted
1389          breakpoint's INSN.  */
1390       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1391     }
1392 }
1393
1394 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1395    by replacing any memory breakpoints with their shadowed contents.
1396
1397    If READBUF is not NULL, this buffer must not overlap with any of
1398    the breakpoint location's shadow_contents buffers.  Otherwise,
1399    a failed assertion internal error will be raised.
1400
1401    The range of shadowed area by each bp_location is:
1402      bl->address - bp_locations_placed_address_before_address_max
1403      up to bl->address + bp_locations_shadow_len_after_address_max
1404    The range we were requested to resolve shadows for is:
1405      memaddr ... memaddr + len
1406    Thus the safe cutoff boundaries for performance optimization are
1407      memaddr + len <= (bl->address
1408                        - bp_locations_placed_address_before_address_max)
1409    and:
1410      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1411
1412 void
1413 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1414                         const gdb_byte *writebuf_org,
1415                         ULONGEST memaddr, LONGEST len)
1416 {
1417   /* Left boundary, right boundary and median element of our binary
1418      search.  */
1419   unsigned bc_l, bc_r, bc;
1420
1421   /* Find BC_L which is a leftmost element which may affect BUF
1422      content.  It is safe to report lower value but a failure to
1423      report higher one.  */
1424
1425   bc_l = 0;
1426   bc_r = bp_locations_count;
1427   while (bc_l + 1 < bc_r)
1428     {
1429       struct bp_location *bl;
1430
1431       bc = (bc_l + bc_r) / 2;
1432       bl = bp_locations[bc];
1433
1434       /* Check first BL->ADDRESS will not overflow due to the added
1435          constant.  Then advance the left boundary only if we are sure
1436          the BC element can in no way affect the BUF content (MEMADDR
1437          to MEMADDR + LEN range).
1438
1439          Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1440          offset so that we cannot miss a breakpoint with its shadow
1441          range tail still reaching MEMADDR.  */
1442
1443       if ((bl->address + bp_locations_shadow_len_after_address_max
1444            >= bl->address)
1445           && (bl->address + bp_locations_shadow_len_after_address_max
1446               <= memaddr))
1447         bc_l = bc;
1448       else
1449         bc_r = bc;
1450     }
1451
1452   /* Due to the binary search above, we need to make sure we pick the
1453      first location that's at BC_L's address.  E.g., if there are
1454      multiple locations at the same address, BC_L may end up pointing
1455      at a duplicate location, and miss the "master"/"inserted"
1456      location.  Say, given locations L1, L2 and L3 at addresses A and
1457      B:
1458
1459       L1@A, L2@A, L3@B, ...
1460
1461      BC_L could end up pointing at location L2, while the "master"
1462      location could be L1.  Since the `loc->inserted' flag is only set
1463      on "master" locations, we'd forget to restore the shadow of L1
1464      and L2.  */
1465   while (bc_l > 0
1466          && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1467     bc_l--;
1468
1469   /* Now do full processing of the found relevant range of elements.  */
1470
1471   for (bc = bc_l; bc < bp_locations_count; bc++)
1472   {
1473     struct bp_location *bl = bp_locations[bc];
1474
1475     /* bp_location array has BL->OWNER always non-NULL.  */
1476     if (bl->owner->type == bp_none)
1477       warning (_("reading through apparently deleted breakpoint #%d?"),
1478                bl->owner->number);
1479
1480     /* Performance optimization: any further element can no longer affect BUF
1481        content.  */
1482
1483     if (bl->address >= bp_locations_placed_address_before_address_max
1484         && memaddr + len <= (bl->address
1485                              - bp_locations_placed_address_before_address_max))
1486       break;
1487
1488     if (!bp_location_has_shadow (bl))
1489       continue;
1490
1491     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1492                                 memaddr, len, &bl->target_info, bl->gdbarch);
1493   }
1494 }
1495
1496 \f
1497
1498 /* Return true if BPT is either a software breakpoint or a hardware
1499    breakpoint.  */
1500
1501 int
1502 is_breakpoint (const struct breakpoint *bpt)
1503 {
1504   return (bpt->type == bp_breakpoint
1505           || bpt->type == bp_hardware_breakpoint
1506           || bpt->type == bp_dprintf);
1507 }
1508
1509 /* Return true if BPT is of any hardware watchpoint kind.  */
1510
1511 static int
1512 is_hardware_watchpoint (const struct breakpoint *bpt)
1513 {
1514   return (bpt->type == bp_hardware_watchpoint
1515           || bpt->type == bp_read_watchpoint
1516           || bpt->type == bp_access_watchpoint);
1517 }
1518
1519 /* Return true if BPT is of any watchpoint kind, hardware or
1520    software.  */
1521
1522 int
1523 is_watchpoint (const struct breakpoint *bpt)
1524 {
1525   return (is_hardware_watchpoint (bpt)
1526           || bpt->type == bp_watchpoint);
1527 }
1528
1529 /* Returns true if the current thread and its running state are safe
1530    to evaluate or update watchpoint B.  Watchpoints on local
1531    expressions need to be evaluated in the context of the thread that
1532    was current when the watchpoint was created, and, that thread needs
1533    to be stopped to be able to select the correct frame context.
1534    Watchpoints on global expressions can be evaluated on any thread,
1535    and in any state.  It is presently left to the target allowing
1536    memory accesses when threads are running.  */
1537
1538 static int
1539 watchpoint_in_thread_scope (struct watchpoint *b)
1540 {
1541   return (b->pspace == current_program_space
1542           && (b->watchpoint_thread == null_ptid
1543               || (inferior_ptid == b->watchpoint_thread
1544                   && !inferior_thread ()->executing)));
1545 }
1546
1547 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1548    associated bp_watchpoint_scope breakpoint.  */
1549
1550 static void
1551 watchpoint_del_at_next_stop (struct watchpoint *w)
1552 {
1553   if (w->related_breakpoint != w)
1554     {
1555       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1556       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1557       w->related_breakpoint->disposition = disp_del_at_next_stop;
1558       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1559       w->related_breakpoint = w;
1560     }
1561   w->disposition = disp_del_at_next_stop;
1562 }
1563
1564 /* Extract a bitfield value from value VAL using the bit parameters contained in
1565    watchpoint W.  */
1566
1567 static struct value *
1568 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1569 {
1570   struct value *bit_val;
1571
1572   if (val == NULL)
1573     return NULL;
1574
1575   bit_val = allocate_value (value_type (val));
1576
1577   unpack_value_bitfield (bit_val,
1578                          w->val_bitpos,
1579                          w->val_bitsize,
1580                          value_contents_for_printing (val),
1581                          value_offset (val),
1582                          val);
1583
1584   return bit_val;
1585 }
1586
1587 /* Allocate a dummy location and add it to B, which must be a software
1588    watchpoint.  This is required because even if a software watchpoint
1589    is not watching any memory, bpstat_stop_status requires a location
1590    to be able to report stops.  */
1591
1592 static void
1593 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1594                                             struct program_space *pspace)
1595 {
1596   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1597
1598   b->loc = allocate_bp_location (b);
1599   b->loc->pspace = pspace;
1600   b->loc->address = -1;
1601   b->loc->length = -1;
1602 }
1603
1604 /* Returns true if B is a software watchpoint that is not watching any
1605    memory (e.g., "watch $pc").  */
1606
1607 static int
1608 is_no_memory_software_watchpoint (struct breakpoint *b)
1609 {
1610   return (b->type == bp_watchpoint
1611           && b->loc != NULL
1612           && b->loc->next == NULL
1613           && b->loc->address == -1
1614           && b->loc->length == -1);
1615 }
1616
1617 /* Assuming that B is a watchpoint:
1618    - Reparse watchpoint expression, if REPARSE is non-zero
1619    - Evaluate expression and store the result in B->val
1620    - Evaluate the condition if there is one, and store the result
1621      in b->loc->cond.
1622    - Update the list of values that must be watched in B->loc.
1623
1624    If the watchpoint disposition is disp_del_at_next_stop, then do
1625    nothing.  If this is local watchpoint that is out of scope, delete
1626    it.
1627
1628    Even with `set breakpoint always-inserted on' the watchpoints are
1629    removed + inserted on each stop here.  Normal breakpoints must
1630    never be removed because they might be missed by a running thread
1631    when debugging in non-stop mode.  On the other hand, hardware
1632    watchpoints (is_hardware_watchpoint; processed here) are specific
1633    to each LWP since they are stored in each LWP's hardware debug
1634    registers.  Therefore, such LWP must be stopped first in order to
1635    be able to modify its hardware watchpoints.
1636
1637    Hardware watchpoints must be reset exactly once after being
1638    presented to the user.  It cannot be done sooner, because it would
1639    reset the data used to present the watchpoint hit to the user.  And
1640    it must not be done later because it could display the same single
1641    watchpoint hit during multiple GDB stops.  Note that the latter is
1642    relevant only to the hardware watchpoint types bp_read_watchpoint
1643    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1644    not user-visible - its hit is suppressed if the memory content has
1645    not changed.
1646
1647    The following constraints influence the location where we can reset
1648    hardware watchpoints:
1649
1650    * target_stopped_by_watchpoint and target_stopped_data_address are
1651      called several times when GDB stops.
1652
1653    [linux] 
1654    * Multiple hardware watchpoints can be hit at the same time,
1655      causing GDB to stop.  GDB only presents one hardware watchpoint
1656      hit at a time as the reason for stopping, and all the other hits
1657      are presented later, one after the other, each time the user
1658      requests the execution to be resumed.  Execution is not resumed
1659      for the threads still having pending hit event stored in
1660      LWP_INFO->STATUS.  While the watchpoint is already removed from
1661      the inferior on the first stop the thread hit event is kept being
1662      reported from its cached value by linux_nat_stopped_data_address
1663      until the real thread resume happens after the watchpoint gets
1664      presented and thus its LWP_INFO->STATUS gets reset.
1665
1666    Therefore the hardware watchpoint hit can get safely reset on the
1667    watchpoint removal from inferior.  */
1668
1669 static void
1670 update_watchpoint (struct watchpoint *b, int reparse)
1671 {
1672   int within_current_scope;
1673   struct frame_id saved_frame_id;
1674   int frame_saved;
1675
1676   /* If this is a local watchpoint, we only want to check if the
1677      watchpoint frame is in scope if the current thread is the thread
1678      that was used to create the watchpoint.  */
1679   if (!watchpoint_in_thread_scope (b))
1680     return;
1681
1682   if (b->disposition == disp_del_at_next_stop)
1683     return;
1684  
1685   frame_saved = 0;
1686
1687   /* Determine if the watchpoint is within scope.  */
1688   if (b->exp_valid_block == NULL)
1689     within_current_scope = 1;
1690   else
1691     {
1692       struct frame_info *fi = get_current_frame ();
1693       struct gdbarch *frame_arch = get_frame_arch (fi);
1694       CORE_ADDR frame_pc = get_frame_pc (fi);
1695
1696       /* If we're at a point where the stack has been destroyed
1697          (e.g. in a function epilogue), unwinding may not work
1698          properly. Do not attempt to recreate locations at this
1699          point.  See similar comments in watchpoint_check.  */
1700       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1701         return;
1702
1703       /* Save the current frame's ID so we can restore it after
1704          evaluating the watchpoint expression on its own frame.  */
1705       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1706          took a frame parameter, so that we didn't have to change the
1707          selected frame.  */
1708       frame_saved = 1;
1709       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1710
1711       fi = frame_find_by_id (b->watchpoint_frame);
1712       within_current_scope = (fi != NULL);
1713       if (within_current_scope)
1714         select_frame (fi);
1715     }
1716
1717   /* We don't free locations.  They are stored in the bp_location array
1718      and update_global_location_list will eventually delete them and
1719      remove breakpoints if needed.  */
1720   b->loc = NULL;
1721
1722   if (within_current_scope && reparse)
1723     {
1724       const char *s;
1725
1726       b->exp.reset ();
1727       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1728       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1729       /* If the meaning of expression itself changed, the old value is
1730          no longer relevant.  We don't want to report a watchpoint hit
1731          to the user when the old value and the new value may actually
1732          be completely different objects.  */
1733       b->val = NULL;
1734       b->val_valid = 0;
1735
1736       /* Note that unlike with breakpoints, the watchpoint's condition
1737          expression is stored in the breakpoint object, not in the
1738          locations (re)created below.  */
1739       if (b->cond_string != NULL)
1740         {
1741           b->cond_exp.reset ();
1742
1743           s = b->cond_string;
1744           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1745         }
1746     }
1747
1748   /* If we failed to parse the expression, for example because
1749      it refers to a global variable in a not-yet-loaded shared library,
1750      don't try to insert watchpoint.  We don't automatically delete
1751      such watchpoint, though, since failure to parse expression
1752      is different from out-of-scope watchpoint.  */
1753   if (!target_has_execution)
1754     {
1755       /* Without execution, memory can't change.  No use to try and
1756          set watchpoint locations.  The watchpoint will be reset when
1757          the target gains execution, through breakpoint_re_set.  */
1758       if (!can_use_hw_watchpoints)
1759         {
1760           if (b->ops->works_in_software_mode (b))
1761             b->type = bp_watchpoint;
1762           else
1763             error (_("Can't set read/access watchpoint when "
1764                      "hardware watchpoints are disabled."));
1765         }
1766     }
1767   else if (within_current_scope && b->exp)
1768     {
1769       int pc = 0;
1770       std::vector<value_ref_ptr> val_chain;
1771       struct value *v, *result;
1772       struct program_space *frame_pspace;
1773
1774       fetch_subexp_value (b->exp.get (), &pc, &v, &result, &val_chain, 0);
1775
1776       /* Avoid setting b->val if it's already set.  The meaning of
1777          b->val is 'the last value' user saw, and we should update
1778          it only if we reported that last value to user.  As it
1779          happens, the code that reports it updates b->val directly.
1780          We don't keep track of the memory value for masked
1781          watchpoints.  */
1782       if (!b->val_valid && !is_masked_watchpoint (b))
1783         {
1784           if (b->val_bitsize != 0)
1785             v = extract_bitfield_from_watchpoint_value (b, v);
1786           b->val = release_value (v);
1787           b->val_valid = 1;
1788         }
1789
1790       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1791
1792       /* Look at each value on the value chain.  */
1793       gdb_assert (!val_chain.empty ());
1794       for (const value_ref_ptr &iter : val_chain)
1795         {
1796           v = iter.get ();
1797
1798           /* If it's a memory location, and GDB actually needed
1799              its contents to evaluate the expression, then we
1800              must watch it.  If the first value returned is
1801              still lazy, that means an error occurred reading it;
1802              watch it anyway in case it becomes readable.  */
1803           if (VALUE_LVAL (v) == lval_memory
1804               && (v == val_chain[0] || ! value_lazy (v)))
1805             {
1806               struct type *vtype = check_typedef (value_type (v));
1807
1808               /* We only watch structs and arrays if user asked
1809                  for it explicitly, never if they just happen to
1810                  appear in the middle of some value chain.  */
1811               if (v == result
1812                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1813                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1814                 {
1815                   CORE_ADDR addr;
1816                   enum target_hw_bp_type type;
1817                   struct bp_location *loc, **tmp;
1818                   int bitpos = 0, bitsize = 0;
1819
1820                   if (value_bitsize (v) != 0)
1821                     {
1822                       /* Extract the bit parameters out from the bitfield
1823                          sub-expression.  */
1824                       bitpos = value_bitpos (v);
1825                       bitsize = value_bitsize (v);
1826                     }
1827                   else if (v == result && b->val_bitsize != 0)
1828                     {
1829                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1830                         lvalue whose bit parameters are saved in the fields
1831                         VAL_BITPOS and VAL_BITSIZE.  */
1832                       bitpos = b->val_bitpos;
1833                       bitsize = b->val_bitsize;
1834                     }
1835
1836                   addr = value_address (v);
1837                   if (bitsize != 0)
1838                     {
1839                       /* Skip the bytes that don't contain the bitfield.  */
1840                       addr += bitpos / 8;
1841                     }
1842
1843                   type = hw_write;
1844                   if (b->type == bp_read_watchpoint)
1845                     type = hw_read;
1846                   else if (b->type == bp_access_watchpoint)
1847                     type = hw_access;
1848
1849                   loc = allocate_bp_location (b);
1850                   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
1851                     ;
1852                   *tmp = loc;
1853                   loc->gdbarch = get_type_arch (value_type (v));
1854
1855                   loc->pspace = frame_pspace;
1856                   loc->address = address_significant (loc->gdbarch, addr);
1857
1858                   if (bitsize != 0)
1859                     {
1860                       /* Just cover the bytes that make up the bitfield.  */
1861                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
1862                     }
1863                   else
1864                     loc->length = TYPE_LENGTH (value_type (v));
1865
1866                   loc->watchpoint_type = type;
1867                 }
1868             }
1869         }
1870
1871       /* Change the type of breakpoint between hardware assisted or
1872          an ordinary watchpoint depending on the hardware support
1873          and free hardware slots.  REPARSE is set when the inferior
1874          is started.  */
1875       if (reparse)
1876         {
1877           int reg_cnt;
1878           enum bp_loc_type loc_type;
1879           struct bp_location *bl;
1880
1881           reg_cnt = can_use_hardware_watchpoint (val_chain);
1882
1883           if (reg_cnt)
1884             {
1885               int i, target_resources_ok, other_type_used;
1886               enum bptype type;
1887
1888               /* Use an exact watchpoint when there's only one memory region to be
1889                  watched, and only one debug register is needed to watch it.  */
1890               b->exact = target_exact_watchpoints && reg_cnt == 1;
1891
1892               /* We need to determine how many resources are already
1893                  used for all other hardware watchpoints plus this one
1894                  to see if we still have enough resources to also fit
1895                  this watchpoint in as well.  */
1896
1897               /* If this is a software watchpoint, we try to turn it
1898                  to a hardware one -- count resources as if B was of
1899                  hardware watchpoint type.  */
1900               type = b->type;
1901               if (type == bp_watchpoint)
1902                 type = bp_hardware_watchpoint;
1903
1904               /* This watchpoint may or may not have been placed on
1905                  the list yet at this point (it won't be in the list
1906                  if we're trying to create it for the first time,
1907                  through watch_command), so always account for it
1908                  manually.  */
1909
1910               /* Count resources used by all watchpoints except B.  */
1911               i = hw_watchpoint_used_count_others (b, type, &other_type_used);
1912
1913               /* Add in the resources needed for B.  */
1914               i += hw_watchpoint_use_count (b);
1915
1916               target_resources_ok
1917                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1918               if (target_resources_ok <= 0)
1919                 {
1920                   int sw_mode = b->ops->works_in_software_mode (b);
1921
1922                   if (target_resources_ok == 0 && !sw_mode)
1923                     error (_("Target does not support this type of "
1924                              "hardware watchpoint."));
1925                   else if (target_resources_ok < 0 && !sw_mode)
1926                     error (_("There are not enough available hardware "
1927                              "resources for this watchpoint."));
1928
1929                   /* Downgrade to software watchpoint.  */
1930                   b->type = bp_watchpoint;
1931                 }
1932               else
1933                 {
1934                   /* If this was a software watchpoint, we've just
1935                      found we have enough resources to turn it to a
1936                      hardware watchpoint.  Otherwise, this is a
1937                      nop.  */
1938                   b->type = type;
1939                 }
1940             }
1941           else if (!b->ops->works_in_software_mode (b))
1942             {
1943               if (!can_use_hw_watchpoints)
1944                 error (_("Can't set read/access watchpoint when "
1945                          "hardware watchpoints are disabled."));
1946               else
1947                 error (_("Expression cannot be implemented with "
1948                          "read/access watchpoint."));
1949             }
1950           else
1951             b->type = bp_watchpoint;
1952
1953           loc_type = (b->type == bp_watchpoint? bp_loc_other
1954                       : bp_loc_hardware_watchpoint);
1955           for (bl = b->loc; bl; bl = bl->next)
1956             bl->loc_type = loc_type;
1957         }
1958
1959       /* If a software watchpoint is not watching any memory, then the
1960          above left it without any location set up.  But,
1961          bpstat_stop_status requires a location to be able to report
1962          stops, so make sure there's at least a dummy one.  */
1963       if (b->type == bp_watchpoint && b->loc == NULL)
1964         software_watchpoint_add_no_memory_location (b, frame_pspace);
1965     }
1966   else if (!within_current_scope)
1967     {
1968       printf_filtered (_("\
1969 Watchpoint %d deleted because the program has left the block\n\
1970 in which its expression is valid.\n"),
1971                        b->number);
1972       watchpoint_del_at_next_stop (b);
1973     }
1974
1975   /* Restore the selected frame.  */
1976   if (frame_saved)
1977     select_frame (frame_find_by_id (saved_frame_id));
1978 }
1979
1980
1981 /* Returns 1 iff breakpoint location should be
1982    inserted in the inferior.  We don't differentiate the type of BL's owner
1983    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1984    breakpoint_ops is not defined, because in insert_bp_location,
1985    tracepoint's insert_location will not be called.  */
1986 static int
1987 should_be_inserted (struct bp_location *bl)
1988 {
1989   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
1990     return 0;
1991
1992   if (bl->owner->disposition == disp_del_at_next_stop)
1993     return 0;
1994
1995   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
1996     return 0;
1997
1998   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
1999     return 0;
2000
2001   /* This is set for example, when we're attached to the parent of a
2002      vfork, and have detached from the child.  The child is running
2003      free, and we expect it to do an exec or exit, at which point the
2004      OS makes the parent schedulable again (and the target reports
2005      that the vfork is done).  Until the child is done with the shared
2006      memory region, do not insert breakpoints in the parent, otherwise
2007      the child could still trip on the parent's breakpoints.  Since
2008      the parent is blocked anyway, it won't miss any breakpoint.  */
2009   if (bl->pspace->breakpoints_not_allowed)
2010     return 0;
2011
2012   /* Don't insert a breakpoint if we're trying to step past its
2013      location, except if the breakpoint is a single-step breakpoint,
2014      and the breakpoint's thread is the thread which is stepping past
2015      a breakpoint.  */
2016   if ((bl->loc_type == bp_loc_software_breakpoint
2017        || bl->loc_type == bp_loc_hardware_breakpoint)
2018       && stepping_past_instruction_at (bl->pspace->aspace,
2019                                        bl->address)
2020       /* The single-step breakpoint may be inserted at the location
2021          we're trying to step if the instruction branches to itself.
2022          However, the instruction won't be executed at all and it may
2023          break the semantics of the instruction, for example, the
2024          instruction is a conditional branch or updates some flags.
2025          We can't fix it unless GDB is able to emulate the instruction
2026          or switch to displaced stepping.  */
2027       && !(bl->owner->type == bp_single_step
2028            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2029     {
2030       if (debug_infrun)
2031         {
2032           fprintf_unfiltered (gdb_stdlog,
2033                               "infrun: skipping breakpoint: "
2034                               "stepping past insn at: %s\n",
2035                               paddress (bl->gdbarch, bl->address));
2036         }
2037       return 0;
2038     }
2039
2040   /* Don't insert watchpoints if we're trying to step past the
2041      instruction that triggered one.  */
2042   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2043       && stepping_past_nonsteppable_watchpoint ())
2044     {
2045       if (debug_infrun)
2046         {
2047           fprintf_unfiltered (gdb_stdlog,
2048                               "infrun: stepping past non-steppable watchpoint. "
2049                               "skipping watchpoint at %s:%d\n",
2050                               paddress (bl->gdbarch, bl->address),
2051                               bl->length);
2052         }
2053       return 0;
2054     }
2055
2056   return 1;
2057 }
2058
2059 /* Same as should_be_inserted but does the check assuming
2060    that the location is not duplicated.  */
2061
2062 static int
2063 unduplicated_should_be_inserted (struct bp_location *bl)
2064 {
2065   int result;
2066   const int save_duplicate = bl->duplicate;
2067
2068   bl->duplicate = 0;
2069   result = should_be_inserted (bl);
2070   bl->duplicate = save_duplicate;
2071   return result;
2072 }
2073
2074 /* Parses a conditional described by an expression COND into an
2075    agent expression bytecode suitable for evaluation
2076    by the bytecode interpreter.  Return NULL if there was
2077    any error during parsing.  */
2078
2079 static agent_expr_up
2080 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2081 {
2082   if (cond == NULL)
2083     return NULL;
2084
2085   agent_expr_up aexpr;
2086
2087   /* We don't want to stop processing, so catch any errors
2088      that may show up.  */
2089   try
2090     {
2091       aexpr = gen_eval_for_expr (scope, cond);
2092     }
2093
2094   catch (const gdb_exception_error &ex)
2095     {
2096       /* If we got here, it means the condition could not be parsed to a valid
2097          bytecode expression and thus can't be evaluated on the target's side.
2098          It's no use iterating through the conditions.  */
2099     }
2100
2101   /* We have a valid agent expression.  */
2102   return aexpr;
2103 }
2104
2105 /* Based on location BL, create a list of breakpoint conditions to be
2106    passed on to the target.  If we have duplicated locations with different
2107    conditions, we will add such conditions to the list.  The idea is that the
2108    target will evaluate the list of conditions and will only notify GDB when
2109    one of them is true.  */
2110
2111 static void
2112 build_target_condition_list (struct bp_location *bl)
2113 {
2114   struct bp_location **locp = NULL, **loc2p;
2115   int null_condition_or_parse_error = 0;
2116   int modified = bl->needs_update;
2117   struct bp_location *loc;
2118
2119   /* Release conditions left over from a previous insert.  */
2120   bl->target_info.conditions.clear ();
2121
2122   /* This is only meaningful if the target is
2123      evaluating conditions and if the user has
2124      opted for condition evaluation on the target's
2125      side.  */
2126   if (gdb_evaluates_breakpoint_condition_p ()
2127       || !target_supports_evaluation_of_breakpoint_conditions ())
2128     return;
2129
2130   /* Do a first pass to check for locations with no assigned
2131      conditions or conditions that fail to parse to a valid agent expression
2132      bytecode.  If any of these happen, then it's no use to send conditions
2133      to the target since this location will always trigger and generate a
2134      response back to GDB.  */
2135   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2136     {
2137       loc = (*loc2p);
2138       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2139         {
2140           if (modified)
2141             {
2142               /* Re-parse the conditions since something changed.  In that
2143                  case we already freed the condition bytecodes (see
2144                  force_breakpoint_reinsertion).  We just
2145                  need to parse the condition to bytecodes again.  */
2146               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2147                                                         loc->cond.get ());
2148             }
2149
2150           /* If we have a NULL bytecode expression, it means something
2151              went wrong or we have a null condition expression.  */
2152           if (!loc->cond_bytecode)
2153             {
2154               null_condition_or_parse_error = 1;
2155               break;
2156             }
2157         }
2158     }
2159
2160   /* If any of these happened, it means we will have to evaluate the conditions
2161      for the location's address on gdb's side.  It is no use keeping bytecodes
2162      for all the other duplicate locations, thus we free all of them here.
2163
2164      This is so we have a finer control over which locations' conditions are
2165      being evaluated by GDB or the remote stub.  */
2166   if (null_condition_or_parse_error)
2167     {
2168       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2169         {
2170           loc = (*loc2p);
2171           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2172             {
2173               /* Only go as far as the first NULL bytecode is
2174                  located.  */
2175               if (!loc->cond_bytecode)
2176                 return;
2177
2178               loc->cond_bytecode.reset ();
2179             }
2180         }
2181     }
2182
2183   /* No NULL conditions or failed bytecode generation.  Build a condition list
2184      for this location's address.  */
2185   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2186     {
2187       loc = (*loc2p);
2188       if (loc->cond
2189           && is_breakpoint (loc->owner)
2190           && loc->pspace->num == bl->pspace->num
2191           && loc->owner->enable_state == bp_enabled
2192           && loc->enabled)
2193         {
2194           /* Add the condition to the vector.  This will be used later
2195              to send the conditions to the target.  */
2196           bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2197         }
2198     }
2199
2200   return;
2201 }
2202
2203 /* Parses a command described by string CMD into an agent expression
2204    bytecode suitable for evaluation by the bytecode interpreter.
2205    Return NULL if there was any error during parsing.  */
2206
2207 static agent_expr_up
2208 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2209 {
2210   const char *cmdrest;
2211   const char *format_start, *format_end;
2212   struct gdbarch *gdbarch = get_current_arch ();
2213
2214   if (cmd == NULL)
2215     return NULL;
2216
2217   cmdrest = cmd;
2218
2219   if (*cmdrest == ',')
2220     ++cmdrest;
2221   cmdrest = skip_spaces (cmdrest);
2222
2223   if (*cmdrest++ != '"')
2224     error (_("No format string following the location"));
2225
2226   format_start = cmdrest;
2227
2228   format_pieces fpieces (&cmdrest);
2229
2230   format_end = cmdrest;
2231
2232   if (*cmdrest++ != '"')
2233     error (_("Bad format string, non-terminated '\"'."));
2234   
2235   cmdrest = skip_spaces (cmdrest);
2236
2237   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2238     error (_("Invalid argument syntax"));
2239
2240   if (*cmdrest == ',')
2241     cmdrest++;
2242   cmdrest = skip_spaces (cmdrest);
2243
2244   /* For each argument, make an expression.  */
2245
2246   std::vector<struct expression *> argvec;
2247   while (*cmdrest != '\0')
2248     {
2249       const char *cmd1;
2250
2251       cmd1 = cmdrest;
2252       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2253       argvec.push_back (expr.release ());
2254       cmdrest = cmd1;
2255       if (*cmdrest == ',')
2256         ++cmdrest;
2257     }
2258
2259   agent_expr_up aexpr;
2260
2261   /* We don't want to stop processing, so catch any errors
2262      that may show up.  */
2263   try
2264     {
2265       aexpr = gen_printf (scope, gdbarch, 0, 0,
2266                           format_start, format_end - format_start,
2267                           argvec.size (), argvec.data ());
2268     }
2269   catch (const gdb_exception_error &ex)
2270     {
2271       /* If we got here, it means the command could not be parsed to a valid
2272          bytecode expression and thus can't be evaluated on the target's side.
2273          It's no use iterating through the other commands.  */
2274     }
2275
2276   /* We have a valid agent expression, return it.  */
2277   return aexpr;
2278 }
2279
2280 /* Based on location BL, create a list of breakpoint commands to be
2281    passed on to the target.  If we have duplicated locations with
2282    different commands, we will add any such to the list.  */
2283
2284 static void
2285 build_target_command_list (struct bp_location *bl)
2286 {
2287   struct bp_location **locp = NULL, **loc2p;
2288   int null_command_or_parse_error = 0;
2289   int modified = bl->needs_update;
2290   struct bp_location *loc;
2291
2292   /* Clear commands left over from a previous insert.  */
2293   bl->target_info.tcommands.clear ();
2294
2295   if (!target_can_run_breakpoint_commands ())
2296     return;
2297
2298   /* For now, limit to agent-style dprintf breakpoints.  */
2299   if (dprintf_style != dprintf_style_agent)
2300     return;
2301
2302   /* For now, if we have any duplicate location that isn't a dprintf,
2303      don't install the target-side commands, as that would make the
2304      breakpoint not be reported to the core, and we'd lose
2305      control.  */
2306   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2307     {
2308       loc = (*loc2p);
2309       if (is_breakpoint (loc->owner)
2310           && loc->pspace->num == bl->pspace->num
2311           && loc->owner->type != bp_dprintf)
2312         return;
2313     }
2314
2315   /* Do a first pass to check for locations with no assigned
2316      conditions or conditions that fail to parse to a valid agent expression
2317      bytecode.  If any of these happen, then it's no use to send conditions
2318      to the target since this location will always trigger and generate a
2319      response back to GDB.  */
2320   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2321     {
2322       loc = (*loc2p);
2323       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2324         {
2325           if (modified)
2326             {
2327               /* Re-parse the commands since something changed.  In that
2328                  case we already freed the command bytecodes (see
2329                  force_breakpoint_reinsertion).  We just
2330                  need to parse the command to bytecodes again.  */
2331               loc->cmd_bytecode
2332                 = parse_cmd_to_aexpr (bl->address,
2333                                       loc->owner->extra_string);
2334             }
2335
2336           /* If we have a NULL bytecode expression, it means something
2337              went wrong or we have a null command expression.  */
2338           if (!loc->cmd_bytecode)
2339             {
2340               null_command_or_parse_error = 1;
2341               break;
2342             }
2343         }
2344     }
2345
2346   /* If anything failed, then we're not doing target-side commands,
2347      and so clean up.  */
2348   if (null_command_or_parse_error)
2349     {
2350       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2351         {
2352           loc = (*loc2p);
2353           if (is_breakpoint (loc->owner)
2354               && loc->pspace->num == bl->pspace->num)
2355             {
2356               /* Only go as far as the first NULL bytecode is
2357                  located.  */
2358               if (loc->cmd_bytecode == NULL)
2359                 return;
2360
2361               loc->cmd_bytecode.reset ();
2362             }
2363         }
2364     }
2365
2366   /* No NULL commands or failed bytecode generation.  Build a command list
2367      for this location's address.  */
2368   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2369     {
2370       loc = (*loc2p);
2371       if (loc->owner->extra_string
2372           && is_breakpoint (loc->owner)
2373           && loc->pspace->num == bl->pspace->num
2374           && loc->owner->enable_state == bp_enabled
2375           && loc->enabled)
2376         {
2377           /* Add the command to the vector.  This will be used later
2378              to send the commands to the target.  */
2379           bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2380         }
2381     }
2382
2383   bl->target_info.persist = 0;
2384   /* Maybe flag this location as persistent.  */
2385   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2386     bl->target_info.persist = 1;
2387 }
2388
2389 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2390    of breakpoint according to ADDR except single-step breakpoint.
2391    Get the kind of single-step breakpoint according to the current
2392    registers state.  */
2393
2394 static int
2395 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2396 {
2397   if (bl->owner->type == bp_single_step)
2398     {
2399       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2400       struct regcache *regcache;
2401
2402       regcache = get_thread_regcache (thr);
2403
2404       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2405                                                          regcache, addr);
2406     }
2407   else
2408     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2409 }
2410
2411 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2412    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2413    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2414    Returns 0 for success, 1 if the bp_location type is not supported or
2415    -1 for failure.
2416
2417    NOTE drow/2003-09-09: This routine could be broken down to an
2418    object-style method for each breakpoint or catchpoint type.  */
2419 static int
2420 insert_bp_location (struct bp_location *bl,
2421                     struct ui_file *tmp_error_stream,
2422                     int *disabled_breaks,
2423                     int *hw_breakpoint_error,
2424                     int *hw_bp_error_explained_already)
2425 {
2426   gdb_exception bp_excpt;
2427
2428   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2429     return 0;
2430
2431   /* Note we don't initialize bl->target_info, as that wipes out
2432      the breakpoint location's shadow_contents if the breakpoint
2433      is still inserted at that location.  This in turn breaks
2434      target_read_memory which depends on these buffers when
2435      a memory read is requested at the breakpoint location:
2436      Once the target_info has been wiped, we fail to see that
2437      we have a breakpoint inserted at that address and thus
2438      read the breakpoint instead of returning the data saved in
2439      the breakpoint location's shadow contents.  */
2440   bl->target_info.reqstd_address = bl->address;
2441   bl->target_info.placed_address_space = bl->pspace->aspace;
2442   bl->target_info.length = bl->length;
2443
2444   /* When working with target-side conditions, we must pass all the conditions
2445      for the same breakpoint address down to the target since GDB will not
2446      insert those locations.  With a list of breakpoint conditions, the target
2447      can decide when to stop and notify GDB.  */
2448
2449   if (is_breakpoint (bl->owner))
2450     {
2451       build_target_condition_list (bl);
2452       build_target_command_list (bl);
2453       /* Reset the modification marker.  */
2454       bl->needs_update = 0;
2455     }
2456
2457   if (bl->loc_type == bp_loc_software_breakpoint
2458       || bl->loc_type == bp_loc_hardware_breakpoint)
2459     {
2460       if (bl->owner->type != bp_hardware_breakpoint)
2461         {
2462           /* If the explicitly specified breakpoint type
2463              is not hardware breakpoint, check the memory map to see
2464              if the breakpoint address is in read only memory or not.
2465
2466              Two important cases are:
2467              - location type is not hardware breakpoint, memory
2468              is readonly.  We change the type of the location to
2469              hardware breakpoint.
2470              - location type is hardware breakpoint, memory is
2471              read-write.  This means we've previously made the
2472              location hardware one, but then the memory map changed,
2473              so we undo.
2474              
2475              When breakpoints are removed, remove_breakpoints will use
2476              location types we've just set here, the only possible
2477              problem is that memory map has changed during running
2478              program, but it's not going to work anyway with current
2479              gdb.  */
2480           struct mem_region *mr 
2481             = lookup_mem_region (bl->target_info.reqstd_address);
2482           
2483           if (mr)
2484             {
2485               if (automatic_hardware_breakpoints)
2486                 {
2487                   enum bp_loc_type new_type;
2488                   
2489                   if (mr->attrib.mode != MEM_RW)
2490                     new_type = bp_loc_hardware_breakpoint;
2491                   else 
2492                     new_type = bp_loc_software_breakpoint;
2493                   
2494                   if (new_type != bl->loc_type)
2495                     {
2496                       static int said = 0;
2497
2498                       bl->loc_type = new_type;
2499                       if (!said)
2500                         {
2501                           fprintf_filtered (gdb_stdout,
2502                                             _("Note: automatically using "
2503                                               "hardware breakpoints for "
2504                                               "read-only addresses.\n"));
2505                           said = 1;
2506                         }
2507                     }
2508                 }
2509               else if (bl->loc_type == bp_loc_software_breakpoint
2510                        && mr->attrib.mode != MEM_RW)
2511                 {
2512                   fprintf_unfiltered (tmp_error_stream,
2513                                       _("Cannot insert breakpoint %d.\n"
2514                                         "Cannot set software breakpoint "
2515                                         "at read-only address %s\n"),
2516                                       bl->owner->number,
2517                                       paddress (bl->gdbarch, bl->address));
2518                   return 1;
2519                 }
2520             }
2521         }
2522         
2523       /* First check to see if we have to handle an overlay.  */
2524       if (overlay_debugging == ovly_off
2525           || bl->section == NULL
2526           || !(section_is_overlay (bl->section)))
2527         {
2528           /* No overlay handling: just set the breakpoint.  */
2529           try
2530             {
2531               int val;
2532
2533               val = bl->owner->ops->insert_location (bl);
2534               if (val)
2535                 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2536             }
2537           catch (gdb_exception &e)
2538             {
2539               bp_excpt = std::move (e);
2540             }
2541         }
2542       else
2543         {
2544           /* This breakpoint is in an overlay section.
2545              Shall we set a breakpoint at the LMA?  */
2546           if (!overlay_events_enabled)
2547             {
2548               /* Yes -- overlay event support is not active, 
2549                  so we must try to set a breakpoint at the LMA.
2550                  This will not work for a hardware breakpoint.  */
2551               if (bl->loc_type == bp_loc_hardware_breakpoint)
2552                 warning (_("hardware breakpoint %d not supported in overlay!"),
2553                          bl->owner->number);
2554               else
2555                 {
2556                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2557                                                              bl->section);
2558                   /* Set a software (trap) breakpoint at the LMA.  */
2559                   bl->overlay_target_info = bl->target_info;
2560                   bl->overlay_target_info.reqstd_address = addr;
2561
2562                   /* No overlay handling: just set the breakpoint.  */
2563                   try
2564                     {
2565                       int val;
2566
2567                       bl->overlay_target_info.kind
2568                         = breakpoint_kind (bl, &addr);
2569                       bl->overlay_target_info.placed_address = addr;
2570                       val = target_insert_breakpoint (bl->gdbarch,
2571                                                       &bl->overlay_target_info);
2572                       if (val)
2573                         bp_excpt
2574                           = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2575                     }
2576                   catch (gdb_exception &e)
2577                     {
2578                       bp_excpt = std::move (e);
2579                     }
2580
2581                   if (bp_excpt.reason != 0)
2582                     fprintf_unfiltered (tmp_error_stream,
2583                                         "Overlay breakpoint %d "
2584                                         "failed: in ROM?\n",
2585                                         bl->owner->number);
2586                 }
2587             }
2588           /* Shall we set a breakpoint at the VMA? */
2589           if (section_is_mapped (bl->section))
2590             {
2591               /* Yes.  This overlay section is mapped into memory.  */
2592               try
2593                 {
2594                   int val;
2595
2596                   val = bl->owner->ops->insert_location (bl);
2597                   if (val)
2598                     bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2599                 }
2600               catch (gdb_exception &e)
2601                 {
2602                   bp_excpt = std::move (e);
2603                 }
2604             }
2605           else
2606             {
2607               /* No.  This breakpoint will not be inserted.  
2608                  No error, but do not mark the bp as 'inserted'.  */
2609               return 0;
2610             }
2611         }
2612
2613       if (bp_excpt.reason != 0)
2614         {
2615           /* Can't set the breakpoint.  */
2616
2617           /* In some cases, we might not be able to insert a
2618              breakpoint in a shared library that has already been
2619              removed, but we have not yet processed the shlib unload
2620              event.  Unfortunately, some targets that implement
2621              breakpoint insertion themselves can't tell why the
2622              breakpoint insertion failed (e.g., the remote target
2623              doesn't define error codes), so we must treat generic
2624              errors as memory errors.  */
2625           if (bp_excpt.reason == RETURN_ERROR
2626               && (bp_excpt.error == GENERIC_ERROR
2627                   || bp_excpt.error == MEMORY_ERROR)
2628               && bl->loc_type == bp_loc_software_breakpoint
2629               && (solib_name_from_address (bl->pspace, bl->address)
2630                   || shared_objfile_contains_address_p (bl->pspace,
2631                                                         bl->address)))
2632             {
2633               /* See also: disable_breakpoints_in_shlibs.  */
2634               bl->shlib_disabled = 1;
2635               gdb::observers::breakpoint_modified.notify (bl->owner);
2636               if (!*disabled_breaks)
2637                 {
2638                   fprintf_unfiltered (tmp_error_stream, 
2639                                       "Cannot insert breakpoint %d.\n", 
2640                                       bl->owner->number);
2641                   fprintf_unfiltered (tmp_error_stream, 
2642                                       "Temporarily disabling shared "
2643                                       "library breakpoints:\n");
2644                 }
2645               *disabled_breaks = 1;
2646               fprintf_unfiltered (tmp_error_stream,
2647                                   "breakpoint #%d\n", bl->owner->number);
2648               return 0;
2649             }
2650           else
2651             {
2652               if (bl->loc_type == bp_loc_hardware_breakpoint)
2653                 {
2654                   *hw_breakpoint_error = 1;
2655                   *hw_bp_error_explained_already = bp_excpt.message != NULL;
2656                   fprintf_unfiltered (tmp_error_stream,
2657                                       "Cannot insert hardware breakpoint %d%s",
2658                                       bl->owner->number,
2659                                       bp_excpt.message ? ":" : ".\n");
2660                   if (bp_excpt.message != NULL)
2661                     fprintf_unfiltered (tmp_error_stream, "%s.\n",
2662                                         bp_excpt.what ());
2663                 }
2664               else
2665                 {
2666                   if (bp_excpt.message == NULL)
2667                     {
2668                       std::string message
2669                         = memory_error_message (TARGET_XFER_E_IO,
2670                                                 bl->gdbarch, bl->address);
2671
2672                       fprintf_unfiltered (tmp_error_stream,
2673                                           "Cannot insert breakpoint %d.\n"
2674                                           "%s\n",
2675                                           bl->owner->number, message.c_str ());
2676                     }
2677                   else
2678                     {
2679                       fprintf_unfiltered (tmp_error_stream,
2680                                           "Cannot insert breakpoint %d: %s\n",
2681                                           bl->owner->number,
2682                                           bp_excpt.what ());
2683                     }
2684                 }
2685               return 1;
2686
2687             }
2688         }
2689       else
2690         bl->inserted = 1;
2691
2692       return 0;
2693     }
2694
2695   else if (bl->loc_type == bp_loc_hardware_watchpoint
2696            /* NOTE drow/2003-09-08: This state only exists for removing
2697               watchpoints.  It's not clear that it's necessary...  */
2698            && bl->owner->disposition != disp_del_at_next_stop)
2699     {
2700       int val;
2701
2702       gdb_assert (bl->owner->ops != NULL
2703                   && bl->owner->ops->insert_location != NULL);
2704
2705       val = bl->owner->ops->insert_location (bl);
2706
2707       /* If trying to set a read-watchpoint, and it turns out it's not
2708          supported, try emulating one with an access watchpoint.  */
2709       if (val == 1 && bl->watchpoint_type == hw_read)
2710         {
2711           struct bp_location *loc, **loc_temp;
2712
2713           /* But don't try to insert it, if there's already another
2714              hw_access location that would be considered a duplicate
2715              of this one.  */
2716           ALL_BP_LOCATIONS (loc, loc_temp)
2717             if (loc != bl
2718                 && loc->watchpoint_type == hw_access
2719                 && watchpoint_locations_match (bl, loc))
2720               {
2721                 bl->duplicate = 1;
2722                 bl->inserted = 1;
2723                 bl->target_info = loc->target_info;
2724                 bl->watchpoint_type = hw_access;
2725                 val = 0;
2726                 break;
2727               }
2728
2729           if (val == 1)
2730             {
2731               bl->watchpoint_type = hw_access;
2732               val = bl->owner->ops->insert_location (bl);
2733
2734               if (val)
2735                 /* Back to the original value.  */
2736                 bl->watchpoint_type = hw_read;
2737             }
2738         }
2739
2740       bl->inserted = (val == 0);
2741     }
2742
2743   else if (bl->owner->type == bp_catchpoint)
2744     {
2745       int val;
2746
2747       gdb_assert (bl->owner->ops != NULL
2748                   && bl->owner->ops->insert_location != NULL);
2749
2750       val = bl->owner->ops->insert_location (bl);
2751       if (val)
2752         {
2753           bl->owner->enable_state = bp_disabled;
2754
2755           if (val == 1)
2756             warning (_("\
2757 Error inserting catchpoint %d: Your system does not support this type\n\
2758 of catchpoint."), bl->owner->number);
2759           else
2760             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2761         }
2762
2763       bl->inserted = (val == 0);
2764
2765       /* We've already printed an error message if there was a problem
2766          inserting this catchpoint, and we've disabled the catchpoint,
2767          so just return success.  */
2768       return 0;
2769     }
2770
2771   return 0;
2772 }
2773
2774 /* This function is called when program space PSPACE is about to be
2775    deleted.  It takes care of updating breakpoints to not reference
2776    PSPACE anymore.  */
2777
2778 void
2779 breakpoint_program_space_exit (struct program_space *pspace)
2780 {
2781   struct breakpoint *b, *b_temp;
2782   struct bp_location *loc, **loc_temp;
2783
2784   /* Remove any breakpoint that was set through this program space.  */
2785   ALL_BREAKPOINTS_SAFE (b, b_temp)
2786     {
2787       if (b->pspace == pspace)
2788         delete_breakpoint (b);
2789     }
2790
2791   /* Breakpoints set through other program spaces could have locations
2792      bound to PSPACE as well.  Remove those.  */
2793   ALL_BP_LOCATIONS (loc, loc_temp)
2794     {
2795       struct bp_location *tmp;
2796
2797       if (loc->pspace == pspace)
2798         {
2799           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2800           if (loc->owner->loc == loc)
2801             loc->owner->loc = loc->next;
2802           else
2803             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2804               if (tmp->next == loc)
2805                 {
2806                   tmp->next = loc->next;
2807                   break;
2808                 }
2809         }
2810     }
2811
2812   /* Now update the global location list to permanently delete the
2813      removed locations above.  */
2814   update_global_location_list (UGLL_DONT_INSERT);
2815 }
2816
2817 /* Make sure all breakpoints are inserted in inferior.
2818    Throws exception on any error.
2819    A breakpoint that is already inserted won't be inserted
2820    again, so calling this function twice is safe.  */
2821 void
2822 insert_breakpoints (void)
2823 {
2824   struct breakpoint *bpt;
2825
2826   ALL_BREAKPOINTS (bpt)
2827     if (is_hardware_watchpoint (bpt))
2828       {
2829         struct watchpoint *w = (struct watchpoint *) bpt;
2830
2831         update_watchpoint (w, 0 /* don't reparse.  */);
2832       }
2833
2834   /* Updating watchpoints creates new locations, so update the global
2835      location list.  Explicitly tell ugll to insert locations and
2836      ignore breakpoints_always_inserted_mode.  */
2837   update_global_location_list (UGLL_INSERT);
2838 }
2839
2840 /* Invoke CALLBACK for each of bp_location.  */
2841
2842 void
2843 iterate_over_bp_locations (walk_bp_location_callback callback)
2844 {
2845   struct bp_location *loc, **loc_tmp;
2846
2847   ALL_BP_LOCATIONS (loc, loc_tmp)
2848     {
2849       callback (loc, NULL);
2850     }
2851 }
2852
2853 /* This is used when we need to synch breakpoint conditions between GDB and the
2854    target.  It is the case with deleting and disabling of breakpoints when using
2855    always-inserted mode.  */
2856
2857 static void
2858 update_inserted_breakpoint_locations (void)
2859 {
2860   struct bp_location *bl, **blp_tmp;
2861   int error_flag = 0;
2862   int val = 0;
2863   int disabled_breaks = 0;
2864   int hw_breakpoint_error = 0;
2865   int hw_bp_details_reported = 0;
2866
2867   string_file tmp_error_stream;
2868
2869   /* Explicitly mark the warning -- this will only be printed if
2870      there was an error.  */
2871   tmp_error_stream.puts ("Warning:\n");
2872
2873   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2874
2875   ALL_BP_LOCATIONS (bl, blp_tmp)
2876     {
2877       /* We only want to update software breakpoints and hardware
2878          breakpoints.  */
2879       if (!is_breakpoint (bl->owner))
2880         continue;
2881
2882       /* We only want to update locations that are already inserted
2883          and need updating.  This is to avoid unwanted insertion during
2884          deletion of breakpoints.  */
2885       if (!bl->inserted || !bl->needs_update)
2886         continue;
2887
2888       switch_to_program_space_and_thread (bl->pspace);
2889
2890       /* For targets that support global breakpoints, there's no need
2891          to select an inferior to insert breakpoint to.  In fact, even
2892          if we aren't attached to any process yet, we should still
2893          insert breakpoints.  */
2894       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2895           && inferior_ptid == null_ptid)
2896         continue;
2897
2898       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2899                                     &hw_breakpoint_error, &hw_bp_details_reported);
2900       if (val)
2901         error_flag = val;
2902     }
2903
2904   if (error_flag)
2905     {
2906       target_terminal::ours_for_output ();
2907       error_stream (tmp_error_stream);
2908     }
2909 }
2910
2911 /* Used when starting or continuing the program.  */
2912
2913 static void
2914 insert_breakpoint_locations (void)
2915 {
2916   struct breakpoint *bpt;
2917   struct bp_location *bl, **blp_tmp;
2918   int error_flag = 0;
2919   int val = 0;
2920   int disabled_breaks = 0;
2921   int hw_breakpoint_error = 0;
2922   int hw_bp_error_explained_already = 0;
2923
2924   string_file tmp_error_stream;
2925
2926   /* Explicitly mark the warning -- this will only be printed if
2927      there was an error.  */
2928   tmp_error_stream.puts ("Warning:\n");
2929
2930   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2931
2932   ALL_BP_LOCATIONS (bl, blp_tmp)
2933     {
2934       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2935         continue;
2936
2937       /* There is no point inserting thread-specific breakpoints if
2938          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2939          has BL->OWNER always non-NULL.  */
2940       if (bl->owner->thread != -1
2941           && !valid_global_thread_id (bl->owner->thread))
2942         continue;
2943
2944       switch_to_program_space_and_thread (bl->pspace);
2945
2946       /* For targets that support global breakpoints, there's no need
2947          to select an inferior to insert breakpoint to.  In fact, even
2948          if we aren't attached to any process yet, we should still
2949          insert breakpoints.  */
2950       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2951           && inferior_ptid == null_ptid)
2952         continue;
2953
2954       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2955                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
2956       if (val)
2957         error_flag = val;
2958     }
2959
2960   /* If we failed to insert all locations of a watchpoint, remove
2961      them, as half-inserted watchpoint is of limited use.  */
2962   ALL_BREAKPOINTS (bpt)  
2963     {
2964       int some_failed = 0;
2965       struct bp_location *loc;
2966
2967       if (!is_hardware_watchpoint (bpt))
2968         continue;
2969
2970       if (!breakpoint_enabled (bpt))
2971         continue;
2972
2973       if (bpt->disposition == disp_del_at_next_stop)
2974         continue;
2975       
2976       for (loc = bpt->loc; loc; loc = loc->next)
2977         if (!loc->inserted && should_be_inserted (loc))
2978           {
2979             some_failed = 1;
2980             break;
2981           }
2982       if (some_failed)
2983         {
2984           for (loc = bpt->loc; loc; loc = loc->next)
2985             if (loc->inserted)
2986               remove_breakpoint (loc);
2987
2988           hw_breakpoint_error = 1;
2989           tmp_error_stream.printf ("Could not insert "
2990                                    "hardware watchpoint %d.\n",
2991                                    bpt->number);
2992           error_flag = -1;
2993         }
2994     }
2995
2996   if (error_flag)
2997     {
2998       /* If a hardware breakpoint or watchpoint was inserted, add a
2999          message about possibly exhausted resources.  */
3000       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3001         {
3002           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3003 You may have requested too many hardware breakpoints/watchpoints.\n");
3004         }
3005       target_terminal::ours_for_output ();
3006       error_stream (tmp_error_stream);
3007     }
3008 }
3009
3010 /* Used when the program stops.
3011    Returns zero if successful, or non-zero if there was a problem
3012    removing a breakpoint location.  */
3013
3014 int
3015 remove_breakpoints (void)
3016 {
3017   struct bp_location *bl, **blp_tmp;
3018   int val = 0;
3019
3020   ALL_BP_LOCATIONS (bl, blp_tmp)
3021   {
3022     if (bl->inserted && !is_tracepoint (bl->owner))
3023       val |= remove_breakpoint (bl);
3024   }
3025   return val;
3026 }
3027
3028 /* When a thread exits, remove breakpoints that are related to
3029    that thread.  */
3030
3031 static void
3032 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3033 {
3034   struct breakpoint *b, *b_tmp;
3035
3036   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3037     {
3038       if (b->thread == tp->global_num && user_breakpoint_p (b))
3039         {
3040           b->disposition = disp_del_at_next_stop;
3041
3042           printf_filtered (_("\
3043 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3044                            b->number, print_thread_id (tp));
3045
3046           /* Hide it from the user.  */
3047           b->number = 0;
3048        }
3049     }
3050 }
3051
3052 /* See breakpoint.h.  */
3053
3054 void
3055 remove_breakpoints_inf (inferior *inf)
3056 {
3057   struct bp_location *bl, **blp_tmp;
3058   int val;
3059
3060   ALL_BP_LOCATIONS (bl, blp_tmp)
3061   {
3062     if (bl->pspace != inf->pspace)
3063       continue;
3064
3065     if (bl->inserted && !bl->target_info.persist)
3066       {
3067         val = remove_breakpoint (bl);
3068         if (val != 0)
3069           return;
3070       }
3071   }
3072 }
3073
3074 static int internal_breakpoint_number = -1;
3075
3076 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3077    If INTERNAL is non-zero, the breakpoint number will be populated
3078    from internal_breakpoint_number and that variable decremented.
3079    Otherwise the breakpoint number will be populated from
3080    breakpoint_count and that value incremented.  Internal breakpoints
3081    do not set the internal var bpnum.  */
3082 static void
3083 set_breakpoint_number (int internal, struct breakpoint *b)
3084 {
3085   if (internal)
3086     b->number = internal_breakpoint_number--;
3087   else
3088     {
3089       set_breakpoint_count (breakpoint_count + 1);
3090       b->number = breakpoint_count;
3091     }
3092 }
3093
3094 static struct breakpoint *
3095 create_internal_breakpoint (struct gdbarch *gdbarch,
3096                             CORE_ADDR address, enum bptype type,
3097                             const struct breakpoint_ops *ops)
3098 {
3099   symtab_and_line sal;
3100   sal.pc = address;
3101   sal.section = find_pc_overlay (sal.pc);
3102   sal.pspace = current_program_space;
3103
3104   breakpoint *b = set_raw_breakpoint (gdbarch, sal, type, ops);
3105   b->number = internal_breakpoint_number--;
3106   b->disposition = disp_donttouch;
3107
3108   return b;
3109 }
3110
3111 static const char *const longjmp_names[] =
3112   {
3113     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3114   };
3115 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3116
3117 /* Per-objfile data private to breakpoint.c.  */
3118 struct breakpoint_objfile_data
3119 {
3120   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3121   struct bound_minimal_symbol overlay_msym {};
3122
3123   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3124   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES] {};
3125
3126   /* True if we have looked for longjmp probes.  */
3127   int longjmp_searched = 0;
3128
3129   /* SystemTap probe points for longjmp (if any).  These are non-owning
3130      references.  */
3131   std::vector<probe *> longjmp_probes;
3132
3133   /* Minimal symbol for "std::terminate()" (if any).  */
3134   struct bound_minimal_symbol terminate_msym {};
3135
3136   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3137   struct bound_minimal_symbol exception_msym {};
3138
3139   /* True if we have looked for exception probes.  */
3140   int exception_searched = 0;
3141
3142   /* SystemTap probe points for unwinding (if any).  These are non-owning
3143      references.  */
3144   std::vector<probe *> exception_probes;
3145 };
3146
3147 static const struct objfile_key<breakpoint_objfile_data>
3148   breakpoint_objfile_key;
3149
3150 /* Minimal symbol not found sentinel.  */
3151 static struct minimal_symbol msym_not_found;
3152
3153 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3154
3155 static int
3156 msym_not_found_p (const struct minimal_symbol *msym)
3157 {
3158   return msym == &msym_not_found;
3159 }
3160
3161 /* Return per-objfile data needed by breakpoint.c.
3162    Allocate the data if necessary.  */
3163
3164 static struct breakpoint_objfile_data *
3165 get_breakpoint_objfile_data (struct objfile *objfile)
3166 {
3167   struct breakpoint_objfile_data *bp_objfile_data;
3168
3169   bp_objfile_data = breakpoint_objfile_key.get (objfile);
3170   if (bp_objfile_data == NULL)
3171     bp_objfile_data = breakpoint_objfile_key.emplace (objfile);
3172   return bp_objfile_data;
3173 }
3174
3175 static void
3176 create_overlay_event_breakpoint (void)
3177 {
3178   const char *const func_name = "_ovly_debug_event";
3179
3180   for (objfile *objfile : current_program_space->objfiles ())
3181     {
3182       struct breakpoint *b;
3183       struct breakpoint_objfile_data *bp_objfile_data;
3184       CORE_ADDR addr;
3185       struct explicit_location explicit_loc;
3186
3187       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3188
3189       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3190         continue;
3191
3192       if (bp_objfile_data->overlay_msym.minsym == NULL)
3193         {
3194           struct bound_minimal_symbol m;
3195
3196           m = lookup_minimal_symbol_text (func_name, objfile);
3197           if (m.minsym == NULL)
3198             {
3199               /* Avoid future lookups in this objfile.  */
3200               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3201               continue;
3202             }
3203           bp_objfile_data->overlay_msym = m;
3204         }
3205
3206       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3207       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3208                                       bp_overlay_event,
3209                                       &internal_breakpoint_ops);
3210       initialize_explicit_location (&explicit_loc);
3211       explicit_loc.function_name = ASTRDUP (func_name);
3212       b->location = new_explicit_location (&explicit_loc);
3213
3214       if (overlay_debugging == ovly_auto)
3215         {
3216           b->enable_state = bp_enabled;
3217           overlay_events_enabled = 1;
3218         }
3219       else
3220        {
3221          b->enable_state = bp_disabled;
3222          overlay_events_enabled = 0;
3223        }
3224     }
3225 }
3226
3227 static void
3228 create_longjmp_master_breakpoint (void)
3229 {
3230   struct program_space *pspace;
3231
3232   scoped_restore_current_program_space restore_pspace;
3233
3234   ALL_PSPACES (pspace)
3235   {
3236     set_current_program_space (pspace);
3237
3238     for (objfile *objfile : current_program_space->objfiles ())
3239       {
3240         int i;
3241         struct gdbarch *gdbarch;
3242         struct breakpoint_objfile_data *bp_objfile_data;
3243
3244         gdbarch = get_objfile_arch (objfile);
3245
3246         bp_objfile_data = get_breakpoint_objfile_data (objfile);
3247
3248         if (!bp_objfile_data->longjmp_searched)
3249           {
3250             std::vector<probe *> ret
3251               = find_probes_in_objfile (objfile, "libc", "longjmp");
3252
3253             if (!ret.empty ())
3254               {
3255                 /* We are only interested in checking one element.  */
3256                 probe *p = ret[0];
3257
3258                 if (!p->can_evaluate_arguments ())
3259                   {
3260                     /* We cannot use the probe interface here, because it does
3261                        not know how to evaluate arguments.  */
3262                     ret.clear ();
3263                   }
3264               }
3265             bp_objfile_data->longjmp_probes = ret;
3266             bp_objfile_data->longjmp_searched = 1;
3267           }
3268
3269         if (!bp_objfile_data->longjmp_probes.empty ())
3270           {
3271             for (probe *p : bp_objfile_data->longjmp_probes)
3272               {
3273                 struct breakpoint *b;
3274
3275                 b = create_internal_breakpoint (gdbarch,
3276                                                 p->get_relocated_address (objfile),
3277                                                 bp_longjmp_master,
3278                                                 &internal_breakpoint_ops);
3279                 b->location = new_probe_location ("-probe-stap libc:longjmp");
3280                 b->enable_state = bp_disabled;
3281               }
3282
3283             continue;
3284           }
3285
3286         if (!gdbarch_get_longjmp_target_p (gdbarch))
3287           continue;
3288
3289         for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3290           {
3291             struct breakpoint *b;
3292             const char *func_name;
3293             CORE_ADDR addr;
3294             struct explicit_location explicit_loc;
3295
3296             if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3297               continue;
3298
3299             func_name = longjmp_names[i];
3300             if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3301               {
3302                 struct bound_minimal_symbol m;
3303
3304                 m = lookup_minimal_symbol_text (func_name, objfile);
3305                 if (m.minsym == NULL)
3306                   {
3307                     /* Prevent future lookups in this objfile.  */
3308                     bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3309                     continue;
3310                   }
3311                 bp_objfile_data->longjmp_msym[i] = m;
3312               }
3313
3314             addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3315             b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3316                                             &internal_breakpoint_ops);
3317             initialize_explicit_location (&explicit_loc);
3318             explicit_loc.function_name = ASTRDUP (func_name);
3319             b->location = new_explicit_location (&explicit_loc);
3320             b->enable_state = bp_disabled;
3321           }
3322       }
3323   }
3324 }
3325
3326 /* Create a master std::terminate breakpoint.  */
3327 static void
3328 create_std_terminate_master_breakpoint (void)
3329 {
3330   struct program_space *pspace;
3331   const char *const func_name = "std::terminate()";
3332
3333   scoped_restore_current_program_space restore_pspace;
3334
3335   ALL_PSPACES (pspace)
3336   {
3337     CORE_ADDR addr;
3338
3339     set_current_program_space (pspace);
3340
3341     for (objfile *objfile : current_program_space->objfiles ())
3342       {
3343         struct breakpoint *b;
3344         struct breakpoint_objfile_data *bp_objfile_data;
3345         struct explicit_location explicit_loc;
3346
3347         bp_objfile_data = get_breakpoint_objfile_data (objfile);
3348
3349         if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3350           continue;
3351
3352         if (bp_objfile_data->terminate_msym.minsym == NULL)
3353           {
3354             struct bound_minimal_symbol m;
3355
3356             m = lookup_minimal_symbol (func_name, NULL, objfile);
3357             if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3358                                      && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3359               {
3360                 /* Prevent future lookups in this objfile.  */
3361                 bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3362                 continue;
3363               }
3364             bp_objfile_data->terminate_msym = m;
3365           }
3366
3367         addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3368         b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3369                                         bp_std_terminate_master,
3370                                         &internal_breakpoint_ops);
3371         initialize_explicit_location (&explicit_loc);
3372         explicit_loc.function_name = ASTRDUP (func_name);
3373         b->location = new_explicit_location (&explicit_loc);
3374         b->enable_state = bp_disabled;
3375       }
3376   }
3377 }
3378
3379 /* Install a master breakpoint on the unwinder's debug hook.  */
3380
3381 static void
3382 create_exception_master_breakpoint (void)
3383 {
3384   const char *const func_name = "_Unwind_DebugHook";
3385
3386   for (objfile *objfile : current_program_space->objfiles ())
3387     {
3388       struct breakpoint *b;
3389       struct gdbarch *gdbarch;
3390       struct breakpoint_objfile_data *bp_objfile_data;
3391       CORE_ADDR addr;
3392       struct explicit_location explicit_loc;
3393
3394       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3395
3396       /* We prefer the SystemTap probe point if it exists.  */
3397       if (!bp_objfile_data->exception_searched)
3398         {
3399           std::vector<probe *> ret
3400             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3401
3402           if (!ret.empty ())
3403             {
3404               /* We are only interested in checking one element.  */
3405               probe *p = ret[0];
3406
3407               if (!p->can_evaluate_arguments ())
3408                 {
3409                   /* We cannot use the probe interface here, because it does
3410                      not know how to evaluate arguments.  */
3411                   ret.clear ();
3412                 }
3413             }
3414           bp_objfile_data->exception_probes = ret;
3415           bp_objfile_data->exception_searched = 1;
3416         }
3417
3418       if (!bp_objfile_data->exception_probes.empty ())
3419         {
3420           gdbarch = get_objfile_arch (objfile);
3421
3422           for (probe *p : bp_objfile_data->exception_probes)
3423             {
3424               b = create_internal_breakpoint (gdbarch,
3425                                               p->get_relocated_address (objfile),
3426                                               bp_exception_master,
3427                                               &internal_breakpoint_ops);
3428               b->location = new_probe_location ("-probe-stap libgcc:unwind");
3429               b->enable_state = bp_disabled;
3430             }
3431
3432           continue;
3433         }
3434
3435       /* Otherwise, try the hook function.  */
3436
3437       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3438         continue;
3439
3440       gdbarch = get_objfile_arch (objfile);
3441
3442       if (bp_objfile_data->exception_msym.minsym == NULL)
3443         {
3444           struct bound_minimal_symbol debug_hook;
3445
3446           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3447           if (debug_hook.minsym == NULL)
3448             {
3449               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3450               continue;
3451             }
3452
3453           bp_objfile_data->exception_msym = debug_hook;
3454         }
3455
3456       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3457       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3458                                                  current_top_target ());
3459       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3460                                       &internal_breakpoint_ops);
3461       initialize_explicit_location (&explicit_loc);
3462       explicit_loc.function_name = ASTRDUP (func_name);
3463       b->location = new_explicit_location (&explicit_loc);
3464       b->enable_state = bp_disabled;
3465     }
3466 }
3467
3468 /* Does B have a location spec?  */
3469
3470 static int
3471 breakpoint_event_location_empty_p (const struct breakpoint *b)
3472 {
3473   return b->location != NULL && event_location_empty_p (b->location.get ());
3474 }
3475
3476 void
3477 update_breakpoints_after_exec (void)
3478 {
3479   struct breakpoint *b, *b_tmp;
3480   struct bp_location *bploc, **bplocp_tmp;
3481
3482   /* We're about to delete breakpoints from GDB's lists.  If the
3483      INSERTED flag is true, GDB will try to lift the breakpoints by
3484      writing the breakpoints' "shadow contents" back into memory.  The
3485      "shadow contents" are NOT valid after an exec, so GDB should not
3486      do that.  Instead, the target is responsible from marking
3487      breakpoints out as soon as it detects an exec.  We don't do that
3488      here instead, because there may be other attempts to delete
3489      breakpoints after detecting an exec and before reaching here.  */
3490   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3491     if (bploc->pspace == current_program_space)
3492       gdb_assert (!bploc->inserted);
3493
3494   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3495   {
3496     if (b->pspace != current_program_space)
3497       continue;
3498
3499     /* Solib breakpoints must be explicitly reset after an exec().  */
3500     if (b->type == bp_shlib_event)
3501       {
3502         delete_breakpoint (b);
3503         continue;
3504       }
3505
3506     /* JIT breakpoints must be explicitly reset after an exec().  */
3507     if (b->type == bp_jit_event)
3508       {
3509         delete_breakpoint (b);
3510         continue;
3511       }
3512
3513     /* Thread event breakpoints must be set anew after an exec(),
3514        as must overlay event and longjmp master breakpoints.  */
3515     if (b->type == bp_thread_event || b->type == bp_overlay_event
3516         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3517         || b->type == bp_exception_master)
3518       {
3519         delete_breakpoint (b);
3520         continue;
3521       }
3522
3523     /* Step-resume breakpoints are meaningless after an exec().  */
3524     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3525       {
3526         delete_breakpoint (b);
3527         continue;
3528       }
3529
3530     /* Just like single-step breakpoints.  */
3531     if (b->type == bp_single_step)
3532       {
3533         delete_breakpoint (b);
3534         continue;
3535       }
3536
3537     /* Longjmp and longjmp-resume breakpoints are also meaningless
3538        after an exec.  */
3539     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3540         || b->type == bp_longjmp_call_dummy
3541         || b->type == bp_exception || b->type == bp_exception_resume)
3542       {
3543         delete_breakpoint (b);
3544         continue;
3545       }
3546
3547     if (b->type == bp_catchpoint)
3548       {
3549         /* For now, none of the bp_catchpoint breakpoints need to
3550            do anything at this point.  In the future, if some of
3551            the catchpoints need to something, we will need to add
3552            a new method, and call this method from here.  */
3553         continue;
3554       }
3555
3556     /* bp_finish is a special case.  The only way we ought to be able
3557        to see one of these when an exec() has happened, is if the user
3558        caught a vfork, and then said "finish".  Ordinarily a finish just
3559        carries them to the call-site of the current callee, by setting
3560        a temporary bp there and resuming.  But in this case, the finish
3561        will carry them entirely through the vfork & exec.
3562
3563        We don't want to allow a bp_finish to remain inserted now.  But
3564        we can't safely delete it, 'cause finish_command has a handle to
3565        the bp on a bpstat, and will later want to delete it.  There's a
3566        chance (and I've seen it happen) that if we delete the bp_finish
3567        here, that its storage will get reused by the time finish_command
3568        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3569        We really must allow finish_command to delete a bp_finish.
3570
3571        In the absence of a general solution for the "how do we know
3572        it's safe to delete something others may have handles to?"
3573        problem, what we'll do here is just uninsert the bp_finish, and
3574        let finish_command delete it.
3575
3576        (We know the bp_finish is "doomed" in the sense that it's
3577        momentary, and will be deleted as soon as finish_command sees
3578        the inferior stopped.  So it doesn't matter that the bp's
3579        address is probably bogus in the new a.out, unlike e.g., the
3580        solib breakpoints.)  */
3581
3582     if (b->type == bp_finish)
3583       {
3584         continue;
3585       }
3586
3587     /* Without a symbolic address, we have little hope of the
3588        pre-exec() address meaning the same thing in the post-exec()
3589        a.out.  */
3590     if (breakpoint_event_location_empty_p (b))
3591       {
3592         delete_breakpoint (b);
3593         continue;
3594       }
3595   }
3596 }
3597
3598 int
3599 detach_breakpoints (ptid_t ptid)
3600 {
3601   struct bp_location *bl, **blp_tmp;
3602   int val = 0;
3603   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3604   struct inferior *inf = current_inferior ();
3605
3606   if (ptid.pid () == inferior_ptid.pid ())
3607     error (_("Cannot detach breakpoints of inferior_ptid"));
3608
3609   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3610   inferior_ptid = ptid;
3611   ALL_BP_LOCATIONS (bl, blp_tmp)
3612   {
3613     if (bl->pspace != inf->pspace)
3614       continue;
3615
3616     /* This function must physically remove breakpoints locations
3617        from the specified ptid, without modifying the breakpoint
3618        package's state.  Locations of type bp_loc_other are only
3619        maintained at GDB side.  So, there is no need to remove
3620        these bp_loc_other locations.  Moreover, removing these
3621        would modify the breakpoint package's state.  */
3622     if (bl->loc_type == bp_loc_other)
3623       continue;
3624
3625     if (bl->inserted)
3626       val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3627   }
3628
3629   return val;
3630 }
3631
3632 /* Remove the breakpoint location BL from the current address space.
3633    Note that this is used to detach breakpoints from a child fork.
3634    When we get here, the child isn't in the inferior list, and neither
3635    do we have objects to represent its address space --- we should
3636    *not* look at bl->pspace->aspace here.  */
3637
3638 static int
3639 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3640 {
3641   int val;
3642
3643   /* BL is never in moribund_locations by our callers.  */
3644   gdb_assert (bl->owner != NULL);
3645
3646   /* The type of none suggests that owner is actually deleted.
3647      This should not ever happen.  */
3648   gdb_assert (bl->owner->type != bp_none);
3649
3650   if (bl->loc_type == bp_loc_software_breakpoint
3651       || bl->loc_type == bp_loc_hardware_breakpoint)
3652     {
3653       /* "Normal" instruction breakpoint: either the standard
3654          trap-instruction bp (bp_breakpoint), or a
3655          bp_hardware_breakpoint.  */
3656
3657       /* First check to see if we have to handle an overlay.  */
3658       if (overlay_debugging == ovly_off
3659           || bl->section == NULL
3660           || !(section_is_overlay (bl->section)))
3661         {
3662           /* No overlay handling: just remove the breakpoint.  */
3663
3664           /* If we're trying to uninsert a memory breakpoint that we
3665              know is set in a dynamic object that is marked
3666              shlib_disabled, then either the dynamic object was
3667              removed with "remove-symbol-file" or with
3668              "nosharedlibrary".  In the former case, we don't know
3669              whether another dynamic object might have loaded over the
3670              breakpoint's address -- the user might well let us know
3671              about it next with add-symbol-file (the whole point of
3672              add-symbol-file is letting the user manually maintain a
3673              list of dynamically loaded objects).  If we have the
3674              breakpoint's shadow memory, that is, this is a software
3675              breakpoint managed by GDB, check whether the breakpoint
3676              is still inserted in memory, to avoid overwriting wrong
3677              code with stale saved shadow contents.  Note that HW
3678              breakpoints don't have shadow memory, as they're
3679              implemented using a mechanism that is not dependent on
3680              being able to modify the target's memory, and as such
3681              they should always be removed.  */
3682           if (bl->shlib_disabled
3683               && bl->target_info.shadow_len != 0
3684               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3685             val = 0;
3686           else
3687             val = bl->owner->ops->remove_location (bl, reason);
3688         }
3689       else
3690         {
3691           /* This breakpoint is in an overlay section.
3692              Did we set a breakpoint at the LMA?  */
3693           if (!overlay_events_enabled)
3694               {
3695                 /* Yes -- overlay event support is not active, so we
3696                    should have set a breakpoint at the LMA.  Remove it.  
3697                 */
3698                 /* Ignore any failures: if the LMA is in ROM, we will
3699                    have already warned when we failed to insert it.  */
3700                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3701                   target_remove_hw_breakpoint (bl->gdbarch,
3702                                                &bl->overlay_target_info);
3703                 else
3704                   target_remove_breakpoint (bl->gdbarch,
3705                                             &bl->overlay_target_info,
3706                                             reason);
3707               }
3708           /* Did we set a breakpoint at the VMA? 
3709              If so, we will have marked the breakpoint 'inserted'.  */
3710           if (bl->inserted)
3711             {
3712               /* Yes -- remove it.  Previously we did not bother to
3713                  remove the breakpoint if the section had been
3714                  unmapped, but let's not rely on that being safe.  We
3715                  don't know what the overlay manager might do.  */
3716
3717               /* However, we should remove *software* breakpoints only
3718                  if the section is still mapped, or else we overwrite
3719                  wrong code with the saved shadow contents.  */
3720               if (bl->loc_type == bp_loc_hardware_breakpoint
3721                   || section_is_mapped (bl->section))
3722                 val = bl->owner->ops->remove_location (bl, reason);
3723               else
3724                 val = 0;
3725             }
3726           else
3727             {
3728               /* No -- not inserted, so no need to remove.  No error.  */
3729               val = 0;
3730             }
3731         }
3732
3733       /* In some cases, we might not be able to remove a breakpoint in
3734          a shared library that has already been removed, but we have
3735          not yet processed the shlib unload event.  Similarly for an
3736          unloaded add-symbol-file object - the user might not yet have
3737          had the chance to remove-symbol-file it.  shlib_disabled will
3738          be set if the library/object has already been removed, but
3739          the breakpoint hasn't been uninserted yet, e.g., after
3740          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3741          always-inserted mode.  */
3742       if (val
3743           && (bl->loc_type == bp_loc_software_breakpoint
3744               && (bl->shlib_disabled
3745                   || solib_name_from_address (bl->pspace, bl->address)
3746                   || shared_objfile_contains_address_p (bl->pspace,
3747                                                         bl->address))))
3748         val = 0;
3749
3750       if (val)
3751         return val;
3752       bl->inserted = (reason == DETACH_BREAKPOINT);
3753     }
3754   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3755     {
3756       gdb_assert (bl->owner->ops != NULL
3757                   && bl->owner->ops->remove_location != NULL);
3758
3759       bl->inserted = (reason == DETACH_BREAKPOINT);
3760       bl->owner->ops->remove_location (bl, reason);
3761
3762       /* Failure to remove any of the hardware watchpoints comes here.  */
3763       if (reason == REMOVE_BREAKPOINT && bl->inserted)
3764         warning (_("Could not remove hardware watchpoint %d."),
3765                  bl->owner->number);
3766     }
3767   else if (bl->owner->type == bp_catchpoint
3768            && breakpoint_enabled (bl->owner)
3769            && !bl->duplicate)
3770     {
3771       gdb_assert (bl->owner->ops != NULL
3772                   && bl->owner->ops->remove_location != NULL);
3773
3774       val = bl->owner->ops->remove_location (bl, reason);
3775       if (val)
3776         return val;
3777
3778       bl->inserted = (reason == DETACH_BREAKPOINT);
3779     }
3780
3781   return 0;
3782 }
3783
3784 static int
3785 remove_breakpoint (struct bp_location *bl)
3786 {
3787   /* BL is never in moribund_locations by our callers.  */
3788   gdb_assert (bl->owner != NULL);
3789
3790   /* The type of none suggests that owner is actually deleted.
3791      This should not ever happen.  */
3792   gdb_assert (bl->owner->type != bp_none);
3793
3794   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3795
3796   switch_to_program_space_and_thread (bl->pspace);
3797
3798   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
3799 }
3800
3801 /* Clear the "inserted" flag in all breakpoints.  */
3802
3803 void
3804 mark_breakpoints_out (void)
3805 {
3806   struct bp_location *bl, **blp_tmp;
3807
3808   ALL_BP_LOCATIONS (bl, blp_tmp)
3809     if (bl->pspace == current_program_space)
3810       bl->inserted = 0;
3811 }
3812
3813 /* Clear the "inserted" flag in all breakpoints and delete any
3814    breakpoints which should go away between runs of the program.
3815
3816    Plus other such housekeeping that has to be done for breakpoints
3817    between runs.
3818
3819    Note: this function gets called at the end of a run (by
3820    generic_mourn_inferior) and when a run begins (by
3821    init_wait_for_inferior).  */
3822
3823
3824
3825 void
3826 breakpoint_init_inferior (enum inf_context context)
3827 {
3828   struct breakpoint *b, *b_tmp;
3829   struct program_space *pspace = current_program_space;
3830
3831   /* If breakpoint locations are shared across processes, then there's
3832      nothing to do.  */
3833   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3834     return;
3835
3836   mark_breakpoints_out ();
3837
3838   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3839   {
3840     if (b->loc && b->loc->pspace != pspace)
3841       continue;
3842
3843     switch (b->type)
3844       {
3845       case bp_call_dummy:
3846       case bp_longjmp_call_dummy:
3847
3848         /* If the call dummy breakpoint is at the entry point it will
3849            cause problems when the inferior is rerun, so we better get
3850            rid of it.  */
3851
3852       case bp_watchpoint_scope:
3853
3854         /* Also get rid of scope breakpoints.  */
3855
3856       case bp_shlib_event:
3857
3858         /* Also remove solib event breakpoints.  Their addresses may
3859            have changed since the last time we ran the program.
3860            Actually we may now be debugging against different target;
3861            and so the solib backend that installed this breakpoint may
3862            not be used in by the target.  E.g.,
3863
3864            (gdb) file prog-linux
3865            (gdb) run               # native linux target
3866            ...
3867            (gdb) kill
3868            (gdb) file prog-win.exe
3869            (gdb) tar rem :9999     # remote Windows gdbserver.
3870         */
3871
3872       case bp_step_resume:
3873
3874         /* Also remove step-resume breakpoints.  */
3875
3876       case bp_single_step:
3877
3878         /* Also remove single-step breakpoints.  */
3879
3880         delete_breakpoint (b);
3881         break;
3882
3883       case bp_watchpoint:
3884       case bp_hardware_watchpoint:
3885       case bp_read_watchpoint:
3886       case bp_access_watchpoint:
3887         {
3888           struct watchpoint *w = (struct watchpoint *) b;
3889
3890           /* Likewise for watchpoints on local expressions.  */
3891           if (w->exp_valid_block != NULL)
3892             delete_breakpoint (b);
3893           else
3894             {
3895               /* Get rid of existing locations, which are no longer
3896                  valid.  New ones will be created in
3897                  update_watchpoint, when the inferior is restarted.
3898                  The next update_global_location_list call will
3899                  garbage collect them.  */
3900               b->loc = NULL;
3901
3902               if (context == inf_starting)
3903                 {
3904                   /* Reset val field to force reread of starting value in
3905                      insert_breakpoints.  */
3906                   w->val.reset (nullptr);
3907                   w->val_valid = 0;
3908                 }
3909             }
3910         }
3911         break;
3912       default:
3913         break;
3914       }
3915   }
3916
3917   /* Get rid of the moribund locations.  */
3918   for (bp_location *bl : moribund_locations)
3919     decref_bp_location (&bl);
3920   moribund_locations.clear ();
3921 }
3922
3923 /* These functions concern about actual breakpoints inserted in the
3924    target --- to e.g. check if we need to do decr_pc adjustment or if
3925    we need to hop over the bkpt --- so we check for address space
3926    match, not program space.  */
3927
3928 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3929    exists at PC.  It returns ordinary_breakpoint_here if it's an
3930    ordinary breakpoint, or permanent_breakpoint_here if it's a
3931    permanent breakpoint.
3932    - When continuing from a location with an ordinary breakpoint, we
3933      actually single step once before calling insert_breakpoints.
3934    - When continuing from a location with a permanent breakpoint, we
3935      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3936      the target, to advance the PC past the breakpoint.  */
3937
3938 enum breakpoint_here
3939 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
3940 {
3941   struct bp_location *bl, **blp_tmp;
3942   int any_breakpoint_here = 0;
3943
3944   ALL_BP_LOCATIONS (bl, blp_tmp)
3945     {
3946       if (bl->loc_type != bp_loc_software_breakpoint
3947           && bl->loc_type != bp_loc_hardware_breakpoint)
3948         continue;
3949
3950       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3951       if ((breakpoint_enabled (bl->owner)
3952            || bl->permanent)
3953           && breakpoint_location_address_match (bl, aspace, pc))
3954         {
3955           if (overlay_debugging 
3956               && section_is_overlay (bl->section)
3957               && !section_is_mapped (bl->section))
3958             continue;           /* unmapped overlay -- can't be a match */
3959           else if (bl->permanent)
3960             return permanent_breakpoint_here;
3961           else
3962             any_breakpoint_here = 1;
3963         }
3964     }
3965
3966   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
3967 }
3968
3969 /* See breakpoint.h.  */
3970
3971 int
3972 breakpoint_in_range_p (const address_space *aspace,
3973                        CORE_ADDR addr, ULONGEST len)
3974 {
3975   struct bp_location *bl, **blp_tmp;
3976
3977   ALL_BP_LOCATIONS (bl, blp_tmp)
3978     {
3979       if (bl->loc_type != bp_loc_software_breakpoint
3980           && bl->loc_type != bp_loc_hardware_breakpoint)
3981         continue;
3982
3983       if ((breakpoint_enabled (bl->owner)
3984            || bl->permanent)
3985           && breakpoint_location_address_range_overlap (bl, aspace,
3986                                                         addr, len))
3987         {
3988           if (overlay_debugging
3989               && section_is_overlay (bl->section)
3990               && !section_is_mapped (bl->section))
3991             {
3992               /* Unmapped overlay -- can't be a match.  */
3993               continue;
3994             }
3995
3996           return 1;
3997         }
3998     }
3999
4000   return 0;
4001 }
4002
4003 /* Return true if there's a moribund breakpoint at PC.  */
4004
4005 int
4006 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4007 {
4008   for (bp_location *loc : moribund_locations)
4009     if (breakpoint_location_address_match (loc, aspace, pc))
4010       return 1;
4011
4012   return 0;
4013 }
4014
4015 /* Returns non-zero iff BL is inserted at PC, in address space
4016    ASPACE.  */
4017
4018 static int
4019 bp_location_inserted_here_p (struct bp_location *bl,
4020                              const address_space *aspace, CORE_ADDR pc)
4021 {
4022   if (bl->inserted
4023       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4024                                    aspace, pc))
4025     {
4026       if (overlay_debugging
4027           && section_is_overlay (bl->section)
4028           && !section_is_mapped (bl->section))
4029         return 0;               /* unmapped overlay -- can't be a match */
4030       else
4031         return 1;
4032     }
4033   return 0;
4034 }
4035
4036 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4037
4038 int
4039 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4040 {
4041   struct bp_location **blp, **blp_tmp = NULL;
4042
4043   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4044     {
4045       struct bp_location *bl = *blp;
4046
4047       if (bl->loc_type != bp_loc_software_breakpoint
4048           && bl->loc_type != bp_loc_hardware_breakpoint)
4049         continue;
4050
4051       if (bp_location_inserted_here_p (bl, aspace, pc))
4052         return 1;
4053     }
4054   return 0;
4055 }
4056
4057 /* This function returns non-zero iff there is a software breakpoint
4058    inserted at PC.  */
4059
4060 int
4061 software_breakpoint_inserted_here_p (const address_space *aspace,
4062                                      CORE_ADDR pc)
4063 {
4064   struct bp_location **blp, **blp_tmp = NULL;
4065
4066   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4067     {
4068       struct bp_location *bl = *blp;
4069
4070       if (bl->loc_type != bp_loc_software_breakpoint)
4071         continue;
4072
4073       if (bp_location_inserted_here_p (bl, aspace, pc))
4074         return 1;
4075     }
4076
4077   return 0;
4078 }
4079
4080 /* See breakpoint.h.  */
4081
4082 int
4083 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4084                                      CORE_ADDR pc)
4085 {
4086   struct bp_location **blp, **blp_tmp = NULL;
4087
4088   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4089     {
4090       struct bp_location *bl = *blp;
4091
4092       if (bl->loc_type != bp_loc_hardware_breakpoint)
4093         continue;
4094
4095       if (bp_location_inserted_here_p (bl, aspace, pc))
4096         return 1;
4097     }
4098
4099   return 0;
4100 }
4101
4102 int
4103 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4104                                        CORE_ADDR addr, ULONGEST len)
4105 {
4106   struct breakpoint *bpt;
4107
4108   ALL_BREAKPOINTS (bpt)
4109     {
4110       struct bp_location *loc;
4111
4112       if (bpt->type != bp_hardware_watchpoint
4113           && bpt->type != bp_access_watchpoint)
4114         continue;
4115
4116       if (!breakpoint_enabled (bpt))
4117         continue;
4118
4119       for (loc = bpt->loc; loc; loc = loc->next)
4120         if (loc->pspace->aspace == aspace && loc->inserted)
4121           {
4122             CORE_ADDR l, h;
4123
4124             /* Check for intersection.  */
4125             l = std::max<CORE_ADDR> (loc->address, addr);
4126             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4127             if (l < h)
4128               return 1;
4129           }
4130     }
4131   return 0;
4132 }
4133 \f
4134
4135 /* bpstat stuff.  External routines' interfaces are documented
4136    in breakpoint.h.  */
4137
4138 int
4139 is_catchpoint (struct breakpoint *ep)
4140 {
4141   return (ep->type == bp_catchpoint);
4142 }
4143
4144 /* Frees any storage that is part of a bpstat.  Does not walk the
4145    'next' chain.  */
4146
4147 bpstats::~bpstats ()
4148 {
4149   if (bp_location_at != NULL)
4150     decref_bp_location (&bp_location_at);
4151 }
4152
4153 /* Clear a bpstat so that it says we are not at any breakpoint.
4154    Also free any storage that is part of a bpstat.  */
4155
4156 void
4157 bpstat_clear (bpstat *bsp)
4158 {
4159   bpstat p;
4160   bpstat q;
4161
4162   if (bsp == 0)
4163     return;
4164   p = *bsp;
4165   while (p != NULL)
4166     {
4167       q = p->next;
4168       delete p;
4169       p = q;
4170     }
4171   *bsp = NULL;
4172 }
4173
4174 bpstats::bpstats (const bpstats &other)
4175   : next (NULL),
4176     bp_location_at (other.bp_location_at),
4177     breakpoint_at (other.breakpoint_at),
4178     commands (other.commands),
4179     print (other.print),
4180     stop (other.stop),
4181     print_it (other.print_it)
4182 {
4183   if (other.old_val != NULL)
4184     old_val = release_value (value_copy (other.old_val.get ()));
4185   incref_bp_location (bp_location_at);
4186 }
4187
4188 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4189    is part of the bpstat is copied as well.  */
4190
4191 bpstat
4192 bpstat_copy (bpstat bs)
4193 {
4194   bpstat p = NULL;
4195   bpstat tmp;
4196   bpstat retval = NULL;
4197
4198   if (bs == NULL)
4199     return bs;
4200
4201   for (; bs != NULL; bs = bs->next)
4202     {
4203       tmp = new bpstats (*bs);
4204
4205       if (p == NULL)
4206         /* This is the first thing in the chain.  */
4207         retval = tmp;
4208       else
4209         p->next = tmp;
4210       p = tmp;
4211     }
4212   p->next = NULL;
4213   return retval;
4214 }
4215
4216 /* Find the bpstat associated with this breakpoint.  */
4217
4218 bpstat
4219 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4220 {
4221   if (bsp == NULL)
4222     return NULL;
4223
4224   for (; bsp != NULL; bsp = bsp->next)
4225     {
4226       if (bsp->breakpoint_at == breakpoint)
4227         return bsp;
4228     }
4229   return NULL;
4230 }
4231
4232 /* See breakpoint.h.  */
4233
4234 int
4235 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4236 {
4237   for (; bsp != NULL; bsp = bsp->next)
4238     {
4239       if (bsp->breakpoint_at == NULL)
4240         {
4241           /* A moribund location can never explain a signal other than
4242              GDB_SIGNAL_TRAP.  */
4243           if (sig == GDB_SIGNAL_TRAP)
4244             return 1;
4245         }
4246       else
4247         {
4248           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4249                                                         sig))
4250             return 1;
4251         }
4252     }
4253
4254   return 0;
4255 }
4256
4257 /* Put in *NUM the breakpoint number of the first breakpoint we are
4258    stopped at.  *BSP upon return is a bpstat which points to the
4259    remaining breakpoints stopped at (but which is not guaranteed to be
4260    good for anything but further calls to bpstat_num).
4261
4262    Return 0 if passed a bpstat which does not indicate any breakpoints.
4263    Return -1 if stopped at a breakpoint that has been deleted since
4264    we set it.
4265    Return 1 otherwise.  */
4266
4267 int
4268 bpstat_num (bpstat *bsp, int *num)
4269 {
4270   struct breakpoint *b;
4271
4272   if ((*bsp) == NULL)
4273     return 0;                   /* No more breakpoint values */
4274
4275   /* We assume we'll never have several bpstats that correspond to a
4276      single breakpoint -- otherwise, this function might return the
4277      same number more than once and this will look ugly.  */
4278   b = (*bsp)->breakpoint_at;
4279   *bsp = (*bsp)->next;
4280   if (b == NULL)
4281     return -1;                  /* breakpoint that's been deleted since */
4282
4283   *num = b->number;             /* We have its number */
4284   return 1;
4285 }
4286
4287 /* See breakpoint.h.  */
4288
4289 void
4290 bpstat_clear_actions (void)
4291 {
4292   bpstat bs;
4293
4294   if (inferior_ptid == null_ptid)
4295     return;
4296
4297   thread_info *tp = inferior_thread ();
4298   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4299     {
4300       bs->commands = NULL;
4301       bs->old_val.reset (nullptr);
4302     }
4303 }
4304
4305 /* Called when a command is about to proceed the inferior.  */
4306
4307 static void
4308 breakpoint_about_to_proceed (void)
4309 {
4310   if (inferior_ptid != null_ptid)
4311     {
4312       struct thread_info *tp = inferior_thread ();
4313
4314       /* Allow inferior function calls in breakpoint commands to not
4315          interrupt the command list.  When the call finishes
4316          successfully, the inferior will be standing at the same
4317          breakpoint as if nothing happened.  */
4318       if (tp->control.in_infcall)
4319         return;
4320     }
4321
4322   breakpoint_proceeded = 1;
4323 }
4324
4325 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4326    or its equivalent.  */
4327
4328 static int
4329 command_line_is_silent (struct command_line *cmd)
4330 {
4331   return cmd && (strcmp ("silent", cmd->line) == 0);
4332 }
4333
4334 /* Execute all the commands associated with all the breakpoints at
4335    this location.  Any of these commands could cause the process to
4336    proceed beyond this point, etc.  We look out for such changes by
4337    checking the global "breakpoint_proceeded" after each command.
4338
4339    Returns true if a breakpoint command resumed the inferior.  In that
4340    case, it is the caller's responsibility to recall it again with the
4341    bpstat of the current thread.  */
4342
4343 static int
4344 bpstat_do_actions_1 (bpstat *bsp)
4345 {
4346   bpstat bs;
4347   int again = 0;
4348
4349   /* Avoid endless recursion if a `source' command is contained
4350      in bs->commands.  */
4351   if (executing_breakpoint_commands)
4352     return 0;
4353
4354   scoped_restore save_executing
4355     = make_scoped_restore (&executing_breakpoint_commands, 1);
4356
4357   scoped_restore preventer = prevent_dont_repeat ();
4358
4359   /* This pointer will iterate over the list of bpstat's.  */
4360   bs = *bsp;
4361
4362   breakpoint_proceeded = 0;
4363   for (; bs != NULL; bs = bs->next)
4364     {
4365       struct command_line *cmd = NULL;
4366
4367       /* Take ownership of the BSP's command tree, if it has one.
4368
4369          The command tree could legitimately contain commands like
4370          'step' and 'next', which call clear_proceed_status, which
4371          frees stop_bpstat's command tree.  To make sure this doesn't
4372          free the tree we're executing out from under us, we need to
4373          take ownership of the tree ourselves.  Since a given bpstat's
4374          commands are only executed once, we don't need to copy it; we
4375          can clear the pointer in the bpstat, and make sure we free
4376          the tree when we're done.  */
4377       counted_command_line ccmd = bs->commands;
4378       bs->commands = NULL;
4379       if (ccmd != NULL)
4380         cmd = ccmd.get ();
4381       if (command_line_is_silent (cmd))
4382         {
4383           /* The action has been already done by bpstat_stop_status.  */
4384           cmd = cmd->next;
4385         }
4386
4387       while (cmd != NULL)
4388         {
4389           execute_control_command (cmd);
4390
4391           if (breakpoint_proceeded)
4392             break;
4393           else
4394             cmd = cmd->next;
4395         }
4396
4397       if (breakpoint_proceeded)
4398         {
4399           if (current_ui->async)
4400             /* If we are in async mode, then the target might be still
4401                running, not stopped at any breakpoint, so nothing for
4402                us to do here -- just return to the event loop.  */
4403             ;
4404           else
4405             /* In sync mode, when execute_control_command returns
4406                we're already standing on the next breakpoint.
4407                Breakpoint commands for that stop were not run, since
4408                execute_command does not run breakpoint commands --
4409                only command_line_handler does, but that one is not
4410                involved in execution of breakpoint commands.  So, we
4411                can now execute breakpoint commands.  It should be
4412                noted that making execute_command do bpstat actions is
4413                not an option -- in this case we'll have recursive
4414                invocation of bpstat for each breakpoint with a
4415                command, and can easily blow up GDB stack.  Instead, we
4416                return true, which will trigger the caller to recall us
4417                with the new stop_bpstat.  */
4418             again = 1;
4419           break;
4420         }
4421     }
4422   return again;
4423 }
4424
4425 /* Helper for bpstat_do_actions.  Get the current thread, if there's
4426    one, is alive and has execution.  Return NULL otherwise.  */
4427
4428 static thread_info *
4429 get_bpstat_thread ()
4430 {
4431   if (inferior_ptid == null_ptid || !target_has_execution)
4432     return NULL;
4433
4434   thread_info *tp = inferior_thread ();
4435   if (tp->state == THREAD_EXITED || tp->executing)
4436     return NULL;
4437   return tp;
4438 }
4439
4440 void
4441 bpstat_do_actions (void)
4442 {
4443   auto cleanup_if_error = make_scope_exit (bpstat_clear_actions);
4444   thread_info *tp;
4445
4446   /* Do any commands attached to breakpoint we are stopped at.  */
4447   while ((tp = get_bpstat_thread ()) != NULL)
4448     {
4449       /* Since in sync mode, bpstat_do_actions may resume the
4450          inferior, and only return when it is stopped at the next
4451          breakpoint, we keep doing breakpoint actions until it returns
4452          false to indicate the inferior was not resumed.  */
4453       if (!bpstat_do_actions_1 (&tp->control.stop_bpstat))
4454         break;
4455     }
4456
4457   cleanup_if_error.release ();
4458 }
4459
4460 /* Print out the (old or new) value associated with a watchpoint.  */
4461
4462 static void
4463 watchpoint_value_print (struct value *val, struct ui_file *stream)
4464 {
4465   if (val == NULL)
4466     fprintf_unfiltered (stream, _("<unreadable>"));
4467   else
4468     {
4469       struct value_print_options opts;
4470       get_user_print_options (&opts);
4471       value_print (val, stream, &opts);
4472     }
4473 }
4474
4475 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4476    debugging multiple threads.  */
4477
4478 void
4479 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4480 {
4481   if (uiout->is_mi_like_p ())
4482     return;
4483
4484   uiout->text ("\n");
4485
4486   if (show_thread_that_caused_stop ())
4487     {
4488       const char *name;
4489       struct thread_info *thr = inferior_thread ();
4490
4491       uiout->text ("Thread ");
4492       uiout->field_fmt ("thread-id", "%s", print_thread_id (thr));
4493
4494       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4495       if (name != NULL)
4496         {
4497           uiout->text (" \"");
4498           uiout->field_fmt ("name", "%s", name);
4499           uiout->text ("\"");
4500         }
4501
4502       uiout->text (" hit ");
4503     }
4504 }
4505
4506 /* Generic routine for printing messages indicating why we
4507    stopped.  The behavior of this function depends on the value
4508    'print_it' in the bpstat structure.  Under some circumstances we
4509    may decide not to print anything here and delegate the task to
4510    normal_stop().  */
4511
4512 static enum print_stop_action
4513 print_bp_stop_message (bpstat bs)
4514 {
4515   switch (bs->print_it)
4516     {
4517     case print_it_noop:
4518       /* Nothing should be printed for this bpstat entry.  */
4519       return PRINT_UNKNOWN;
4520       break;
4521
4522     case print_it_done:
4523       /* We still want to print the frame, but we already printed the
4524          relevant messages.  */
4525       return PRINT_SRC_AND_LOC;
4526       break;
4527
4528     case print_it_normal:
4529       {
4530         struct breakpoint *b = bs->breakpoint_at;
4531
4532         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4533            which has since been deleted.  */
4534         if (b == NULL)
4535           return PRINT_UNKNOWN;
4536
4537         /* Normal case.  Call the breakpoint's print_it method.  */
4538         return b->ops->print_it (bs);
4539       }
4540       break;
4541
4542     default:
4543       internal_error (__FILE__, __LINE__,
4544                       _("print_bp_stop_message: unrecognized enum value"));
4545       break;
4546     }
4547 }
4548
4549 /* A helper function that prints a shared library stopped event.  */
4550
4551 static void
4552 print_solib_event (int is_catchpoint)
4553 {
4554   bool any_deleted = !current_program_space->deleted_solibs.empty ();
4555   bool any_added = !current_program_space->added_solibs.empty ();
4556
4557   if (!is_catchpoint)
4558     {
4559       if (any_added || any_deleted)
4560         current_uiout->text (_("Stopped due to shared library event:\n"));
4561       else
4562         current_uiout->text (_("Stopped due to shared library event (no "
4563                                "libraries added or removed)\n"));
4564     }
4565
4566   if (current_uiout->is_mi_like_p ())
4567     current_uiout->field_string ("reason",
4568                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4569
4570   if (any_deleted)
4571     {
4572       current_uiout->text (_("  Inferior unloaded "));
4573       ui_out_emit_list list_emitter (current_uiout, "removed");
4574       for (int ix = 0; ix < current_program_space->deleted_solibs.size (); ix++)
4575         {
4576           const std::string &name = current_program_space->deleted_solibs[ix];
4577
4578           if (ix > 0)
4579             current_uiout->text ("    ");
4580           current_uiout->field_string ("library", name);
4581           current_uiout->text ("\n");
4582         }
4583     }
4584
4585   if (any_added)
4586     {
4587       current_uiout->text (_("  Inferior loaded "));
4588       ui_out_emit_list list_emitter (current_uiout, "added");
4589       bool first = true;
4590       for (so_list *iter : current_program_space->added_solibs)
4591         {
4592           if (!first)
4593             current_uiout->text ("    ");
4594           first = false;
4595           current_uiout->field_string ("library", iter->so_name);
4596           current_uiout->text ("\n");
4597         }
4598     }
4599 }
4600
4601 /* Print a message indicating what happened.  This is called from
4602    normal_stop().  The input to this routine is the head of the bpstat
4603    list - a list of the eventpoints that caused this stop.  KIND is
4604    the target_waitkind for the stopping event.  This
4605    routine calls the generic print routine for printing a message
4606    about reasons for stopping.  This will print (for example) the
4607    "Breakpoint n," part of the output.  The return value of this
4608    routine is one of:
4609
4610    PRINT_UNKNOWN: Means we printed nothing.
4611    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4612    code to print the location.  An example is 
4613    "Breakpoint 1, " which should be followed by
4614    the location.
4615    PRINT_SRC_ONLY: Means we printed something, but there is no need
4616    to also print the location part of the message.
4617    An example is the catch/throw messages, which
4618    don't require a location appended to the end.
4619    PRINT_NOTHING: We have done some printing and we don't need any 
4620    further info to be printed.  */
4621
4622 enum print_stop_action
4623 bpstat_print (bpstat bs, int kind)
4624 {
4625   enum print_stop_action val;
4626
4627   /* Maybe another breakpoint in the chain caused us to stop.
4628      (Currently all watchpoints go on the bpstat whether hit or not.
4629      That probably could (should) be changed, provided care is taken
4630      with respect to bpstat_explains_signal).  */
4631   for (; bs; bs = bs->next)
4632     {
4633       val = print_bp_stop_message (bs);
4634       if (val == PRINT_SRC_ONLY 
4635           || val == PRINT_SRC_AND_LOC 
4636           || val == PRINT_NOTHING)
4637         return val;
4638     }
4639
4640   /* If we had hit a shared library event breakpoint,
4641      print_bp_stop_message would print out this message.  If we hit an
4642      OS-level shared library event, do the same thing.  */
4643   if (kind == TARGET_WAITKIND_LOADED)
4644     {
4645       print_solib_event (0);
4646       return PRINT_NOTHING;
4647     }
4648
4649   /* We reached the end of the chain, or we got a null BS to start
4650      with and nothing was printed.  */
4651   return PRINT_UNKNOWN;
4652 }
4653
4654 /* Evaluate the boolean expression EXP and return the result.  */
4655
4656 static bool
4657 breakpoint_cond_eval (expression *exp)
4658 {
4659   struct value *mark = value_mark ();
4660   bool res = value_true (evaluate_expression (exp));
4661
4662   value_free_to_mark (mark);
4663   return res;
4664 }
4665
4666 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4667
4668 bpstats::bpstats (struct bp_location *bl, bpstat **bs_link_pointer)
4669   : next (NULL),
4670     bp_location_at (bl),
4671     breakpoint_at (bl->owner),
4672     commands (NULL),
4673     print (0),
4674     stop (0),
4675     print_it (print_it_normal)
4676 {
4677   incref_bp_location (bl);
4678   **bs_link_pointer = this;
4679   *bs_link_pointer = &next;
4680 }
4681
4682 bpstats::bpstats ()
4683   : next (NULL),
4684     bp_location_at (NULL),
4685     breakpoint_at (NULL),
4686     commands (NULL),
4687     print (0),
4688     stop (0),
4689     print_it (print_it_normal)
4690 {
4691 }
4692 \f
4693 /* The target has stopped with waitstatus WS.  Check if any hardware
4694    watchpoints have triggered, according to the target.  */
4695
4696 int
4697 watchpoints_triggered (struct target_waitstatus *ws)
4698 {
4699   bool stopped_by_watchpoint = target_stopped_by_watchpoint ();
4700   CORE_ADDR addr;
4701   struct breakpoint *b;
4702
4703   if (!stopped_by_watchpoint)
4704     {
4705       /* We were not stopped by a watchpoint.  Mark all watchpoints
4706          as not triggered.  */
4707       ALL_BREAKPOINTS (b)
4708         if (is_hardware_watchpoint (b))
4709           {
4710             struct watchpoint *w = (struct watchpoint *) b;
4711
4712             w->watchpoint_triggered = watch_triggered_no;
4713           }
4714
4715       return 0;
4716     }
4717
4718   if (!target_stopped_data_address (current_top_target (), &addr))
4719     {
4720       /* We were stopped by a watchpoint, but we don't know where.
4721          Mark all watchpoints as unknown.  */
4722       ALL_BREAKPOINTS (b)
4723         if (is_hardware_watchpoint (b))
4724           {
4725             struct watchpoint *w = (struct watchpoint *) b;
4726
4727             w->watchpoint_triggered = watch_triggered_unknown;
4728           }
4729
4730       return 1;
4731     }
4732
4733   /* The target could report the data address.  Mark watchpoints
4734      affected by this data address as triggered, and all others as not
4735      triggered.  */
4736
4737   ALL_BREAKPOINTS (b)
4738     if (is_hardware_watchpoint (b))
4739       {
4740         struct watchpoint *w = (struct watchpoint *) b;
4741         struct bp_location *loc;
4742
4743         w->watchpoint_triggered = watch_triggered_no;
4744         for (loc = b->loc; loc; loc = loc->next)
4745           {
4746             if (is_masked_watchpoint (b))
4747               {
4748                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4749                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4750
4751                 if (newaddr == start)
4752                   {
4753                     w->watchpoint_triggered = watch_triggered_yes;
4754                     break;
4755                   }
4756               }
4757             /* Exact match not required.  Within range is sufficient.  */
4758             else if (target_watchpoint_addr_within_range (current_top_target (),
4759                                                          addr, loc->address,
4760                                                          loc->length))
4761               {
4762                 w->watchpoint_triggered = watch_triggered_yes;
4763                 break;
4764               }
4765           }
4766       }
4767
4768   return 1;
4769 }
4770
4771 /* Possible return values for watchpoint_check.  */
4772 enum wp_check_result
4773   {
4774     /* The watchpoint has been deleted.  */
4775     WP_DELETED = 1,
4776
4777     /* The value has changed.  */
4778     WP_VALUE_CHANGED = 2,
4779
4780     /* The value has not changed.  */
4781     WP_VALUE_NOT_CHANGED = 3,
4782
4783     /* Ignore this watchpoint, no matter if the value changed or not.  */
4784     WP_IGNORE = 4,
4785   };
4786
4787 #define BP_TEMPFLAG 1
4788 #define BP_HARDWAREFLAG 2
4789
4790 /* Evaluate watchpoint condition expression and check if its value
4791    changed.  */
4792
4793 static wp_check_result
4794 watchpoint_check (bpstat bs)
4795 {
4796   struct watchpoint *b;
4797   struct frame_info *fr;
4798   int within_current_scope;
4799
4800   /* BS is built from an existing struct breakpoint.  */
4801   gdb_assert (bs->breakpoint_at != NULL);
4802   b = (struct watchpoint *) bs->breakpoint_at;
4803
4804   /* If this is a local watchpoint, we only want to check if the
4805      watchpoint frame is in scope if the current thread is the thread
4806      that was used to create the watchpoint.  */
4807   if (!watchpoint_in_thread_scope (b))
4808     return WP_IGNORE;
4809
4810   if (b->exp_valid_block == NULL)
4811     within_current_scope = 1;
4812   else
4813     {
4814       struct frame_info *frame = get_current_frame ();
4815       struct gdbarch *frame_arch = get_frame_arch (frame);
4816       CORE_ADDR frame_pc = get_frame_pc (frame);
4817
4818       /* stack_frame_destroyed_p() returns a non-zero value if we're
4819          still in the function but the stack frame has already been
4820          invalidated.  Since we can't rely on the values of local
4821          variables after the stack has been destroyed, we are treating
4822          the watchpoint in that state as `not changed' without further
4823          checking.  Don't mark watchpoints as changed if the current
4824          frame is in an epilogue - even if they are in some other
4825          frame, our view of the stack is likely to be wrong and
4826          frame_find_by_id could error out.  */
4827       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
4828         return WP_IGNORE;
4829
4830       fr = frame_find_by_id (b->watchpoint_frame);
4831       within_current_scope = (fr != NULL);
4832
4833       /* If we've gotten confused in the unwinder, we might have
4834          returned a frame that can't describe this variable.  */
4835       if (within_current_scope)
4836         {
4837           struct symbol *function;
4838
4839           function = get_frame_function (fr);
4840           if (function == NULL
4841               || !contained_in (b->exp_valid_block,
4842                                 SYMBOL_BLOCK_VALUE (function)))
4843             within_current_scope = 0;
4844         }
4845
4846       if (within_current_scope)
4847         /* If we end up stopping, the current frame will get selected
4848            in normal_stop.  So this call to select_frame won't affect
4849            the user.  */
4850         select_frame (fr);
4851     }
4852
4853   if (within_current_scope)
4854     {
4855       /* We use value_{,free_to_}mark because it could be a *long*
4856          time before we return to the command level and call
4857          free_all_values.  We can't call free_all_values because we
4858          might be in the middle of evaluating a function call.  */
4859
4860       int pc = 0;
4861       struct value *mark;
4862       struct value *new_val;
4863
4864       if (is_masked_watchpoint (b))
4865         /* Since we don't know the exact trigger address (from
4866            stopped_data_address), just tell the user we've triggered
4867            a mask watchpoint.  */
4868         return WP_VALUE_CHANGED;
4869
4870       mark = value_mark ();
4871       fetch_subexp_value (b->exp.get (), &pc, &new_val, NULL, NULL, 0);
4872
4873       if (b->val_bitsize != 0)
4874         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
4875
4876       /* We use value_equal_contents instead of value_equal because
4877          the latter coerces an array to a pointer, thus comparing just
4878          the address of the array instead of its contents.  This is
4879          not what we want.  */
4880       if ((b->val != NULL) != (new_val != NULL)
4881           || (b->val != NULL && !value_equal_contents (b->val.get (),
4882                                                        new_val)))
4883         {
4884           bs->old_val = b->val;
4885           b->val = release_value (new_val);
4886           b->val_valid = 1;
4887           if (new_val != NULL)
4888             value_free_to_mark (mark);
4889           return WP_VALUE_CHANGED;
4890         }
4891       else
4892         {
4893           /* Nothing changed.  */
4894           value_free_to_mark (mark);
4895           return WP_VALUE_NOT_CHANGED;
4896         }
4897     }
4898   else
4899     {
4900       /* This seems like the only logical thing to do because
4901          if we temporarily ignored the watchpoint, then when
4902          we reenter the block in which it is valid it contains
4903          garbage (in the case of a function, it may have two
4904          garbage values, one before and one after the prologue).
4905          So we can't even detect the first assignment to it and
4906          watch after that (since the garbage may or may not equal
4907          the first value assigned).  */
4908       /* We print all the stop information in
4909          breakpoint_ops->print_it, but in this case, by the time we
4910          call breakpoint_ops->print_it this bp will be deleted
4911          already.  So we have no choice but print the information
4912          here.  */
4913
4914       SWITCH_THRU_ALL_UIS ()
4915         {
4916           struct ui_out *uiout = current_uiout;
4917
4918           if (uiout->is_mi_like_p ())
4919             uiout->field_string
4920               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4921           uiout->text ("\nWatchpoint ");
4922           uiout->field_int ("wpnum", b->number);
4923           uiout->text (" deleted because the program has left the block in\n"
4924                        "which its expression is valid.\n");
4925         }
4926
4927       /* Make sure the watchpoint's commands aren't executed.  */
4928       b->commands = NULL;
4929       watchpoint_del_at_next_stop (b);
4930
4931       return WP_DELETED;
4932     }
4933 }
4934
4935 /* Return true if it looks like target has stopped due to hitting
4936    breakpoint location BL.  This function does not check if we should
4937    stop, only if BL explains the stop.  */
4938
4939 static int
4940 bpstat_check_location (const struct bp_location *bl,
4941                        const address_space *aspace, CORE_ADDR bp_addr,
4942                        const struct target_waitstatus *ws)
4943 {
4944   struct breakpoint *b = bl->owner;
4945
4946   /* BL is from an existing breakpoint.  */
4947   gdb_assert (b != NULL);
4948
4949   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4950 }
4951
4952 /* Determine if the watched values have actually changed, and we
4953    should stop.  If not, set BS->stop to 0.  */
4954
4955 static void
4956 bpstat_check_watchpoint (bpstat bs)
4957 {
4958   const struct bp_location *bl;
4959   struct watchpoint *b;
4960
4961   /* BS is built for existing struct breakpoint.  */
4962   bl = bs->bp_location_at;
4963   gdb_assert (bl != NULL);
4964   b = (struct watchpoint *) bs->breakpoint_at;
4965   gdb_assert (b != NULL);
4966
4967     {
4968       int must_check_value = 0;
4969       
4970       if (b->type == bp_watchpoint)
4971         /* For a software watchpoint, we must always check the
4972            watched value.  */
4973         must_check_value = 1;
4974       else if (b->watchpoint_triggered == watch_triggered_yes)
4975         /* We have a hardware watchpoint (read, write, or access)
4976            and the target earlier reported an address watched by
4977            this watchpoint.  */
4978         must_check_value = 1;
4979       else if (b->watchpoint_triggered == watch_triggered_unknown
4980                && b->type == bp_hardware_watchpoint)
4981         /* We were stopped by a hardware watchpoint, but the target could
4982            not report the data address.  We must check the watchpoint's
4983            value.  Access and read watchpoints are out of luck; without
4984            a data address, we can't figure it out.  */
4985         must_check_value = 1;
4986
4987       if (must_check_value)
4988         {
4989           wp_check_result e;
4990
4991           try
4992             {
4993               e = watchpoint_check (bs);
4994             }
4995           catch (const gdb_exception &ex)
4996             {
4997               exception_fprintf (gdb_stderr, ex,
4998                                  "Error evaluating expression "
4999                                  "for watchpoint %d\n",
5000                                  b->number);
5001
5002               SWITCH_THRU_ALL_UIS ()
5003                 {
5004                   printf_filtered (_("Watchpoint %d deleted.\n"),
5005                                    b->number);
5006                 }
5007               watchpoint_del_at_next_stop (b);
5008               e = WP_DELETED;
5009             }
5010
5011           switch (e)
5012             {
5013             case WP_DELETED:
5014               /* We've already printed what needs to be printed.  */
5015               bs->print_it = print_it_done;
5016               /* Stop.  */
5017               break;
5018             case WP_IGNORE:
5019               bs->print_it = print_it_noop;
5020               bs->stop = 0;
5021               break;
5022             case WP_VALUE_CHANGED:
5023               if (b->type == bp_read_watchpoint)
5024                 {
5025                   /* There are two cases to consider here:
5026
5027                      1. We're watching the triggered memory for reads.
5028                      In that case, trust the target, and always report
5029                      the watchpoint hit to the user.  Even though
5030                      reads don't cause value changes, the value may
5031                      have changed since the last time it was read, and
5032                      since we're not trapping writes, we will not see
5033                      those, and as such we should ignore our notion of
5034                      old value.
5035
5036                      2. We're watching the triggered memory for both
5037                      reads and writes.  There are two ways this may
5038                      happen:
5039
5040                      2.1. This is a target that can't break on data
5041                      reads only, but can break on accesses (reads or
5042                      writes), such as e.g., x86.  We detect this case
5043                      at the time we try to insert read watchpoints.
5044
5045                      2.2. Otherwise, the target supports read
5046                      watchpoints, but, the user set an access or write
5047                      watchpoint watching the same memory as this read
5048                      watchpoint.
5049
5050                      If we're watching memory writes as well as reads,
5051                      ignore watchpoint hits when we find that the
5052                      value hasn't changed, as reads don't cause
5053                      changes.  This still gives false positives when
5054                      the program writes the same value to memory as
5055                      what there was already in memory (we will confuse
5056                      it for a read), but it's much better than
5057                      nothing.  */
5058
5059                   int other_write_watchpoint = 0;
5060
5061                   if (bl->watchpoint_type == hw_read)
5062                     {
5063                       struct breakpoint *other_b;
5064
5065                       ALL_BREAKPOINTS (other_b)
5066                         if (other_b->type == bp_hardware_watchpoint
5067                             || other_b->type == bp_access_watchpoint)
5068                           {
5069                             struct watchpoint *other_w =
5070                               (struct watchpoint *) other_b;
5071
5072                             if (other_w->watchpoint_triggered
5073                                 == watch_triggered_yes)
5074                               {
5075                                 other_write_watchpoint = 1;
5076                                 break;
5077                               }
5078                           }
5079                     }
5080
5081                   if (other_write_watchpoint
5082                       || bl->watchpoint_type == hw_access)
5083                     {
5084                       /* We're watching the same memory for writes,
5085                          and the value changed since the last time we
5086                          updated it, so this trap must be for a write.
5087                          Ignore it.  */
5088                       bs->print_it = print_it_noop;
5089                       bs->stop = 0;
5090                     }
5091                 }
5092               break;
5093             case WP_VALUE_NOT_CHANGED:
5094               if (b->type == bp_hardware_watchpoint
5095                   || b->type == bp_watchpoint)
5096                 {
5097                   /* Don't stop: write watchpoints shouldn't fire if
5098                      the value hasn't changed.  */
5099                   bs->print_it = print_it_noop;
5100                   bs->stop = 0;
5101                 }
5102               /* Stop.  */
5103               break;
5104             default:
5105               /* Can't happen.  */
5106               break;
5107             }
5108         }
5109       else      /* must_check_value == 0 */
5110         {
5111           /* This is a case where some watchpoint(s) triggered, but
5112              not at the address of this watchpoint, or else no
5113              watchpoint triggered after all.  So don't print
5114              anything for this watchpoint.  */
5115           bs->print_it = print_it_noop;
5116           bs->stop = 0;
5117         }
5118     }
5119 }
5120
5121 /* For breakpoints that are currently marked as telling gdb to stop,
5122    check conditions (condition proper, frame, thread and ignore count)
5123    of breakpoint referred to by BS.  If we should not stop for this
5124    breakpoint, set BS->stop to 0.  */
5125
5126 static void
5127 bpstat_check_breakpoint_conditions (bpstat bs, thread_info *thread)
5128 {
5129   const struct bp_location *bl;
5130   struct breakpoint *b;
5131   /* Assume stop.  */
5132   bool condition_result = true;
5133   struct expression *cond;
5134
5135   gdb_assert (bs->stop);
5136
5137   /* BS is built for existing struct breakpoint.  */
5138   bl = bs->bp_location_at;
5139   gdb_assert (bl != NULL);
5140   b = bs->breakpoint_at;
5141   gdb_assert (b != NULL);
5142
5143   /* Even if the target evaluated the condition on its end and notified GDB, we
5144      need to do so again since GDB does not know if we stopped due to a
5145      breakpoint or a single step breakpoint.  */
5146
5147   if (frame_id_p (b->frame_id)
5148       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5149     {
5150       bs->stop = 0;
5151       return;
5152     }
5153
5154   /* If this is a thread/task-specific breakpoint, don't waste cpu
5155      evaluating the condition if this isn't the specified
5156      thread/task.  */
5157   if ((b->thread != -1 && b->thread != thread->global_num)
5158       || (b->task != 0 && b->task != ada_get_task_number (thread)))
5159     {
5160       bs->stop = 0;
5161       return;
5162     }
5163
5164   /* Evaluate extension language breakpoints that have a "stop" method
5165      implemented.  */
5166   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5167
5168   if (is_watchpoint (b))
5169     {
5170       struct watchpoint *w = (struct watchpoint *) b;
5171
5172       cond = w->cond_exp.get ();
5173     }
5174   else
5175     cond = bl->cond.get ();
5176
5177   if (cond && b->disposition != disp_del_at_next_stop)
5178     {
5179       int within_current_scope = 1;
5180       struct watchpoint * w;
5181
5182       /* We use value_mark and value_free_to_mark because it could
5183          be a long time before we return to the command level and
5184          call free_all_values.  We can't call free_all_values
5185          because we might be in the middle of evaluating a
5186          function call.  */
5187       struct value *mark = value_mark ();
5188
5189       if (is_watchpoint (b))
5190         w = (struct watchpoint *) b;
5191       else
5192         w = NULL;
5193
5194       /* Need to select the frame, with all that implies so that
5195          the conditions will have the right context.  Because we
5196          use the frame, we will not see an inlined function's
5197          variables when we arrive at a breakpoint at the start
5198          of the inlined function; the current frame will be the
5199          call site.  */
5200       if (w == NULL || w->cond_exp_valid_block == NULL)
5201         select_frame (get_current_frame ());
5202       else
5203         {
5204           struct frame_info *frame;
5205
5206           /* For local watchpoint expressions, which particular
5207              instance of a local is being watched matters, so we
5208              keep track of the frame to evaluate the expression
5209              in.  To evaluate the condition however, it doesn't
5210              really matter which instantiation of the function
5211              where the condition makes sense triggers the
5212              watchpoint.  This allows an expression like "watch
5213              global if q > 10" set in `func', catch writes to
5214              global on all threads that call `func', or catch
5215              writes on all recursive calls of `func' by a single
5216              thread.  We simply always evaluate the condition in
5217              the innermost frame that's executing where it makes
5218              sense to evaluate the condition.  It seems
5219              intuitive.  */
5220           frame = block_innermost_frame (w->cond_exp_valid_block);
5221           if (frame != NULL)
5222             select_frame (frame);
5223           else
5224             within_current_scope = 0;
5225         }
5226       if (within_current_scope)
5227         {
5228           try
5229             {
5230               condition_result = breakpoint_cond_eval (cond);
5231             }
5232           catch (const gdb_exception &ex)
5233             {
5234               exception_fprintf (gdb_stderr, ex,
5235                                  "Error in testing breakpoint condition:\n");
5236             }
5237         }
5238       else
5239         {
5240           warning (_("Watchpoint condition cannot be tested "
5241                      "in the current scope"));
5242           /* If we failed to set the right context for this
5243              watchpoint, unconditionally report it.  */
5244         }
5245       /* FIXME-someday, should give breakpoint #.  */
5246       value_free_to_mark (mark);
5247     }
5248
5249   if (cond && !condition_result)
5250     {
5251       bs->stop = 0;
5252     }
5253   else if (b->ignore_count > 0)
5254     {
5255       b->ignore_count--;
5256       bs->stop = 0;
5257       /* Increase the hit count even though we don't stop.  */
5258       ++(b->hit_count);
5259       gdb::observers::breakpoint_modified.notify (b);
5260     }   
5261 }
5262
5263 /* Returns true if we need to track moribund locations of LOC's type
5264    on the current target.  */
5265
5266 static int
5267 need_moribund_for_location_type (struct bp_location *loc)
5268 {
5269   return ((loc->loc_type == bp_loc_software_breakpoint
5270            && !target_supports_stopped_by_sw_breakpoint ())
5271           || (loc->loc_type == bp_loc_hardware_breakpoint
5272               && !target_supports_stopped_by_hw_breakpoint ()));
5273 }
5274
5275 /* See breakpoint.h.  */
5276
5277 bpstat
5278 build_bpstat_chain (const address_space *aspace, CORE_ADDR bp_addr,
5279                     const struct target_waitstatus *ws)
5280 {
5281   struct breakpoint *b;
5282   bpstat bs_head = NULL, *bs_link = &bs_head;
5283
5284   ALL_BREAKPOINTS (b)
5285     {
5286       if (!breakpoint_enabled (b))
5287         continue;
5288
5289       for (bp_location *bl = b->loc; bl != NULL; bl = bl->next)
5290         {
5291           /* For hardware watchpoints, we look only at the first
5292              location.  The watchpoint_check function will work on the
5293              entire expression, not the individual locations.  For
5294              read watchpoints, the watchpoints_triggered function has
5295              checked all locations already.  */
5296           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5297             break;
5298
5299           if (!bl->enabled || bl->shlib_disabled)
5300             continue;
5301
5302           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5303             continue;
5304
5305           /* Come here if it's a watchpoint, or if the break address
5306              matches.  */
5307
5308           bpstat bs = new bpstats (bl, &bs_link);       /* Alloc a bpstat to
5309                                                            explain stop.  */
5310
5311           /* Assume we stop.  Should we find a watchpoint that is not
5312              actually triggered, or if the condition of the breakpoint
5313              evaluates as false, we'll reset 'stop' to 0.  */
5314           bs->stop = 1;
5315           bs->print = 1;
5316
5317           /* If this is a scope breakpoint, mark the associated
5318              watchpoint as triggered so that we will handle the
5319              out-of-scope event.  We'll get to the watchpoint next
5320              iteration.  */
5321           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5322             {
5323               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5324
5325               w->watchpoint_triggered = watch_triggered_yes;
5326             }
5327         }
5328     }
5329
5330   /* Check if a moribund breakpoint explains the stop.  */
5331   if (!target_supports_stopped_by_sw_breakpoint ()
5332       || !target_supports_stopped_by_hw_breakpoint ())
5333     {
5334       for (bp_location *loc : moribund_locations)
5335         {
5336           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5337               && need_moribund_for_location_type (loc))
5338             {
5339               bpstat bs = new bpstats (loc, &bs_link);
5340               /* For hits of moribund locations, we should just proceed.  */
5341               bs->stop = 0;
5342               bs->print = 0;
5343               bs->print_it = print_it_noop;
5344             }
5345         }
5346     }
5347
5348   return bs_head;
5349 }
5350
5351 /* See breakpoint.h.  */
5352
5353 bpstat
5354 bpstat_stop_status (const address_space *aspace,
5355                     CORE_ADDR bp_addr, thread_info *thread,
5356                     const struct target_waitstatus *ws,
5357                     bpstat stop_chain)
5358 {
5359   struct breakpoint *b = NULL;
5360   /* First item of allocated bpstat's.  */
5361   bpstat bs_head = stop_chain;
5362   bpstat bs;
5363   int need_remove_insert;
5364   int removed_any;
5365
5366   /* First, build the bpstat chain with locations that explain a
5367      target stop, while being careful to not set the target running,
5368      as that may invalidate locations (in particular watchpoint
5369      locations are recreated).  Resuming will happen here with
5370      breakpoint conditions or watchpoint expressions that include
5371      inferior function calls.  */
5372   if (bs_head == NULL)
5373     bs_head = build_bpstat_chain (aspace, bp_addr, ws);
5374
5375   /* A bit of special processing for shlib breakpoints.  We need to
5376      process solib loading here, so that the lists of loaded and
5377      unloaded libraries are correct before we handle "catch load" and
5378      "catch unload".  */
5379   for (bs = bs_head; bs != NULL; bs = bs->next)
5380     {
5381       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5382         {
5383           handle_solib_event ();
5384           break;
5385         }
5386     }
5387
5388   /* Now go through the locations that caused the target to stop, and
5389      check whether we're interested in reporting this stop to higher
5390      layers, or whether we should resume the target transparently.  */
5391
5392   removed_any = 0;
5393
5394   for (bs = bs_head; bs != NULL; bs = bs->next)
5395     {
5396       if (!bs->stop)
5397         continue;
5398
5399       b = bs->breakpoint_at;
5400       b->ops->check_status (bs);
5401       if (bs->stop)
5402         {
5403           bpstat_check_breakpoint_conditions (bs, thread);
5404
5405           if (bs->stop)
5406             {
5407               ++(b->hit_count);
5408               gdb::observers::breakpoint_modified.notify (b);
5409
5410               /* We will stop here.  */
5411               if (b->disposition == disp_disable)
5412                 {
5413                   --(b->enable_count);
5414                   if (b->enable_count <= 0)
5415                     b->enable_state = bp_disabled;
5416                   removed_any = 1;
5417                 }
5418               if (b->silent)
5419                 bs->print = 0;
5420               bs->commands = b->commands;
5421               if (command_line_is_silent (bs->commands
5422                                           ? bs->commands.get () : NULL))
5423                 bs->print = 0;
5424
5425               b->ops->after_condition_true (bs);
5426             }
5427
5428         }
5429
5430       /* Print nothing for this entry if we don't stop or don't
5431          print.  */
5432       if (!bs->stop || !bs->print)
5433         bs->print_it = print_it_noop;
5434     }
5435
5436   /* If we aren't stopping, the value of some hardware watchpoint may
5437      not have changed, but the intermediate memory locations we are
5438      watching may have.  Don't bother if we're stopping; this will get
5439      done later.  */
5440   need_remove_insert = 0;
5441   if (! bpstat_causes_stop (bs_head))
5442     for (bs = bs_head; bs != NULL; bs = bs->next)
5443       if (!bs->stop
5444           && bs->breakpoint_at
5445           && is_hardware_watchpoint (bs->breakpoint_at))
5446         {
5447           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5448
5449           update_watchpoint (w, 0 /* don't reparse.  */);
5450           need_remove_insert = 1;
5451         }
5452
5453   if (need_remove_insert)
5454     update_global_location_list (UGLL_MAY_INSERT);
5455   else if (removed_any)
5456     update_global_location_list (UGLL_DONT_INSERT);
5457
5458   return bs_head;
5459 }
5460
5461 static void
5462 handle_jit_event (void)
5463 {
5464   struct frame_info *frame;
5465   struct gdbarch *gdbarch;
5466
5467   if (debug_infrun)
5468     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5469
5470   /* Switch terminal for any messages produced by
5471      breakpoint_re_set.  */
5472   target_terminal::ours_for_output ();
5473
5474   frame = get_current_frame ();
5475   gdbarch = get_frame_arch (frame);
5476
5477   jit_event_handler (gdbarch);
5478
5479   target_terminal::inferior ();
5480 }
5481
5482 /* Prepare WHAT final decision for infrun.  */
5483
5484 /* Decide what infrun needs to do with this bpstat.  */
5485
5486 struct bpstat_what
5487 bpstat_what (bpstat bs_head)
5488 {
5489   struct bpstat_what retval;
5490   bpstat bs;
5491
5492   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5493   retval.call_dummy = STOP_NONE;
5494   retval.is_longjmp = 0;
5495
5496   for (bs = bs_head; bs != NULL; bs = bs->next)
5497     {
5498       /* Extract this BS's action.  After processing each BS, we check
5499          if its action overrides all we've seem so far.  */
5500       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5501       enum bptype bptype;
5502
5503       if (bs->breakpoint_at == NULL)
5504         {
5505           /* I suspect this can happen if it was a momentary
5506              breakpoint which has since been deleted.  */
5507           bptype = bp_none;
5508         }
5509       else
5510         bptype = bs->breakpoint_at->type;
5511
5512       switch (bptype)
5513         {
5514         case bp_none:
5515           break;
5516         case bp_breakpoint:
5517         case bp_hardware_breakpoint:
5518         case bp_single_step:
5519         case bp_until:
5520         case bp_finish:
5521         case bp_shlib_event:
5522           if (bs->stop)
5523             {
5524               if (bs->print)
5525                 this_action = BPSTAT_WHAT_STOP_NOISY;
5526               else
5527                 this_action = BPSTAT_WHAT_STOP_SILENT;
5528             }
5529           else
5530             this_action = BPSTAT_WHAT_SINGLE;
5531           break;
5532         case bp_watchpoint:
5533         case bp_hardware_watchpoint:
5534         case bp_read_watchpoint:
5535         case bp_access_watchpoint:
5536           if (bs->stop)
5537             {
5538               if (bs->print)
5539                 this_action = BPSTAT_WHAT_STOP_NOISY;
5540               else
5541                 this_action = BPSTAT_WHAT_STOP_SILENT;
5542             }
5543           else
5544             {
5545               /* There was a watchpoint, but we're not stopping.
5546                  This requires no further action.  */
5547             }
5548           break;
5549         case bp_longjmp:
5550         case bp_longjmp_call_dummy:
5551         case bp_exception:
5552           if (bs->stop)
5553             {
5554               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5555               retval.is_longjmp = bptype != bp_exception;
5556             }
5557           else
5558             this_action = BPSTAT_WHAT_SINGLE;
5559           break;
5560         case bp_longjmp_resume:
5561         case bp_exception_resume:
5562           if (bs->stop)
5563             {
5564               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5565               retval.is_longjmp = bptype == bp_longjmp_resume;
5566             }
5567           else
5568             this_action = BPSTAT_WHAT_SINGLE;
5569           break;
5570         case bp_step_resume:
5571           if (bs->stop)
5572             this_action = BPSTAT_WHAT_STEP_RESUME;
5573           else
5574             {
5575               /* It is for the wrong frame.  */
5576               this_action = BPSTAT_WHAT_SINGLE;
5577             }
5578           break;
5579         case bp_hp_step_resume:
5580           if (bs->stop)
5581             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5582           else
5583             {
5584               /* It is for the wrong frame.  */
5585               this_action = BPSTAT_WHAT_SINGLE;
5586             }
5587           break;
5588         case bp_watchpoint_scope:
5589         case bp_thread_event:
5590         case bp_overlay_event:
5591         case bp_longjmp_master:
5592         case bp_std_terminate_master:
5593         case bp_exception_master:
5594           this_action = BPSTAT_WHAT_SINGLE;
5595           break;
5596         case bp_catchpoint:
5597           if (bs->stop)
5598             {
5599               if (bs->print)
5600                 this_action = BPSTAT_WHAT_STOP_NOISY;
5601               else
5602                 this_action = BPSTAT_WHAT_STOP_SILENT;
5603             }
5604           else
5605             {
5606               /* There was a catchpoint, but we're not stopping.
5607                  This requires no further action.  */
5608             }
5609           break;
5610         case bp_jit_event:
5611           this_action = BPSTAT_WHAT_SINGLE;
5612           break;
5613         case bp_call_dummy:
5614           /* Make sure the action is stop (silent or noisy),
5615              so infrun.c pops the dummy frame.  */
5616           retval.call_dummy = STOP_STACK_DUMMY;
5617           this_action = BPSTAT_WHAT_STOP_SILENT;
5618           break;
5619         case bp_std_terminate:
5620           /* Make sure the action is stop (silent or noisy),
5621              so infrun.c pops the dummy frame.  */
5622           retval.call_dummy = STOP_STD_TERMINATE;
5623           this_action = BPSTAT_WHAT_STOP_SILENT;
5624           break;
5625         case bp_tracepoint:
5626         case bp_fast_tracepoint:
5627         case bp_static_tracepoint:
5628           /* Tracepoint hits should not be reported back to GDB, and
5629              if one got through somehow, it should have been filtered
5630              out already.  */
5631           internal_error (__FILE__, __LINE__,
5632                           _("bpstat_what: tracepoint encountered"));
5633           break;
5634         case bp_gnu_ifunc_resolver:
5635           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5636           this_action = BPSTAT_WHAT_SINGLE;
5637           break;
5638         case bp_gnu_ifunc_resolver_return:
5639           /* The breakpoint will be removed, execution will restart from the
5640              PC of the former breakpoint.  */
5641           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5642           break;
5643
5644         case bp_dprintf:
5645           if (bs->stop)
5646             this_action = BPSTAT_WHAT_STOP_SILENT;
5647           else
5648             this_action = BPSTAT_WHAT_SINGLE;
5649           break;
5650
5651         default:
5652           internal_error (__FILE__, __LINE__,
5653                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5654         }
5655
5656       retval.main_action = std::max (retval.main_action, this_action);
5657     }
5658
5659   return retval;
5660 }
5661
5662 void
5663 bpstat_run_callbacks (bpstat bs_head)
5664 {
5665   bpstat bs;
5666
5667   for (bs = bs_head; bs != NULL; bs = bs->next)
5668     {
5669       struct breakpoint *b = bs->breakpoint_at;
5670
5671       if (b == NULL)
5672         continue;
5673       switch (b->type)
5674         {
5675         case bp_jit_event:
5676           handle_jit_event ();
5677           break;
5678         case bp_gnu_ifunc_resolver:
5679           gnu_ifunc_resolver_stop (b);
5680           break;
5681         case bp_gnu_ifunc_resolver_return:
5682           gnu_ifunc_resolver_return_stop (b);
5683           break;
5684         }
5685     }
5686 }
5687
5688 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5689    without hardware support).  This isn't related to a specific bpstat,
5690    just to things like whether watchpoints are set.  */
5691
5692 int
5693 bpstat_should_step (void)
5694 {
5695   struct breakpoint *b;
5696
5697   ALL_BREAKPOINTS (b)
5698     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5699       return 1;
5700   return 0;
5701 }
5702
5703 int
5704 bpstat_causes_stop (bpstat bs)
5705 {
5706   for (; bs != NULL; bs = bs->next)
5707     if (bs->stop)
5708       return 1;
5709
5710   return 0;
5711 }
5712
5713 \f
5714
5715 /* Compute a string of spaces suitable to indent the next line
5716    so it starts at the position corresponding to the table column
5717    named COL_NAME in the currently active table of UIOUT.  */
5718
5719 static char *
5720 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5721 {
5722   static char wrap_indent[80];
5723   int i, total_width, width, align;
5724   const char *text;
5725
5726   total_width = 0;
5727   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
5728     {
5729       if (strcmp (text, col_name) == 0)
5730         {
5731           gdb_assert (total_width < sizeof wrap_indent);
5732           memset (wrap_indent, ' ', total_width);
5733           wrap_indent[total_width] = 0;
5734
5735           return wrap_indent;
5736         }
5737
5738       total_width += width + 1;
5739     }
5740
5741   return NULL;
5742 }
5743
5744 /* Determine if the locations of this breakpoint will have their conditions
5745    evaluated by the target, host or a mix of both.  Returns the following:
5746
5747     "host": Host evals condition.
5748     "host or target": Host or Target evals condition.
5749     "target": Target evals condition.
5750 */
5751
5752 static const char *
5753 bp_condition_evaluator (struct breakpoint *b)
5754 {
5755   struct bp_location *bl;
5756   char host_evals = 0;
5757   char target_evals = 0;
5758
5759   if (!b)
5760     return NULL;
5761
5762   if (!is_breakpoint (b))
5763     return NULL;
5764
5765   if (gdb_evaluates_breakpoint_condition_p ()
5766       || !target_supports_evaluation_of_breakpoint_conditions ())
5767     return condition_evaluation_host;
5768
5769   for (bl = b->loc; bl; bl = bl->next)
5770     {
5771       if (bl->cond_bytecode)
5772         target_evals++;
5773       else
5774         host_evals++;
5775     }
5776
5777   if (host_evals && target_evals)
5778     return condition_evaluation_both;
5779   else if (target_evals)
5780     return condition_evaluation_target;
5781   else
5782     return condition_evaluation_host;
5783 }
5784
5785 /* Determine the breakpoint location's condition evaluator.  This is
5786    similar to bp_condition_evaluator, but for locations.  */
5787
5788 static const char *
5789 bp_location_condition_evaluator (struct bp_location *bl)
5790 {
5791   if (bl && !is_breakpoint (bl->owner))
5792     return NULL;
5793
5794   if (gdb_evaluates_breakpoint_condition_p ()
5795       || !target_supports_evaluation_of_breakpoint_conditions ())
5796     return condition_evaluation_host;
5797
5798   if (bl && bl->cond_bytecode)
5799     return condition_evaluation_target;
5800   else
5801     return condition_evaluation_host;
5802 }
5803
5804 /* Print the LOC location out of the list of B->LOC locations.  */
5805
5806 static void
5807 print_breakpoint_location (struct breakpoint *b,
5808                            struct bp_location *loc)
5809 {
5810   struct ui_out *uiout = current_uiout;
5811
5812   scoped_restore_current_program_space restore_pspace;
5813
5814   if (loc != NULL && loc->shlib_disabled)
5815     loc = NULL;
5816
5817   if (loc != NULL)
5818     set_current_program_space (loc->pspace);
5819
5820   if (b->display_canonical)
5821     uiout->field_string ("what", event_location_to_string (b->location.get ()));
5822   else if (loc && loc->symtab)
5823     {
5824       const struct symbol *sym = loc->symbol;
5825
5826       if (sym)
5827         {
5828           uiout->text ("in ");
5829           uiout->field_string ("func", SYMBOL_PRINT_NAME (sym),
5830                                ui_out_style_kind::FUNCTION);
5831           uiout->text (" ");
5832           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
5833           uiout->text ("at ");
5834         }
5835       uiout->field_string ("file",
5836                            symtab_to_filename_for_display (loc->symtab),
5837                            ui_out_style_kind::FILE);
5838       uiout->text (":");
5839
5840       if (uiout->is_mi_like_p ())
5841         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
5842       
5843       uiout->field_int ("line", loc->line_number);
5844     }
5845   else if (loc)
5846     {
5847       string_file stb;
5848
5849       print_address_symbolic (loc->gdbarch, loc->address, &stb,
5850                               demangle, "");
5851       uiout->field_stream ("at", stb);
5852     }
5853   else
5854     {
5855       uiout->field_string ("pending",
5856                            event_location_to_string (b->location.get ()));
5857       /* If extra_string is available, it could be holding a condition
5858          or dprintf arguments.  In either case, make sure it is printed,
5859          too, but only for non-MI streams.  */
5860       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
5861         {
5862           if (b->type == bp_dprintf)
5863             uiout->text (",");
5864           else
5865             uiout->text (" ");
5866           uiout->text (b->extra_string);
5867         }
5868     }
5869
5870   if (loc && is_breakpoint (b)
5871       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5872       && bp_condition_evaluator (b) == condition_evaluation_both)
5873     {
5874       uiout->text (" (");
5875       uiout->field_string ("evaluated-by",
5876                            bp_location_condition_evaluator (loc));
5877       uiout->text (")");
5878     }
5879 }
5880
5881 static const char *
5882 bptype_string (enum bptype type)
5883 {
5884   struct ep_type_description
5885     {
5886       enum bptype type;
5887       const char *description;
5888     };
5889   static struct ep_type_description bptypes[] =
5890   {
5891     {bp_none, "?deleted?"},
5892     {bp_breakpoint, "breakpoint"},
5893     {bp_hardware_breakpoint, "hw breakpoint"},
5894     {bp_single_step, "sw single-step"},
5895     {bp_until, "until"},
5896     {bp_finish, "finish"},
5897     {bp_watchpoint, "watchpoint"},
5898     {bp_hardware_watchpoint, "hw watchpoint"},
5899     {bp_read_watchpoint, "read watchpoint"},
5900     {bp_access_watchpoint, "acc watchpoint"},
5901     {bp_longjmp, "longjmp"},
5902     {bp_longjmp_resume, "longjmp resume"},
5903     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5904     {bp_exception, "exception"},
5905     {bp_exception_resume, "exception resume"},
5906     {bp_step_resume, "step resume"},
5907     {bp_hp_step_resume, "high-priority step resume"},
5908     {bp_watchpoint_scope, "watchpoint scope"},
5909     {bp_call_dummy, "call dummy"},
5910     {bp_std_terminate, "std::terminate"},
5911     {bp_shlib_event, "shlib events"},
5912     {bp_thread_event, "thread events"},
5913     {bp_overlay_event, "overlay events"},
5914     {bp_longjmp_master, "longjmp master"},
5915     {bp_std_terminate_master, "std::terminate master"},
5916     {bp_exception_master, "exception master"},
5917     {bp_catchpoint, "catchpoint"},
5918     {bp_tracepoint, "tracepoint"},
5919     {bp_fast_tracepoint, "fast tracepoint"},
5920     {bp_static_tracepoint, "static tracepoint"},
5921     {bp_dprintf, "dprintf"},
5922     {bp_jit_event, "jit events"},
5923     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5924     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5925   };
5926
5927   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5928       || ((int) type != bptypes[(int) type].type))
5929     internal_error (__FILE__, __LINE__,
5930                     _("bptypes table does not describe type #%d."),
5931                     (int) type);
5932
5933   return bptypes[(int) type].description;
5934 }
5935
5936 /* For MI, output a field named 'thread-groups' with a list as the value.
5937    For CLI, prefix the list with the string 'inf'. */
5938
5939 static void
5940 output_thread_groups (struct ui_out *uiout,
5941                       const char *field_name,
5942                       const std::vector<int> &inf_nums,
5943                       int mi_only)
5944 {
5945   int is_mi = uiout->is_mi_like_p ();
5946
5947   /* For backward compatibility, don't display inferiors in CLI unless
5948      there are several.  Always display them for MI. */
5949   if (!is_mi && mi_only)
5950     return;
5951
5952   ui_out_emit_list list_emitter (uiout, field_name);
5953
5954   for (size_t i = 0; i < inf_nums.size (); i++)
5955     {
5956       if (is_mi)
5957         {
5958           char mi_group[10];
5959
5960           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf_nums[i]);
5961           uiout->field_string (NULL, mi_group);
5962         }
5963       else
5964         {
5965           if (i == 0)
5966             uiout->text (" inf ");
5967           else
5968             uiout->text (", ");
5969         
5970           uiout->text (plongest (inf_nums[i]));
5971         }
5972     }
5973 }
5974
5975 /* Print B to gdb_stdout.  */
5976
5977 static void
5978 print_one_breakpoint_location (struct breakpoint *b,
5979                                struct bp_location *loc,
5980                                int loc_number,
5981                                struct bp_location **last_loc,
5982                                int allflag)
5983 {
5984   struct command_line *l;
5985   static char bpenables[] = "nynny";
5986
5987   struct ui_out *uiout = current_uiout;
5988   int header_of_multiple = 0;
5989   int part_of_multiple = (loc != NULL);
5990   struct value_print_options opts;
5991
5992   get_user_print_options (&opts);
5993
5994   gdb_assert (!loc || loc_number != 0);
5995   /* See comment in print_one_breakpoint concerning treatment of
5996      breakpoints with single disabled location.  */
5997   if (loc == NULL 
5998       && (b->loc != NULL 
5999           && (b->loc->next != NULL || !b->loc->enabled)))
6000     header_of_multiple = 1;
6001   if (loc == NULL)
6002     loc = b->loc;
6003
6004   annotate_record ();
6005
6006   /* 1 */
6007   annotate_field (0);
6008   if (part_of_multiple)
6009     uiout->field_fmt ("number", "%d.%d", b->number, loc_number);
6010   else
6011     uiout->field_int ("number", b->number);
6012
6013   /* 2 */
6014   annotate_field (1);
6015   if (part_of_multiple)
6016     uiout->field_skip ("type");
6017   else
6018     uiout->field_string ("type", bptype_string (b->type));
6019
6020   /* 3 */
6021   annotate_field (2);
6022   if (part_of_multiple)
6023     uiout->field_skip ("disp");
6024   else
6025     uiout->field_string ("disp", bpdisp_text (b->disposition));
6026
6027   /* 4 */
6028   annotate_field (3);
6029   if (part_of_multiple)
6030     uiout->field_string ("enabled", loc->enabled ? "y" : "n");
6031   else
6032     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6033
6034   /* 5 and 6 */
6035   if (b->ops != NULL && b->ops->print_one != NULL)
6036     {
6037       /* Although the print_one can possibly print all locations,
6038          calling it here is not likely to get any nice result.  So,
6039          make sure there's just one location.  */
6040       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6041       b->ops->print_one (b, last_loc);
6042     }
6043   else
6044     switch (b->type)
6045       {
6046       case bp_none:
6047         internal_error (__FILE__, __LINE__,
6048                         _("print_one_breakpoint: bp_none encountered\n"));
6049         break;
6050
6051       case bp_watchpoint:
6052       case bp_hardware_watchpoint:
6053       case bp_read_watchpoint:
6054       case bp_access_watchpoint:
6055         {
6056           struct watchpoint *w = (struct watchpoint *) b;
6057
6058           /* Field 4, the address, is omitted (which makes the columns
6059              not line up too nicely with the headers, but the effect
6060              is relatively readable).  */
6061           if (opts.addressprint)
6062             uiout->field_skip ("addr");
6063           annotate_field (5);
6064           uiout->field_string ("what", w->exp_string);
6065         }
6066         break;
6067
6068       case bp_breakpoint:
6069       case bp_hardware_breakpoint:
6070       case bp_single_step:
6071       case bp_until:
6072       case bp_finish:
6073       case bp_longjmp:
6074       case bp_longjmp_resume:
6075       case bp_longjmp_call_dummy:
6076       case bp_exception:
6077       case bp_exception_resume:
6078       case bp_step_resume:
6079       case bp_hp_step_resume:
6080       case bp_watchpoint_scope:
6081       case bp_call_dummy:
6082       case bp_std_terminate:
6083       case bp_shlib_event:
6084       case bp_thread_event:
6085       case bp_overlay_event:
6086       case bp_longjmp_master:
6087       case bp_std_terminate_master:
6088       case bp_exception_master:
6089       case bp_tracepoint:
6090       case bp_fast_tracepoint:
6091       case bp_static_tracepoint:
6092       case bp_dprintf:
6093       case bp_jit_event:
6094       case bp_gnu_ifunc_resolver:
6095       case bp_gnu_ifunc_resolver_return:
6096         if (opts.addressprint)
6097           {
6098             annotate_field (4);
6099             if (header_of_multiple)
6100               uiout->field_string ("addr", "<MULTIPLE>");
6101             else if (b->loc == NULL || loc->shlib_disabled)
6102               uiout->field_string ("addr", "<PENDING>");
6103             else
6104               uiout->field_core_addr ("addr",
6105                                       loc->gdbarch, loc->address);
6106           }
6107         annotate_field (5);
6108         if (!header_of_multiple)
6109           print_breakpoint_location (b, loc);
6110         if (b->loc)
6111           *last_loc = b->loc;
6112         break;
6113       }
6114
6115
6116   if (loc != NULL && !header_of_multiple)
6117     {
6118       std::vector<int> inf_nums;
6119       int mi_only = 1;
6120
6121       for (inferior *inf : all_inferiors ())
6122         {
6123           if (inf->pspace == loc->pspace)
6124             inf_nums.push_back (inf->num);
6125         }
6126
6127         /* For backward compatibility, don't display inferiors in CLI unless
6128            there are several.  Always display for MI. */
6129         if (allflag
6130             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6131                 && (number_of_program_spaces () > 1
6132                     || number_of_inferiors () > 1)
6133                 /* LOC is for existing B, it cannot be in
6134                    moribund_locations and thus having NULL OWNER.  */
6135                 && loc->owner->type != bp_catchpoint))
6136         mi_only = 0;
6137       output_thread_groups (uiout, "thread-groups", inf_nums, mi_only);
6138     }
6139
6140   if (!part_of_multiple)
6141     {
6142       if (b->thread != -1)
6143         {
6144           /* FIXME: This seems to be redundant and lost here; see the
6145              "stop only in" line a little further down.  */
6146           uiout->text (" thread ");
6147           uiout->field_int ("thread", b->thread);
6148         }
6149       else if (b->task != 0)
6150         {
6151           uiout->text (" task ");
6152           uiout->field_int ("task", b->task);
6153         }
6154     }
6155
6156   uiout->text ("\n");
6157
6158   if (!part_of_multiple)
6159     b->ops->print_one_detail (b, uiout);
6160
6161   if (part_of_multiple && frame_id_p (b->frame_id))
6162     {
6163       annotate_field (6);
6164       uiout->text ("\tstop only in stack frame at ");
6165       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6166          the frame ID.  */
6167       uiout->field_core_addr ("frame",
6168                               b->gdbarch, b->frame_id.stack_addr);
6169       uiout->text ("\n");
6170     }
6171   
6172   if (!part_of_multiple && b->cond_string)
6173     {
6174       annotate_field (7);
6175       if (is_tracepoint (b))
6176         uiout->text ("\ttrace only if ");
6177       else
6178         uiout->text ("\tstop only if ");
6179       uiout->field_string ("cond", b->cond_string);
6180
6181       /* Print whether the target is doing the breakpoint's condition
6182          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6183       if (is_breakpoint (b)
6184           && breakpoint_condition_evaluation_mode ()
6185           == condition_evaluation_target)
6186         {
6187           uiout->text (" (");
6188           uiout->field_string ("evaluated-by",
6189                                bp_condition_evaluator (b));
6190           uiout->text (" evals)");
6191         }
6192       uiout->text ("\n");
6193     }
6194
6195   if (!part_of_multiple && b->thread != -1)
6196     {
6197       /* FIXME should make an annotation for this.  */
6198       uiout->text ("\tstop only in thread ");
6199       if (uiout->is_mi_like_p ())
6200         uiout->field_int ("thread", b->thread);
6201       else
6202         {
6203           struct thread_info *thr = find_thread_global_id (b->thread);
6204
6205           uiout->field_string ("thread", print_thread_id (thr));
6206         }
6207       uiout->text ("\n");
6208     }
6209   
6210   if (!part_of_multiple)
6211     {
6212       if (b->hit_count)
6213         {
6214           /* FIXME should make an annotation for this.  */
6215           if (is_catchpoint (b))
6216             uiout->text ("\tcatchpoint");
6217           else if (is_tracepoint (b))
6218             uiout->text ("\ttracepoint");
6219           else
6220             uiout->text ("\tbreakpoint");
6221           uiout->text (" already hit ");
6222           uiout->field_int ("times", b->hit_count);
6223           if (b->hit_count == 1)
6224             uiout->text (" time\n");
6225           else
6226             uiout->text (" times\n");
6227         }
6228       else
6229         {
6230           /* Output the count also if it is zero, but only if this is mi.  */
6231           if (uiout->is_mi_like_p ())
6232             uiout->field_int ("times", b->hit_count);
6233         }
6234     }
6235
6236   if (!part_of_multiple && b->ignore_count)
6237     {
6238       annotate_field (8);
6239       uiout->text ("\tignore next ");
6240       uiout->field_int ("ignore", b->ignore_count);
6241       uiout->text (" hits\n");
6242     }
6243
6244   /* Note that an enable count of 1 corresponds to "enable once"
6245      behavior, which is reported by the combination of enablement and
6246      disposition, so we don't need to mention it here.  */
6247   if (!part_of_multiple && b->enable_count > 1)
6248     {
6249       annotate_field (8);
6250       uiout->text ("\tdisable after ");
6251       /* Tweak the wording to clarify that ignore and enable counts
6252          are distinct, and have additive effect.  */
6253       if (b->ignore_count)
6254         uiout->text ("additional ");
6255       else
6256         uiout->text ("next ");
6257       uiout->field_int ("enable", b->enable_count);
6258       uiout->text (" hits\n");
6259     }
6260
6261   if (!part_of_multiple && is_tracepoint (b))
6262     {
6263       struct tracepoint *tp = (struct tracepoint *) b;
6264
6265       if (tp->traceframe_usage)
6266         {
6267           uiout->text ("\ttrace buffer usage ");
6268           uiout->field_int ("traceframe-usage", tp->traceframe_usage);
6269           uiout->text (" bytes\n");
6270         }
6271     }
6272
6273   l = b->commands ? b->commands.get () : NULL;
6274   if (!part_of_multiple && l)
6275     {
6276       annotate_field (9);
6277       ui_out_emit_tuple tuple_emitter (uiout, "script");
6278       print_command_lines (uiout, l, 4);
6279     }
6280
6281   if (is_tracepoint (b))
6282     {
6283       struct tracepoint *t = (struct tracepoint *) b;
6284
6285       if (!part_of_multiple && t->pass_count)
6286         {
6287           annotate_field (10);
6288           uiout->text ("\tpass count ");
6289           uiout->field_int ("pass", t->pass_count);
6290           uiout->text (" \n");
6291         }
6292
6293       /* Don't display it when tracepoint or tracepoint location is
6294          pending.   */
6295       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6296         {
6297           annotate_field (11);
6298
6299           if (uiout->is_mi_like_p ())
6300             uiout->field_string ("installed",
6301                                  loc->inserted ? "y" : "n");
6302           else
6303             {
6304               if (loc->inserted)
6305                 uiout->text ("\t");
6306               else
6307                 uiout->text ("\tnot ");
6308               uiout->text ("installed on target\n");
6309             }
6310         }
6311     }
6312
6313   if (uiout->is_mi_like_p () && !part_of_multiple)
6314     {
6315       if (is_watchpoint (b))
6316         {
6317           struct watchpoint *w = (struct watchpoint *) b;
6318
6319           uiout->field_string ("original-location", w->exp_string);
6320         }
6321       else if (b->location != NULL
6322                && event_location_to_string (b->location.get ()) != NULL)
6323         uiout->field_string ("original-location",
6324                              event_location_to_string (b->location.get ()));
6325     }
6326 }
6327
6328 /* See breakpoint.h. */
6329
6330 bool fix_multi_location_breakpoint_output_globally = false;
6331
6332 static void
6333 print_one_breakpoint (struct breakpoint *b,
6334                       struct bp_location **last_loc, 
6335                       int allflag)
6336 {
6337   struct ui_out *uiout = current_uiout;
6338   bool use_fixed_output
6339     = (uiout->test_flags (fix_multi_location_breakpoint_output)
6340        || fix_multi_location_breakpoint_output_globally);
6341
6342   gdb::optional<ui_out_emit_tuple> bkpt_tuple_emitter (gdb::in_place, uiout, "bkpt");
6343   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6344
6345   /* The mi2 broken format: the main breakpoint tuple ends here, the locations
6346      are outside.  */
6347   if (!use_fixed_output)
6348     bkpt_tuple_emitter.reset ();
6349
6350   /* If this breakpoint has custom print function,
6351      it's already printed.  Otherwise, print individual
6352      locations, if any.  */
6353   if (b->ops == NULL || b->ops->print_one == NULL)
6354     {
6355       /* If breakpoint has a single location that is disabled, we
6356          print it as if it had several locations, since otherwise it's
6357          hard to represent "breakpoint enabled, location disabled"
6358          situation.
6359
6360          Note that while hardware watchpoints have several locations
6361          internally, that's not a property exposed to user.  */
6362       if (b->loc 
6363           && !is_hardware_watchpoint (b)
6364           && (b->loc->next || !b->loc->enabled))
6365         {
6366           gdb::optional<ui_out_emit_list> locations_list;
6367
6368           /* For MI version <= 2, keep the behavior where GDB outputs an invalid
6369              MI record.  For later versions, place breakpoint locations in a
6370              list.  */
6371           if (uiout->is_mi_like_p () && use_fixed_output)
6372             locations_list.emplace (uiout, "locations");
6373
6374           int n = 1;
6375           for (bp_location *loc = b->loc; loc != NULL; loc = loc->next, ++n)
6376             {
6377               ui_out_emit_tuple loc_tuple_emitter (uiout, NULL);
6378               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6379             }
6380         }
6381     }
6382 }
6383
6384 static int
6385 breakpoint_address_bits (struct breakpoint *b)
6386 {
6387   int print_address_bits = 0;
6388   struct bp_location *loc;
6389
6390   /* Software watchpoints that aren't watching memory don't have an
6391      address to print.  */
6392   if (is_no_memory_software_watchpoint (b))
6393     return 0;
6394
6395   for (loc = b->loc; loc; loc = loc->next)
6396     {
6397       int addr_bit;
6398
6399       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6400       if (addr_bit > print_address_bits)
6401         print_address_bits = addr_bit;
6402     }
6403
6404   return print_address_bits;
6405 }
6406
6407 /* See breakpoint.h.  */
6408
6409 void
6410 print_breakpoint (breakpoint *b)
6411 {
6412   struct bp_location *dummy_loc = NULL;
6413   print_one_breakpoint (b, &dummy_loc, 0);
6414 }
6415
6416 /* Return true if this breakpoint was set by the user, false if it is
6417    internal or momentary.  */
6418
6419 int
6420 user_breakpoint_p (struct breakpoint *b)
6421 {
6422   return b->number > 0;
6423 }
6424
6425 /* See breakpoint.h.  */
6426
6427 int
6428 pending_breakpoint_p (struct breakpoint *b)
6429 {
6430   return b->loc == NULL;
6431 }
6432
6433 /* Print information on user settable breakpoint (watchpoint, etc)
6434    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6435    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6436    FILTER is non-NULL, call it on each breakpoint and only include the
6437    ones for which it returns non-zero.  Return the total number of
6438    breakpoints listed.  */
6439
6440 static int
6441 breakpoint_1 (const char *args, int allflag, 
6442               int (*filter) (const struct breakpoint *))
6443 {
6444   struct breakpoint *b;
6445   struct bp_location *last_loc = NULL;
6446   int nr_printable_breakpoints;
6447   struct value_print_options opts;
6448   int print_address_bits = 0;
6449   int print_type_col_width = 14;
6450   struct ui_out *uiout = current_uiout;
6451
6452   get_user_print_options (&opts);
6453
6454   /* Compute the number of rows in the table, as well as the size
6455      required for address fields.  */
6456   nr_printable_breakpoints = 0;
6457   ALL_BREAKPOINTS (b)
6458     {
6459       /* If we have a filter, only list the breakpoints it accepts.  */
6460       if (filter && !filter (b))
6461         continue;
6462
6463       /* If we have an "args" string, it is a list of breakpoints to 
6464          accept.  Skip the others.  */
6465       if (args != NULL && *args != '\0')
6466         {
6467           if (allflag && parse_and_eval_long (args) != b->number)
6468             continue;
6469           if (!allflag && !number_is_in_list (args, b->number))
6470             continue;
6471         }
6472
6473       if (allflag || user_breakpoint_p (b))
6474         {
6475           int addr_bit, type_len;
6476
6477           addr_bit = breakpoint_address_bits (b);
6478           if (addr_bit > print_address_bits)
6479             print_address_bits = addr_bit;
6480
6481           type_len = strlen (bptype_string (b->type));
6482           if (type_len > print_type_col_width)
6483             print_type_col_width = type_len;
6484
6485           nr_printable_breakpoints++;
6486         }
6487     }
6488
6489   {
6490     ui_out_emit_table table_emitter (uiout,
6491                                      opts.addressprint ? 6 : 5,
6492                                      nr_printable_breakpoints,
6493                                      "BreakpointTable");
6494
6495     if (nr_printable_breakpoints > 0)
6496       annotate_breakpoints_headers ();
6497     if (nr_printable_breakpoints > 0)
6498       annotate_field (0);
6499     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6500     if (nr_printable_breakpoints > 0)
6501       annotate_field (1);
6502     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6503     if (nr_printable_breakpoints > 0)
6504       annotate_field (2);
6505     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6506     if (nr_printable_breakpoints > 0)
6507       annotate_field (3);
6508     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6509     if (opts.addressprint)
6510       {
6511         if (nr_printable_breakpoints > 0)
6512           annotate_field (4);
6513         if (print_address_bits <= 32)
6514           uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6515         else
6516           uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6517       }
6518     if (nr_printable_breakpoints > 0)
6519       annotate_field (5);
6520     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6521     uiout->table_body ();
6522     if (nr_printable_breakpoints > 0)
6523       annotate_breakpoints_table ();
6524
6525     ALL_BREAKPOINTS (b)
6526       {
6527         QUIT;
6528         /* If we have a filter, only list the breakpoints it accepts.  */
6529         if (filter && !filter (b))
6530           continue;
6531
6532         /* If we have an "args" string, it is a list of breakpoints to 
6533            accept.  Skip the others.  */
6534
6535         if (args != NULL && *args != '\0')
6536           {
6537             if (allflag)        /* maintenance info breakpoint */
6538               {
6539                 if (parse_and_eval_long (args) != b->number)
6540                   continue;
6541               }
6542             else                /* all others */
6543               {
6544                 if (!number_is_in_list (args, b->number))
6545                   continue;
6546               }
6547           }
6548         /* We only print out user settable breakpoints unless the
6549            allflag is set.  */
6550         if (allflag || user_breakpoint_p (b))
6551           print_one_breakpoint (b, &last_loc, allflag);
6552       }
6553   }
6554
6555   if (nr_printable_breakpoints == 0)
6556     {
6557       /* If there's a filter, let the caller decide how to report
6558          empty list.  */
6559       if (!filter)
6560         {
6561           if (args == NULL || *args == '\0')
6562             uiout->message ("No breakpoints or watchpoints.\n");
6563           else
6564             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6565                             args);
6566         }
6567     }
6568   else
6569     {
6570       if (last_loc && !server_command)
6571         set_next_address (last_loc->gdbarch, last_loc->address);
6572     }
6573
6574   /* FIXME?  Should this be moved up so that it is only called when
6575      there have been breakpoints? */
6576   annotate_breakpoints_table_end ();
6577
6578   return nr_printable_breakpoints;
6579 }
6580
6581 /* Display the value of default-collect in a way that is generally
6582    compatible with the breakpoint list.  */
6583
6584 static void
6585 default_collect_info (void)
6586 {
6587   struct ui_out *uiout = current_uiout;
6588
6589   /* If it has no value (which is frequently the case), say nothing; a
6590      message like "No default-collect." gets in user's face when it's
6591      not wanted.  */
6592   if (!*default_collect)
6593     return;
6594
6595   /* The following phrase lines up nicely with per-tracepoint collect
6596      actions.  */
6597   uiout->text ("default collect ");
6598   uiout->field_string ("default-collect", default_collect);
6599   uiout->text (" \n");
6600 }
6601   
6602 static void
6603 info_breakpoints_command (const char *args, int from_tty)
6604 {
6605   breakpoint_1 (args, 0, NULL);
6606
6607   default_collect_info ();
6608 }
6609
6610 static void
6611 info_watchpoints_command (const char *args, int from_tty)
6612 {
6613   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6614   struct ui_out *uiout = current_uiout;
6615
6616   if (num_printed == 0)
6617     {
6618       if (args == NULL || *args == '\0')
6619         uiout->message ("No watchpoints.\n");
6620       else
6621         uiout->message ("No watchpoint matching '%s'.\n", args);
6622     }
6623 }
6624
6625 static void
6626 maintenance_info_breakpoints (const char *args, int from_tty)
6627 {
6628   breakpoint_1 (args, 1, NULL);
6629
6630   default_collect_info ();
6631 }
6632
6633 static int
6634 breakpoint_has_pc (struct breakpoint *b,
6635                    struct program_space *pspace,
6636                    CORE_ADDR pc, struct obj_section *section)
6637 {
6638   struct bp_location *bl = b->loc;
6639
6640   for (; bl; bl = bl->next)
6641     {
6642       if (bl->pspace == pspace
6643           && bl->address == pc
6644           && (!overlay_debugging || bl->section == section))
6645         return 1;         
6646     }
6647   return 0;
6648 }
6649
6650 /* Print a message describing any user-breakpoints set at PC.  This
6651    concerns with logical breakpoints, so we match program spaces, not
6652    address spaces.  */
6653
6654 static void
6655 describe_other_breakpoints (struct gdbarch *gdbarch,
6656                             struct program_space *pspace, CORE_ADDR pc,
6657                             struct obj_section *section, int thread)
6658 {
6659   int others = 0;
6660   struct breakpoint *b;
6661
6662   ALL_BREAKPOINTS (b)
6663     others += (user_breakpoint_p (b)
6664                && breakpoint_has_pc (b, pspace, pc, section));
6665   if (others > 0)
6666     {
6667       if (others == 1)
6668         printf_filtered (_("Note: breakpoint "));
6669       else /* if (others == ???) */
6670         printf_filtered (_("Note: breakpoints "));
6671       ALL_BREAKPOINTS (b)
6672         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6673           {
6674             others--;
6675             printf_filtered ("%d", b->number);
6676             if (b->thread == -1 && thread != -1)
6677               printf_filtered (" (all threads)");
6678             else if (b->thread != -1)
6679               printf_filtered (" (thread %d)", b->thread);
6680             printf_filtered ("%s%s ",
6681                              ((b->enable_state == bp_disabled
6682                                || b->enable_state == bp_call_disabled)
6683                               ? " (disabled)"
6684                               : ""),
6685                              (others > 1) ? "," 
6686                              : ((others == 1) ? " and" : ""));
6687           }
6688       printf_filtered (_("also set at pc "));
6689       fputs_styled (paddress (gdbarch, pc), address_style.style (), gdb_stdout);
6690       printf_filtered (".\n");
6691     }
6692 }
6693 \f
6694
6695 /* Return true iff it is meaningful to use the address member of
6696    BPT locations.  For some breakpoint types, the locations' address members
6697    are irrelevant and it makes no sense to attempt to compare them to other
6698    addresses (or use them for any other purpose either).
6699
6700    More specifically, each of the following breakpoint types will
6701    always have a zero valued location address and we don't want to mark
6702    breakpoints of any of these types to be a duplicate of an actual
6703    breakpoint location at address zero:
6704
6705       bp_watchpoint
6706       bp_catchpoint
6707
6708 */
6709
6710 static int
6711 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6712 {
6713   enum bptype type = bpt->type;
6714
6715   return (type != bp_watchpoint && type != bp_catchpoint);
6716 }
6717
6718 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6719    true if LOC1 and LOC2 represent the same watchpoint location.  */
6720
6721 static int
6722 watchpoint_locations_match (struct bp_location *loc1, 
6723                             struct bp_location *loc2)
6724 {
6725   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6726   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6727
6728   /* Both of them must exist.  */
6729   gdb_assert (w1 != NULL);
6730   gdb_assert (w2 != NULL);
6731
6732   /* If the target can evaluate the condition expression in hardware,
6733      then we we need to insert both watchpoints even if they are at
6734      the same place.  Otherwise the watchpoint will only trigger when
6735      the condition of whichever watchpoint was inserted evaluates to
6736      true, not giving a chance for GDB to check the condition of the
6737      other watchpoint.  */
6738   if ((w1->cond_exp
6739        && target_can_accel_watchpoint_condition (loc1->address, 
6740                                                  loc1->length,
6741                                                  loc1->watchpoint_type,
6742                                                  w1->cond_exp.get ()))
6743       || (w2->cond_exp
6744           && target_can_accel_watchpoint_condition (loc2->address, 
6745                                                     loc2->length,
6746                                                     loc2->watchpoint_type,
6747                                                     w2->cond_exp.get ())))
6748     return 0;
6749
6750   /* Note that this checks the owner's type, not the location's.  In
6751      case the target does not support read watchpoints, but does
6752      support access watchpoints, we'll have bp_read_watchpoint
6753      watchpoints with hw_access locations.  Those should be considered
6754      duplicates of hw_read locations.  The hw_read locations will
6755      become hw_access locations later.  */
6756   return (loc1->owner->type == loc2->owner->type
6757           && loc1->pspace->aspace == loc2->pspace->aspace
6758           && loc1->address == loc2->address
6759           && loc1->length == loc2->length);
6760 }
6761
6762 /* See breakpoint.h.  */
6763
6764 int
6765 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
6766                           const address_space *aspace2, CORE_ADDR addr2)
6767 {
6768   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6769            || aspace1 == aspace2)
6770           && addr1 == addr2);
6771 }
6772
6773 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6774    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6775    matches ASPACE2.  On targets that have global breakpoints, the address
6776    space doesn't really matter.  */
6777
6778 static int
6779 breakpoint_address_match_range (const address_space *aspace1,
6780                                 CORE_ADDR addr1,
6781                                 int len1, const address_space *aspace2,
6782                                 CORE_ADDR addr2)
6783 {
6784   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6785            || aspace1 == aspace2)
6786           && addr2 >= addr1 && addr2 < addr1 + len1);
6787 }
6788
6789 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6790    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6791    matches the breakpoint's address space.  On targets that have global
6792    breakpoints, the address space doesn't really matter.  */
6793
6794 static int
6795 breakpoint_location_address_match (struct bp_location *bl,
6796                                    const address_space *aspace,
6797                                    CORE_ADDR addr)
6798 {
6799   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6800                                     aspace, addr)
6801           || (bl->length
6802               && breakpoint_address_match_range (bl->pspace->aspace,
6803                                                  bl->address, bl->length,
6804                                                  aspace, addr)));
6805 }
6806
6807 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
6808    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
6809    match happens only if ASPACE matches the breakpoint's address
6810    space.  On targets that have global breakpoints, the address space
6811    doesn't really matter.  */
6812
6813 static int
6814 breakpoint_location_address_range_overlap (struct bp_location *bl,
6815                                            const address_space *aspace,
6816                                            CORE_ADDR addr, int len)
6817 {
6818   if (gdbarch_has_global_breakpoints (target_gdbarch ())
6819       || bl->pspace->aspace == aspace)
6820     {
6821       int bl_len = bl->length != 0 ? bl->length : 1;
6822
6823       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
6824         return 1;
6825     }
6826   return 0;
6827 }
6828
6829 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6830    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6831    true, otherwise returns false.  */
6832
6833 static int
6834 tracepoint_locations_match (struct bp_location *loc1,
6835                             struct bp_location *loc2)
6836 {
6837   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6838     /* Since tracepoint locations are never duplicated with others', tracepoint
6839        locations at the same address of different tracepoints are regarded as
6840        different locations.  */
6841     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6842   else
6843     return 0;
6844 }
6845
6846 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6847    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6848    represent the same location.  */
6849
6850 static int
6851 breakpoint_locations_match (struct bp_location *loc1, 
6852                             struct bp_location *loc2)
6853 {
6854   int hw_point1, hw_point2;
6855
6856   /* Both of them must not be in moribund_locations.  */
6857   gdb_assert (loc1->owner != NULL);
6858   gdb_assert (loc2->owner != NULL);
6859
6860   hw_point1 = is_hardware_watchpoint (loc1->owner);
6861   hw_point2 = is_hardware_watchpoint (loc2->owner);
6862
6863   if (hw_point1 != hw_point2)
6864     return 0;
6865   else if (hw_point1)
6866     return watchpoint_locations_match (loc1, loc2);
6867   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6868     return tracepoint_locations_match (loc1, loc2);
6869   else
6870     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6871     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6872                                      loc2->pspace->aspace, loc2->address)
6873             && loc1->length == loc2->length);
6874 }
6875
6876 static void
6877 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6878                                int bnum, int have_bnum)
6879 {
6880   /* The longest string possibly returned by hex_string_custom
6881      is 50 chars.  These must be at least that big for safety.  */
6882   char astr1[64];
6883   char astr2[64];
6884
6885   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6886   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6887   if (have_bnum)
6888     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6889              bnum, astr1, astr2);
6890   else
6891     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6892 }
6893
6894 /* Adjust a breakpoint's address to account for architectural
6895    constraints on breakpoint placement.  Return the adjusted address.
6896    Note: Very few targets require this kind of adjustment.  For most
6897    targets, this function is simply the identity function.  */
6898
6899 static CORE_ADDR
6900 adjust_breakpoint_address (struct gdbarch *gdbarch,
6901                            CORE_ADDR bpaddr, enum bptype bptype)
6902 {
6903   if (bptype == bp_watchpoint
6904       || bptype == bp_hardware_watchpoint
6905       || bptype == bp_read_watchpoint
6906       || bptype == bp_access_watchpoint
6907       || bptype == bp_catchpoint)
6908     {
6909       /* Watchpoints and the various bp_catch_* eventpoints should not
6910          have their addresses modified.  */
6911       return bpaddr;
6912     }
6913   else if (bptype == bp_single_step)
6914     {
6915       /* Single-step breakpoints should not have their addresses
6916          modified.  If there's any architectural constrain that
6917          applies to this address, then it should have already been
6918          taken into account when the breakpoint was created in the
6919          first place.  If we didn't do this, stepping through e.g.,
6920          Thumb-2 IT blocks would break.  */
6921       return bpaddr;
6922     }
6923   else
6924     {
6925       CORE_ADDR adjusted_bpaddr = bpaddr;
6926
6927       if (gdbarch_adjust_breakpoint_address_p (gdbarch))
6928         {
6929           /* Some targets have architectural constraints on the placement
6930              of breakpoint instructions.  Obtain the adjusted address.  */
6931           adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6932         }
6933
6934       adjusted_bpaddr = address_significant (gdbarch, adjusted_bpaddr);
6935
6936       /* An adjusted breakpoint address can significantly alter
6937          a user's expectations.  Print a warning if an adjustment
6938          is required.  */
6939       if (adjusted_bpaddr != bpaddr)
6940         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6941
6942       return adjusted_bpaddr;
6943     }
6944 }
6945
6946 bp_location::bp_location (breakpoint *owner)
6947 {
6948   bp_location *loc = this;
6949
6950   loc->owner = owner;
6951   loc->cond_bytecode = NULL;
6952   loc->shlib_disabled = 0;
6953   loc->enabled = 1;
6954
6955   switch (owner->type)
6956     {
6957     case bp_breakpoint:
6958     case bp_single_step:
6959     case bp_until:
6960     case bp_finish:
6961     case bp_longjmp:
6962     case bp_longjmp_resume:
6963     case bp_longjmp_call_dummy:
6964     case bp_exception:
6965     case bp_exception_resume:
6966     case bp_step_resume:
6967     case bp_hp_step_resume:
6968     case bp_watchpoint_scope:
6969     case bp_call_dummy:
6970     case bp_std_terminate:
6971     case bp_shlib_event:
6972     case bp_thread_event:
6973     case bp_overlay_event:
6974     case bp_jit_event:
6975     case bp_longjmp_master:
6976     case bp_std_terminate_master:
6977     case bp_exception_master:
6978     case bp_gnu_ifunc_resolver:
6979     case bp_gnu_ifunc_resolver_return:
6980     case bp_dprintf:
6981       loc->loc_type = bp_loc_software_breakpoint;
6982       mark_breakpoint_location_modified (loc);
6983       break;
6984     case bp_hardware_breakpoint:
6985       loc->loc_type = bp_loc_hardware_breakpoint;
6986       mark_breakpoint_location_modified (loc);
6987       break;
6988     case bp_hardware_watchpoint:
6989     case bp_read_watchpoint:
6990     case bp_access_watchpoint:
6991       loc->loc_type = bp_loc_hardware_watchpoint;
6992       break;
6993     case bp_watchpoint:
6994     case bp_catchpoint:
6995     case bp_tracepoint:
6996     case bp_fast_tracepoint:
6997     case bp_static_tracepoint:
6998       loc->loc_type = bp_loc_other;
6999       break;
7000     default:
7001       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7002     }
7003
7004   loc->refc = 1;
7005 }
7006
7007 /* Allocate a struct bp_location.  */
7008
7009 static struct bp_location *
7010 allocate_bp_location (struct breakpoint *bpt)
7011 {
7012   return bpt->ops->allocate_location (bpt);
7013 }
7014
7015 static void
7016 free_bp_location (struct bp_location *loc)
7017 {
7018   delete loc;
7019 }
7020
7021 /* Increment reference count.  */
7022
7023 static void
7024 incref_bp_location (struct bp_location *bl)
7025 {
7026   ++bl->refc;
7027 }
7028
7029 /* Decrement reference count.  If the reference count reaches 0,
7030    destroy the bp_location.  Sets *BLP to NULL.  */
7031
7032 static void
7033 decref_bp_location (struct bp_location **blp)
7034 {
7035   gdb_assert ((*blp)->refc > 0);
7036
7037   if (--(*blp)->refc == 0)
7038     free_bp_location (*blp);
7039   *blp = NULL;
7040 }
7041
7042 /* Add breakpoint B at the end of the global breakpoint chain.  */
7043
7044 static breakpoint *
7045 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7046 {
7047   struct breakpoint *b1;
7048   struct breakpoint *result = b.get ();
7049
7050   /* Add this breakpoint to the end of the chain so that a list of
7051      breakpoints will come out in order of increasing numbers.  */
7052
7053   b1 = breakpoint_chain;
7054   if (b1 == 0)
7055     breakpoint_chain = b.release ();
7056   else
7057     {
7058       while (b1->next)
7059         b1 = b1->next;
7060       b1->next = b.release ();
7061     }
7062
7063   return result;
7064 }
7065
7066 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7067
7068 static void
7069 init_raw_breakpoint_without_location (struct breakpoint *b,
7070                                       struct gdbarch *gdbarch,
7071                                       enum bptype bptype,
7072                                       const struct breakpoint_ops *ops)
7073 {
7074   gdb_assert (ops != NULL);
7075
7076   b->ops = ops;
7077   b->type = bptype;
7078   b->gdbarch = gdbarch;
7079   b->language = current_language->la_language;
7080   b->input_radix = input_radix;
7081   b->related_breakpoint = b;
7082 }
7083
7084 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7085    that has type BPTYPE and has no locations as yet.  */
7086
7087 static struct breakpoint *
7088 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7089                                      enum bptype bptype,
7090                                      const struct breakpoint_ops *ops)
7091 {
7092   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7093
7094   init_raw_breakpoint_without_location (b.get (), gdbarch, bptype, ops);
7095   return add_to_breakpoint_chain (std::move (b));
7096 }
7097
7098 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7099    resolutions should be made as the user specified the location explicitly
7100    enough.  */
7101
7102 static void
7103 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7104 {
7105   gdb_assert (loc->owner != NULL);
7106
7107   if (loc->owner->type == bp_breakpoint
7108       || loc->owner->type == bp_hardware_breakpoint
7109       || is_tracepoint (loc->owner))
7110     {
7111       const char *function_name;
7112
7113       if (loc->msymbol != NULL
7114           && (MSYMBOL_TYPE (loc->msymbol) == mst_text_gnu_ifunc
7115               || MSYMBOL_TYPE (loc->msymbol) == mst_data_gnu_ifunc)
7116           && !explicit_loc)
7117         {
7118           struct breakpoint *b = loc->owner;
7119
7120           function_name = MSYMBOL_LINKAGE_NAME (loc->msymbol);
7121
7122           if (b->type == bp_breakpoint && b->loc == loc
7123               && loc->next == NULL && b->related_breakpoint == b)
7124             {
7125               /* Create only the whole new breakpoint of this type but do not
7126                  mess more complicated breakpoints with multiple locations.  */
7127               b->type = bp_gnu_ifunc_resolver;
7128               /* Remember the resolver's address for use by the return
7129                  breakpoint.  */
7130               loc->related_address = loc->address;
7131             }
7132         }
7133       else
7134         find_pc_partial_function (loc->address, &function_name, NULL, NULL);
7135
7136       if (function_name)
7137         loc->function_name = xstrdup (function_name);
7138     }
7139 }
7140
7141 /* Attempt to determine architecture of location identified by SAL.  */
7142 struct gdbarch *
7143 get_sal_arch (struct symtab_and_line sal)
7144 {
7145   if (sal.section)
7146     return get_objfile_arch (sal.section->objfile);
7147   if (sal.symtab)
7148     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7149
7150   return NULL;
7151 }
7152
7153 /* Low level routine for partially initializing a breakpoint of type
7154    BPTYPE.  The newly created breakpoint's address, section, source
7155    file name, and line number are provided by SAL.
7156
7157    It is expected that the caller will complete the initialization of
7158    the newly created breakpoint struct as well as output any status
7159    information regarding the creation of a new breakpoint.  */
7160
7161 static void
7162 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7163                      struct symtab_and_line sal, enum bptype bptype,
7164                      const struct breakpoint_ops *ops)
7165 {
7166   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7167
7168   add_location_to_breakpoint (b, &sal);
7169
7170   if (bptype != bp_catchpoint)
7171     gdb_assert (sal.pspace != NULL);
7172
7173   /* Store the program space that was used to set the breakpoint,
7174      except for ordinary breakpoints, which are independent of the
7175      program space.  */
7176   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7177     b->pspace = sal.pspace;
7178 }
7179
7180 /* set_raw_breakpoint is a low level routine for allocating and
7181    partially initializing a breakpoint of type BPTYPE.  The newly
7182    created breakpoint's address, section, source file name, and line
7183    number are provided by SAL.  The newly created and partially
7184    initialized breakpoint is added to the breakpoint chain and
7185    is also returned as the value of this function.
7186
7187    It is expected that the caller will complete the initialization of
7188    the newly created breakpoint struct as well as output any status
7189    information regarding the creation of a new breakpoint.  In
7190    particular, set_raw_breakpoint does NOT set the breakpoint
7191    number!  Care should be taken to not allow an error to occur
7192    prior to completing the initialization of the breakpoint.  If this
7193    should happen, a bogus breakpoint will be left on the chain.  */
7194
7195 struct breakpoint *
7196 set_raw_breakpoint (struct gdbarch *gdbarch,
7197                     struct symtab_and_line sal, enum bptype bptype,
7198                     const struct breakpoint_ops *ops)
7199 {
7200   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7201
7202   init_raw_breakpoint (b.get (), gdbarch, sal, bptype, ops);
7203   return add_to_breakpoint_chain (std::move (b));
7204 }
7205
7206 /* Call this routine when stepping and nexting to enable a breakpoint
7207    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7208    initiated the operation.  */
7209
7210 void
7211 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7212 {
7213   struct breakpoint *b, *b_tmp;
7214   int thread = tp->global_num;
7215
7216   /* To avoid having to rescan all objfile symbols at every step,
7217      we maintain a list of continually-inserted but always disabled
7218      longjmp "master" breakpoints.  Here, we simply create momentary
7219      clones of those and enable them for the requested thread.  */
7220   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7221     if (b->pspace == current_program_space
7222         && (b->type == bp_longjmp_master
7223             || b->type == bp_exception_master))
7224       {
7225         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7226         struct breakpoint *clone;
7227
7228         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7229            after their removal.  */
7230         clone = momentary_breakpoint_from_master (b, type,
7231                                                   &momentary_breakpoint_ops, 1);
7232         clone->thread = thread;
7233       }
7234
7235   tp->initiating_frame = frame;
7236 }
7237
7238 /* Delete all longjmp breakpoints from THREAD.  */
7239 void
7240 delete_longjmp_breakpoint (int thread)
7241 {
7242   struct breakpoint *b, *b_tmp;
7243
7244   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7245     if (b->type == bp_longjmp || b->type == bp_exception)
7246       {
7247         if (b->thread == thread)
7248           delete_breakpoint (b);
7249       }
7250 }
7251
7252 void
7253 delete_longjmp_breakpoint_at_next_stop (int thread)
7254 {
7255   struct breakpoint *b, *b_tmp;
7256
7257   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7258     if (b->type == bp_longjmp || b->type == bp_exception)
7259       {
7260         if (b->thread == thread)
7261           b->disposition = disp_del_at_next_stop;
7262       }
7263 }
7264
7265 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7266    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7267    pointer to any of them.  Return NULL if this system cannot place longjmp
7268    breakpoints.  */
7269
7270 struct breakpoint *
7271 set_longjmp_breakpoint_for_call_dummy (void)
7272 {
7273   struct breakpoint *b, *retval = NULL;
7274
7275   ALL_BREAKPOINTS (b)
7276     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7277       {
7278         struct breakpoint *new_b;
7279
7280         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7281                                                   &momentary_breakpoint_ops,
7282                                                   1);
7283         new_b->thread = inferior_thread ()->global_num;
7284
7285         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7286
7287         gdb_assert (new_b->related_breakpoint == new_b);
7288         if (retval == NULL)
7289           retval = new_b;
7290         new_b->related_breakpoint = retval;
7291         while (retval->related_breakpoint != new_b->related_breakpoint)
7292           retval = retval->related_breakpoint;
7293         retval->related_breakpoint = new_b;
7294       }
7295
7296   return retval;
7297 }
7298
7299 /* Verify all existing dummy frames and their associated breakpoints for
7300    TP.  Remove those which can no longer be found in the current frame
7301    stack.
7302
7303    You should call this function only at places where it is safe to currently
7304    unwind the whole stack.  Failed stack unwind would discard live dummy
7305    frames.  */
7306
7307 void
7308 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7309 {
7310   struct breakpoint *b, *b_tmp;
7311
7312   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7313     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7314       {
7315         struct breakpoint *dummy_b = b->related_breakpoint;
7316
7317         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7318           dummy_b = dummy_b->related_breakpoint;
7319         if (dummy_b->type != bp_call_dummy
7320             || frame_find_by_id (dummy_b->frame_id) != NULL)
7321           continue;
7322         
7323         dummy_frame_discard (dummy_b->frame_id, tp);
7324
7325         while (b->related_breakpoint != b)
7326           {
7327             if (b_tmp == b->related_breakpoint)
7328               b_tmp = b->related_breakpoint->next;
7329             delete_breakpoint (b->related_breakpoint);
7330           }
7331         delete_breakpoint (b);
7332       }
7333 }
7334
7335 void
7336 enable_overlay_breakpoints (void)
7337 {
7338   struct breakpoint *b;
7339
7340   ALL_BREAKPOINTS (b)
7341     if (b->type == bp_overlay_event)
7342     {
7343       b->enable_state = bp_enabled;
7344       update_global_location_list (UGLL_MAY_INSERT);
7345       overlay_events_enabled = 1;
7346     }
7347 }
7348
7349 void
7350 disable_overlay_breakpoints (void)
7351 {
7352   struct breakpoint *b;
7353
7354   ALL_BREAKPOINTS (b)
7355     if (b->type == bp_overlay_event)
7356     {
7357       b->enable_state = bp_disabled;
7358       update_global_location_list (UGLL_DONT_INSERT);
7359       overlay_events_enabled = 0;
7360     }
7361 }
7362
7363 /* Set an active std::terminate breakpoint for each std::terminate
7364    master breakpoint.  */
7365 void
7366 set_std_terminate_breakpoint (void)
7367 {
7368   struct breakpoint *b, *b_tmp;
7369
7370   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7371     if (b->pspace == current_program_space
7372         && b->type == bp_std_terminate_master)
7373       {
7374         momentary_breakpoint_from_master (b, bp_std_terminate,
7375                                           &momentary_breakpoint_ops, 1);
7376       }
7377 }
7378
7379 /* Delete all the std::terminate breakpoints.  */
7380 void
7381 delete_std_terminate_breakpoint (void)
7382 {
7383   struct breakpoint *b, *b_tmp;
7384
7385   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7386     if (b->type == bp_std_terminate)
7387       delete_breakpoint (b);
7388 }
7389
7390 struct breakpoint *
7391 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7392 {
7393   struct breakpoint *b;
7394
7395   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7396                                   &internal_breakpoint_ops);
7397
7398   b->enable_state = bp_enabled;
7399   /* location has to be used or breakpoint_re_set will delete me.  */
7400   b->location = new_address_location (b->loc->address, NULL, 0);
7401
7402   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7403
7404   return b;
7405 }
7406
7407 struct lang_and_radix
7408   {
7409     enum language lang;
7410     int radix;
7411   };
7412
7413 /* Create a breakpoint for JIT code registration and unregistration.  */
7414
7415 struct breakpoint *
7416 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7417 {
7418   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7419                                      &internal_breakpoint_ops);
7420 }
7421
7422 /* Remove JIT code registration and unregistration breakpoint(s).  */
7423
7424 void
7425 remove_jit_event_breakpoints (void)
7426 {
7427   struct breakpoint *b, *b_tmp;
7428
7429   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7430     if (b->type == bp_jit_event
7431         && b->loc->pspace == current_program_space)
7432       delete_breakpoint (b);
7433 }
7434
7435 void
7436 remove_solib_event_breakpoints (void)
7437 {
7438   struct breakpoint *b, *b_tmp;
7439
7440   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7441     if (b->type == bp_shlib_event
7442         && b->loc->pspace == current_program_space)
7443       delete_breakpoint (b);
7444 }
7445
7446 /* See breakpoint.h.  */
7447
7448 void
7449 remove_solib_event_breakpoints_at_next_stop (void)
7450 {
7451   struct breakpoint *b, *b_tmp;
7452
7453   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7454     if (b->type == bp_shlib_event
7455         && b->loc->pspace == current_program_space)
7456       b->disposition = disp_del_at_next_stop;
7457 }
7458
7459 /* Helper for create_solib_event_breakpoint /
7460    create_and_insert_solib_event_breakpoint.  Allows specifying which
7461    INSERT_MODE to pass through to update_global_location_list.  */
7462
7463 static struct breakpoint *
7464 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7465                                  enum ugll_insert_mode insert_mode)
7466 {
7467   struct breakpoint *b;
7468
7469   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7470                                   &internal_breakpoint_ops);
7471   update_global_location_list_nothrow (insert_mode);
7472   return b;
7473 }
7474
7475 struct breakpoint *
7476 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7477 {
7478   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7479 }
7480
7481 /* See breakpoint.h.  */
7482
7483 struct breakpoint *
7484 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7485 {
7486   struct breakpoint *b;
7487
7488   /* Explicitly tell update_global_location_list to insert
7489      locations.  */
7490   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7491   if (!b->loc->inserted)
7492     {
7493       delete_breakpoint (b);
7494       return NULL;
7495     }
7496   return b;
7497 }
7498
7499 /* Disable any breakpoints that are on code in shared libraries.  Only
7500    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7501
7502 void
7503 disable_breakpoints_in_shlibs (void)
7504 {
7505   struct bp_location *loc, **locp_tmp;
7506
7507   ALL_BP_LOCATIONS (loc, locp_tmp)
7508   {
7509     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7510     struct breakpoint *b = loc->owner;
7511
7512     /* We apply the check to all breakpoints, including disabled for
7513        those with loc->duplicate set.  This is so that when breakpoint
7514        becomes enabled, or the duplicate is removed, gdb will try to
7515        insert all breakpoints.  If we don't set shlib_disabled here,
7516        we'll try to insert those breakpoints and fail.  */
7517     if (((b->type == bp_breakpoint)
7518          || (b->type == bp_jit_event)
7519          || (b->type == bp_hardware_breakpoint)
7520          || (is_tracepoint (b)))
7521         && loc->pspace == current_program_space
7522         && !loc->shlib_disabled
7523         && solib_name_from_address (loc->pspace, loc->address)
7524         )
7525       {
7526         loc->shlib_disabled = 1;
7527       }
7528   }
7529 }
7530
7531 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7532    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7533    disabled ones can just stay disabled.  */
7534
7535 static void
7536 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7537 {
7538   struct bp_location *loc, **locp_tmp;
7539   int disabled_shlib_breaks = 0;
7540
7541   ALL_BP_LOCATIONS (loc, locp_tmp)
7542   {
7543     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7544     struct breakpoint *b = loc->owner;
7545
7546     if (solib->pspace == loc->pspace
7547         && !loc->shlib_disabled
7548         && (((b->type == bp_breakpoint
7549               || b->type == bp_jit_event
7550               || b->type == bp_hardware_breakpoint)
7551              && (loc->loc_type == bp_loc_hardware_breakpoint
7552                  || loc->loc_type == bp_loc_software_breakpoint))
7553             || is_tracepoint (b))
7554         && solib_contains_address_p (solib, loc->address))
7555       {
7556         loc->shlib_disabled = 1;
7557         /* At this point, we cannot rely on remove_breakpoint
7558            succeeding so we must mark the breakpoint as not inserted
7559            to prevent future errors occurring in remove_breakpoints.  */
7560         loc->inserted = 0;
7561
7562         /* This may cause duplicate notifications for the same breakpoint.  */
7563         gdb::observers::breakpoint_modified.notify (b);
7564
7565         if (!disabled_shlib_breaks)
7566           {
7567             target_terminal::ours_for_output ();
7568             warning (_("Temporarily disabling breakpoints "
7569                        "for unloaded shared library \"%s\""),
7570                      solib->so_name);
7571           }
7572         disabled_shlib_breaks = 1;
7573       }
7574   }
7575 }
7576
7577 /* Disable any breakpoints and tracepoints in OBJFILE upon
7578    notification of free_objfile.  Only apply to enabled breakpoints,
7579    disabled ones can just stay disabled.  */
7580
7581 static void
7582 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7583 {
7584   struct breakpoint *b;
7585
7586   if (objfile == NULL)
7587     return;
7588
7589   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7590      managed by the user with add-symbol-file/remove-symbol-file.
7591      Similarly to how breakpoints in shared libraries are handled in
7592      response to "nosharedlibrary", mark breakpoints in such modules
7593      shlib_disabled so they end up uninserted on the next global
7594      location list update.  Shared libraries not loaded by the user
7595      aren't handled here -- they're already handled in
7596      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7597      solib_unloaded observer.  We skip objfiles that are not
7598      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7599      main objfile).  */
7600   if ((objfile->flags & OBJF_SHARED) == 0
7601       || (objfile->flags & OBJF_USERLOADED) == 0)
7602     return;
7603
7604   ALL_BREAKPOINTS (b)
7605     {
7606       struct bp_location *loc;
7607       int bp_modified = 0;
7608
7609       if (!is_breakpoint (b) && !is_tracepoint (b))
7610         continue;
7611
7612       for (loc = b->loc; loc != NULL; loc = loc->next)
7613         {
7614           CORE_ADDR loc_addr = loc->address;
7615
7616           if (loc->loc_type != bp_loc_hardware_breakpoint
7617               && loc->loc_type != bp_loc_software_breakpoint)
7618             continue;
7619
7620           if (loc->shlib_disabled != 0)
7621             continue;
7622
7623           if (objfile->pspace != loc->pspace)
7624             continue;
7625
7626           if (loc->loc_type != bp_loc_hardware_breakpoint
7627               && loc->loc_type != bp_loc_software_breakpoint)
7628             continue;
7629
7630           if (is_addr_in_objfile (loc_addr, objfile))
7631             {
7632               loc->shlib_disabled = 1;
7633               /* At this point, we don't know whether the object was
7634                  unmapped from the inferior or not, so leave the
7635                  inserted flag alone.  We'll handle failure to
7636                  uninsert quietly, in case the object was indeed
7637                  unmapped.  */
7638
7639               mark_breakpoint_location_modified (loc);
7640
7641               bp_modified = 1;
7642             }
7643         }
7644
7645       if (bp_modified)
7646         gdb::observers::breakpoint_modified.notify (b);
7647     }
7648 }
7649
7650 /* FORK & VFORK catchpoints.  */
7651
7652 /* An instance of this type is used to represent a fork or vfork
7653    catchpoint.  A breakpoint is really of this type iff its ops pointer points
7654    to CATCH_FORK_BREAKPOINT_OPS.  */
7655
7656 struct fork_catchpoint : public breakpoint
7657 {
7658   /* Process id of a child process whose forking triggered this
7659      catchpoint.  This field is only valid immediately after this
7660      catchpoint has triggered.  */
7661   ptid_t forked_inferior_pid;
7662 };
7663
7664 /* Implement the "insert" breakpoint_ops method for fork
7665    catchpoints.  */
7666
7667 static int
7668 insert_catch_fork (struct bp_location *bl)
7669 {
7670   return target_insert_fork_catchpoint (inferior_ptid.pid ());
7671 }
7672
7673 /* Implement the "remove" breakpoint_ops method for fork
7674    catchpoints.  */
7675
7676 static int
7677 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
7678 {
7679   return target_remove_fork_catchpoint (inferior_ptid.pid ());
7680 }
7681
7682 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7683    catchpoints.  */
7684
7685 static int
7686 breakpoint_hit_catch_fork (const struct bp_location *bl,
7687                            const address_space *aspace, CORE_ADDR bp_addr,
7688                            const struct target_waitstatus *ws)
7689 {
7690   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7691
7692   if (ws->kind != TARGET_WAITKIND_FORKED)
7693     return 0;
7694
7695   c->forked_inferior_pid = ws->value.related_pid;
7696   return 1;
7697 }
7698
7699 /* Implement the "print_it" breakpoint_ops method for fork
7700    catchpoints.  */
7701
7702 static enum print_stop_action
7703 print_it_catch_fork (bpstat bs)
7704 {
7705   struct ui_out *uiout = current_uiout;
7706   struct breakpoint *b = bs->breakpoint_at;
7707   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7708
7709   annotate_catchpoint (b->number);
7710   maybe_print_thread_hit_breakpoint (uiout);
7711   if (b->disposition == disp_del)
7712     uiout->text ("Temporary catchpoint ");
7713   else
7714     uiout->text ("Catchpoint ");
7715   if (uiout->is_mi_like_p ())
7716     {
7717       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
7718       uiout->field_string ("disp", bpdisp_text (b->disposition));
7719     }
7720   uiout->field_int ("bkptno", b->number);
7721   uiout->text (" (forked process ");
7722   uiout->field_int ("newpid", c->forked_inferior_pid.pid ());
7723   uiout->text ("), ");
7724   return PRINT_SRC_AND_LOC;
7725 }
7726
7727 /* Implement the "print_one" breakpoint_ops method for fork
7728    catchpoints.  */
7729
7730 static void
7731 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7732 {
7733   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7734   struct value_print_options opts;
7735   struct ui_out *uiout = current_uiout;
7736
7737   get_user_print_options (&opts);
7738
7739   /* Field 4, the address, is omitted (which makes the columns not
7740      line up too nicely with the headers, but the effect is relatively
7741      readable).  */
7742   if (opts.addressprint)
7743     uiout->field_skip ("addr");
7744   annotate_field (5);
7745   uiout->text ("fork");
7746   if (c->forked_inferior_pid != null_ptid)
7747     {
7748       uiout->text (", process ");
7749       uiout->field_int ("what", c->forked_inferior_pid.pid ());
7750       uiout->spaces (1);
7751     }
7752
7753   if (uiout->is_mi_like_p ())
7754     uiout->field_string ("catch-type", "fork");
7755 }
7756
7757 /* Implement the "print_mention" breakpoint_ops method for fork
7758    catchpoints.  */
7759
7760 static void
7761 print_mention_catch_fork (struct breakpoint *b)
7762 {
7763   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7764 }
7765
7766 /* Implement the "print_recreate" breakpoint_ops method for fork
7767    catchpoints.  */
7768
7769 static void
7770 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7771 {
7772   fprintf_unfiltered (fp, "catch fork");
7773   print_recreate_thread (b, fp);
7774 }
7775
7776 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7777
7778 static struct breakpoint_ops catch_fork_breakpoint_ops;
7779
7780 /* Implement the "insert" breakpoint_ops method for vfork
7781    catchpoints.  */
7782
7783 static int
7784 insert_catch_vfork (struct bp_location *bl)
7785 {
7786   return target_insert_vfork_catchpoint (inferior_ptid.pid ());
7787 }
7788
7789 /* Implement the "remove" breakpoint_ops method for vfork
7790    catchpoints.  */
7791
7792 static int
7793 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
7794 {
7795   return target_remove_vfork_catchpoint (inferior_ptid.pid ());
7796 }
7797
7798 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7799    catchpoints.  */
7800
7801 static int
7802 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7803                             const address_space *aspace, CORE_ADDR bp_addr,
7804                             const struct target_waitstatus *ws)
7805 {
7806   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7807
7808   if (ws->kind != TARGET_WAITKIND_VFORKED)
7809     return 0;
7810
7811   c->forked_inferior_pid = ws->value.related_pid;
7812   return 1;
7813 }
7814
7815 /* Implement the "print_it" breakpoint_ops method for vfork
7816    catchpoints.  */
7817
7818 static enum print_stop_action
7819 print_it_catch_vfork (bpstat bs)
7820 {
7821   struct ui_out *uiout = current_uiout;
7822   struct breakpoint *b = bs->breakpoint_at;
7823   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7824
7825   annotate_catchpoint (b->number);
7826   maybe_print_thread_hit_breakpoint (uiout);
7827   if (b->disposition == disp_del)
7828     uiout->text ("Temporary catchpoint ");
7829   else
7830     uiout->text ("Catchpoint ");
7831   if (uiout->is_mi_like_p ())
7832     {
7833       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
7834       uiout->field_string ("disp", bpdisp_text (b->disposition));
7835     }
7836   uiout->field_int ("bkptno", b->number);
7837   uiout->text (" (vforked process ");
7838   uiout->field_int ("newpid", c->forked_inferior_pid.pid ());
7839   uiout->text ("), ");
7840   return PRINT_SRC_AND_LOC;
7841 }
7842
7843 /* Implement the "print_one" breakpoint_ops method for vfork
7844    catchpoints.  */
7845
7846 static void
7847 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7848 {
7849   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7850   struct value_print_options opts;
7851   struct ui_out *uiout = current_uiout;
7852
7853   get_user_print_options (&opts);
7854   /* Field 4, the address, is omitted (which makes the columns not
7855      line up too nicely with the headers, but the effect is relatively
7856      readable).  */
7857   if (opts.addressprint)
7858     uiout->field_skip ("addr");
7859   annotate_field (5);
7860   uiout->text ("vfork");
7861   if (c->forked_inferior_pid != null_ptid)
7862     {
7863       uiout->text (", process ");
7864       uiout->field_int ("what", c->forked_inferior_pid.pid ());
7865       uiout->spaces (1);
7866     }
7867
7868   if (uiout->is_mi_like_p ())
7869     uiout->field_string ("catch-type", "vfork");
7870 }
7871
7872 /* Implement the "print_mention" breakpoint_ops method for vfork
7873    catchpoints.  */
7874
7875 static void
7876 print_mention_catch_vfork (struct breakpoint *b)
7877 {
7878   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7879 }
7880
7881 /* Implement the "print_recreate" breakpoint_ops method for vfork
7882    catchpoints.  */
7883
7884 static void
7885 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7886 {
7887   fprintf_unfiltered (fp, "catch vfork");
7888   print_recreate_thread (b, fp);
7889 }
7890
7891 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7892
7893 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7894
7895 /* An instance of this type is used to represent an solib catchpoint.
7896    A breakpoint is really of this type iff its ops pointer points to
7897    CATCH_SOLIB_BREAKPOINT_OPS.  */
7898
7899 struct solib_catchpoint : public breakpoint
7900 {
7901   ~solib_catchpoint () override;
7902
7903   /* True for "catch load", false for "catch unload".  */
7904   unsigned char is_load;
7905
7906   /* Regular expression to match, if any.  COMPILED is only valid when
7907      REGEX is non-NULL.  */
7908   char *regex;
7909   std::unique_ptr<compiled_regex> compiled;
7910 };
7911
7912 solib_catchpoint::~solib_catchpoint ()
7913 {
7914   xfree (this->regex);
7915 }
7916
7917 static int
7918 insert_catch_solib (struct bp_location *ignore)
7919 {
7920   return 0;
7921 }
7922
7923 static int
7924 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
7925 {
7926   return 0;
7927 }
7928
7929 static int
7930 breakpoint_hit_catch_solib (const struct bp_location *bl,
7931                             const address_space *aspace,
7932                             CORE_ADDR bp_addr,
7933                             const struct target_waitstatus *ws)
7934 {
7935   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7936   struct breakpoint *other;
7937
7938   if (ws->kind == TARGET_WAITKIND_LOADED)
7939     return 1;
7940
7941   ALL_BREAKPOINTS (other)
7942   {
7943     struct bp_location *other_bl;
7944
7945     if (other == bl->owner)
7946       continue;
7947
7948     if (other->type != bp_shlib_event)
7949       continue;
7950
7951     if (self->pspace != NULL && other->pspace != self->pspace)
7952       continue;
7953
7954     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7955       {
7956         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7957           return 1;
7958       }
7959   }
7960
7961   return 0;
7962 }
7963
7964 static void
7965 check_status_catch_solib (struct bpstats *bs)
7966 {
7967   struct solib_catchpoint *self
7968     = (struct solib_catchpoint *) bs->breakpoint_at;
7969
7970   if (self->is_load)
7971     {
7972       for (so_list *iter : current_program_space->added_solibs)
7973         {
7974           if (!self->regex
7975               || self->compiled->exec (iter->so_name, 0, NULL, 0) == 0)
7976             return;
7977         }
7978     }
7979   else
7980     {
7981       for (const std::string &iter : current_program_space->deleted_solibs)
7982         {
7983           if (!self->regex
7984               || self->compiled->exec (iter.c_str (), 0, NULL, 0) == 0)
7985             return;
7986         }
7987     }
7988
7989   bs->stop = 0;
7990   bs->print_it = print_it_noop;
7991 }
7992
7993 static enum print_stop_action
7994 print_it_catch_solib (bpstat bs)
7995 {
7996   struct breakpoint *b = bs->breakpoint_at;
7997   struct ui_out *uiout = current_uiout;
7998
7999   annotate_catchpoint (b->number);
8000   maybe_print_thread_hit_breakpoint (uiout);
8001   if (b->disposition == disp_del)
8002     uiout->text ("Temporary catchpoint ");
8003   else
8004     uiout->text ("Catchpoint ");
8005   uiout->field_int ("bkptno", b->number);
8006   uiout->text ("\n");
8007   if (uiout->is_mi_like_p ())
8008     uiout->field_string ("disp", bpdisp_text (b->disposition));
8009   print_solib_event (1);
8010   return PRINT_SRC_AND_LOC;
8011 }
8012
8013 static void
8014 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8015 {
8016   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8017   struct value_print_options opts;
8018   struct ui_out *uiout = current_uiout;
8019
8020   get_user_print_options (&opts);
8021   /* Field 4, the address, is omitted (which makes the columns not
8022      line up too nicely with the headers, but the effect is relatively
8023      readable).  */
8024   if (opts.addressprint)
8025     {
8026       annotate_field (4);
8027       uiout->field_skip ("addr");
8028     }
8029
8030   std::string msg;
8031   annotate_field (5);
8032   if (self->is_load)
8033     {
8034       if (self->regex)
8035         msg = string_printf (_("load of library matching %s"), self->regex);
8036       else
8037         msg = _("load of library");
8038     }
8039   else
8040     {
8041       if (self->regex)
8042         msg = string_printf (_("unload of library matching %s"), self->regex);
8043       else
8044         msg = _("unload of library");
8045     }
8046   uiout->field_string ("what", msg);
8047
8048   if (uiout->is_mi_like_p ())
8049     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8050 }
8051
8052 static void
8053 print_mention_catch_solib (struct breakpoint *b)
8054 {
8055   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8056
8057   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8058                    self->is_load ? "load" : "unload");
8059 }
8060
8061 static void
8062 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8063 {
8064   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8065
8066   fprintf_unfiltered (fp, "%s %s",
8067                       b->disposition == disp_del ? "tcatch" : "catch",
8068                       self->is_load ? "load" : "unload");
8069   if (self->regex)
8070     fprintf_unfiltered (fp, " %s", self->regex);
8071   fprintf_unfiltered (fp, "\n");
8072 }
8073
8074 static struct breakpoint_ops catch_solib_breakpoint_ops;
8075
8076 /* Shared helper function (MI and CLI) for creating and installing
8077    a shared object event catchpoint.  If IS_LOAD is non-zero then
8078    the events to be caught are load events, otherwise they are
8079    unload events.  If IS_TEMP is non-zero the catchpoint is a
8080    temporary one.  If ENABLED is non-zero the catchpoint is
8081    created in an enabled state.  */
8082
8083 void
8084 add_solib_catchpoint (const char *arg, int is_load, int is_temp, int enabled)
8085 {
8086   struct gdbarch *gdbarch = get_current_arch ();
8087
8088   if (!arg)
8089     arg = "";
8090   arg = skip_spaces (arg);
8091
8092   std::unique_ptr<solib_catchpoint> c (new solib_catchpoint ());
8093
8094   if (*arg != '\0')
8095     {
8096       c->compiled.reset (new compiled_regex (arg, REG_NOSUB,
8097                                              _("Invalid regexp")));
8098       c->regex = xstrdup (arg);
8099     }
8100
8101   c->is_load = is_load;
8102   init_catchpoint (c.get (), gdbarch, is_temp, NULL,
8103                    &catch_solib_breakpoint_ops);
8104
8105   c->enable_state = enabled ? bp_enabled : bp_disabled;
8106
8107   install_breakpoint (0, std::move (c), 1);
8108 }
8109
8110 /* A helper function that does all the work for "catch load" and
8111    "catch unload".  */
8112
8113 static void
8114 catch_load_or_unload (const char *arg, int from_tty, int is_load,
8115                       struct cmd_list_element *command)
8116 {
8117   int tempflag;
8118   const int enabled = 1;
8119
8120   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8121
8122   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8123 }
8124
8125 static void
8126 catch_load_command_1 (const char *arg, int from_tty,
8127                       struct cmd_list_element *command)
8128 {
8129   catch_load_or_unload (arg, from_tty, 1, command);
8130 }
8131
8132 static void
8133 catch_unload_command_1 (const char *arg, int from_tty,
8134                         struct cmd_list_element *command)
8135 {
8136   catch_load_or_unload (arg, from_tty, 0, command);
8137 }
8138
8139 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8140    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8141    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8142    the breakpoint_ops structure associated to the catchpoint.  */
8143
8144 void
8145 init_catchpoint (struct breakpoint *b,
8146                  struct gdbarch *gdbarch, int tempflag,
8147                  const char *cond_string,
8148                  const struct breakpoint_ops *ops)
8149 {
8150   symtab_and_line sal;
8151   sal.pspace = current_program_space;
8152
8153   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8154
8155   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8156   b->disposition = tempflag ? disp_del : disp_donttouch;
8157 }
8158
8159 void
8160 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8161 {
8162   breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8163   set_breakpoint_number (internal, b);
8164   if (is_tracepoint (b))
8165     set_tracepoint_count (breakpoint_count);
8166   if (!internal)
8167     mention (b);
8168   gdb::observers::breakpoint_created.notify (b);
8169
8170   if (update_gll)
8171     update_global_location_list (UGLL_MAY_INSERT);
8172 }
8173
8174 static void
8175 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8176                                     int tempflag, const char *cond_string,
8177                                     const struct breakpoint_ops *ops)
8178 {
8179   std::unique_ptr<fork_catchpoint> c (new fork_catchpoint ());
8180
8181   init_catchpoint (c.get (), gdbarch, tempflag, cond_string, ops);
8182
8183   c->forked_inferior_pid = null_ptid;
8184
8185   install_breakpoint (0, std::move (c), 1);
8186 }
8187
8188 /* Exec catchpoints.  */
8189
8190 /* An instance of this type is used to represent an exec catchpoint.
8191    A breakpoint is really of this type iff its ops pointer points to
8192    CATCH_EXEC_BREAKPOINT_OPS.  */
8193
8194 struct exec_catchpoint : public breakpoint
8195 {
8196   ~exec_catchpoint () override;
8197
8198   /* Filename of a program whose exec triggered this catchpoint.
8199      This field is only valid immediately after this catchpoint has
8200      triggered.  */
8201   char *exec_pathname;
8202 };
8203
8204 /* Exec catchpoint destructor.  */
8205
8206 exec_catchpoint::~exec_catchpoint ()
8207 {
8208   xfree (this->exec_pathname);
8209 }
8210
8211 static int
8212 insert_catch_exec (struct bp_location *bl)
8213 {
8214   return target_insert_exec_catchpoint (inferior_ptid.pid ());
8215 }
8216
8217 static int
8218 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8219 {
8220   return target_remove_exec_catchpoint (inferior_ptid.pid ());
8221 }
8222
8223 static int
8224 breakpoint_hit_catch_exec (const struct bp_location *bl,
8225                            const address_space *aspace, CORE_ADDR bp_addr,
8226                            const struct target_waitstatus *ws)
8227 {
8228   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8229
8230   if (ws->kind != TARGET_WAITKIND_EXECD)
8231     return 0;
8232
8233   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8234   return 1;
8235 }
8236
8237 static enum print_stop_action
8238 print_it_catch_exec (bpstat bs)
8239 {
8240   struct ui_out *uiout = current_uiout;
8241   struct breakpoint *b = bs->breakpoint_at;
8242   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8243
8244   annotate_catchpoint (b->number);
8245   maybe_print_thread_hit_breakpoint (uiout);
8246   if (b->disposition == disp_del)
8247     uiout->text ("Temporary catchpoint ");
8248   else
8249     uiout->text ("Catchpoint ");
8250   if (uiout->is_mi_like_p ())
8251     {
8252       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8253       uiout->field_string ("disp", bpdisp_text (b->disposition));
8254     }
8255   uiout->field_int ("bkptno", b->number);
8256   uiout->text (" (exec'd ");
8257   uiout->field_string ("new-exec", c->exec_pathname);
8258   uiout->text ("), ");
8259
8260   return PRINT_SRC_AND_LOC;
8261 }
8262
8263 static void
8264 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8265 {
8266   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8267   struct value_print_options opts;
8268   struct ui_out *uiout = current_uiout;
8269
8270   get_user_print_options (&opts);
8271
8272   /* Field 4, the address, is omitted (which makes the columns
8273      not line up too nicely with the headers, but the effect
8274      is relatively readable).  */
8275   if (opts.addressprint)
8276     uiout->field_skip ("addr");
8277   annotate_field (5);
8278   uiout->text ("exec");
8279   if (c->exec_pathname != NULL)
8280     {
8281       uiout->text (", program \"");
8282       uiout->field_string ("what", c->exec_pathname);
8283       uiout->text ("\" ");
8284     }
8285
8286   if (uiout->is_mi_like_p ())
8287     uiout->field_string ("catch-type", "exec");
8288 }
8289
8290 static void
8291 print_mention_catch_exec (struct breakpoint *b)
8292 {
8293   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8294 }
8295
8296 /* Implement the "print_recreate" breakpoint_ops method for exec
8297    catchpoints.  */
8298
8299 static void
8300 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8301 {
8302   fprintf_unfiltered (fp, "catch exec");
8303   print_recreate_thread (b, fp);
8304 }
8305
8306 static struct breakpoint_ops catch_exec_breakpoint_ops;
8307
8308 static int
8309 hw_breakpoint_used_count (void)
8310 {
8311   int i = 0;
8312   struct breakpoint *b;
8313   struct bp_location *bl;
8314
8315   ALL_BREAKPOINTS (b)
8316   {
8317     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8318       for (bl = b->loc; bl; bl = bl->next)
8319         {
8320           /* Special types of hardware breakpoints may use more than
8321              one register.  */
8322           i += b->ops->resources_needed (bl);
8323         }
8324   }
8325
8326   return i;
8327 }
8328
8329 /* Returns the resources B would use if it were a hardware
8330    watchpoint.  */
8331
8332 static int
8333 hw_watchpoint_use_count (struct breakpoint *b)
8334 {
8335   int i = 0;
8336   struct bp_location *bl;
8337
8338   if (!breakpoint_enabled (b))
8339     return 0;
8340
8341   for (bl = b->loc; bl; bl = bl->next)
8342     {
8343       /* Special types of hardware watchpoints may use more than
8344          one register.  */
8345       i += b->ops->resources_needed (bl);
8346     }
8347
8348   return i;
8349 }
8350
8351 /* Returns the sum the used resources of all hardware watchpoints of
8352    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8353    the sum of the used resources of all hardware watchpoints of other
8354    types _not_ TYPE.  */
8355
8356 static int
8357 hw_watchpoint_used_count_others (struct breakpoint *except,
8358                                  enum bptype type, int *other_type_used)
8359 {
8360   int i = 0;
8361   struct breakpoint *b;
8362
8363   *other_type_used = 0;
8364   ALL_BREAKPOINTS (b)
8365     {
8366       if (b == except)
8367         continue;
8368       if (!breakpoint_enabled (b))
8369         continue;
8370
8371       if (b->type == type)
8372         i += hw_watchpoint_use_count (b);
8373       else if (is_hardware_watchpoint (b))
8374         *other_type_used = 1;
8375     }
8376
8377   return i;
8378 }
8379
8380 void
8381 disable_watchpoints_before_interactive_call_start (void)
8382 {
8383   struct breakpoint *b;
8384
8385   ALL_BREAKPOINTS (b)
8386   {
8387     if (is_watchpoint (b) && breakpoint_enabled (b))
8388       {
8389         b->enable_state = bp_call_disabled;
8390         update_global_location_list (UGLL_DONT_INSERT);
8391       }
8392   }
8393 }
8394
8395 void
8396 enable_watchpoints_after_interactive_call_stop (void)
8397 {
8398   struct breakpoint *b;
8399
8400   ALL_BREAKPOINTS (b)
8401   {
8402     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8403       {
8404         b->enable_state = bp_enabled;
8405         update_global_location_list (UGLL_MAY_INSERT);
8406       }
8407   }
8408 }
8409
8410 void
8411 disable_breakpoints_before_startup (void)
8412 {
8413   current_program_space->executing_startup = 1;
8414   update_global_location_list (UGLL_DONT_INSERT);
8415 }
8416
8417 void
8418 enable_breakpoints_after_startup (void)
8419 {
8420   current_program_space->executing_startup = 0;
8421   breakpoint_re_set ();
8422 }
8423
8424 /* Create a new single-step breakpoint for thread THREAD, with no
8425    locations.  */
8426
8427 static struct breakpoint *
8428 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8429 {
8430   std::unique_ptr<breakpoint> b (new breakpoint ());
8431
8432   init_raw_breakpoint_without_location (b.get (), gdbarch, bp_single_step,
8433                                         &momentary_breakpoint_ops);
8434
8435   b->disposition = disp_donttouch;
8436   b->frame_id = null_frame_id;
8437
8438   b->thread = thread;
8439   gdb_assert (b->thread != 0);
8440
8441   return add_to_breakpoint_chain (std::move (b));
8442 }
8443
8444 /* Set a momentary breakpoint of type TYPE at address specified by
8445    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8446    frame.  */
8447
8448 breakpoint_up
8449 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8450                           struct frame_id frame_id, enum bptype type)
8451 {
8452   struct breakpoint *b;
8453
8454   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8455      tail-called one.  */
8456   gdb_assert (!frame_id_artificial_p (frame_id));
8457
8458   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8459   b->enable_state = bp_enabled;
8460   b->disposition = disp_donttouch;
8461   b->frame_id = frame_id;
8462
8463   b->thread = inferior_thread ()->global_num;
8464
8465   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8466
8467   return breakpoint_up (b);
8468 }
8469
8470 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8471    The new breakpoint will have type TYPE, use OPS as its
8472    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8473
8474 static struct breakpoint *
8475 momentary_breakpoint_from_master (struct breakpoint *orig,
8476                                   enum bptype type,
8477                                   const struct breakpoint_ops *ops,
8478                                   int loc_enabled)
8479 {
8480   struct breakpoint *copy;
8481
8482   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8483   copy->loc = allocate_bp_location (copy);
8484   set_breakpoint_location_function (copy->loc, 1);
8485
8486   copy->loc->gdbarch = orig->loc->gdbarch;
8487   copy->loc->requested_address = orig->loc->requested_address;
8488   copy->loc->address = orig->loc->address;
8489   copy->loc->section = orig->loc->section;
8490   copy->loc->pspace = orig->loc->pspace;
8491   copy->loc->probe = orig->loc->probe;
8492   copy->loc->line_number = orig->loc->line_number;
8493   copy->loc->symtab = orig->loc->symtab;
8494   copy->loc->enabled = loc_enabled;
8495   copy->frame_id = orig->frame_id;
8496   copy->thread = orig->thread;
8497   copy->pspace = orig->pspace;
8498
8499   copy->enable_state = bp_enabled;
8500   copy->disposition = disp_donttouch;
8501   copy->number = internal_breakpoint_number--;
8502
8503   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8504   return copy;
8505 }
8506
8507 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8508    ORIG is NULL.  */
8509
8510 struct breakpoint *
8511 clone_momentary_breakpoint (struct breakpoint *orig)
8512 {
8513   /* If there's nothing to clone, then return nothing.  */
8514   if (orig == NULL)
8515     return NULL;
8516
8517   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8518 }
8519
8520 breakpoint_up
8521 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8522                                 enum bptype type)
8523 {
8524   struct symtab_and_line sal;
8525
8526   sal = find_pc_line (pc, 0);
8527   sal.pc = pc;
8528   sal.section = find_pc_overlay (pc);
8529   sal.explicit_pc = 1;
8530
8531   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8532 }
8533 \f
8534
8535 /* Tell the user we have just set a breakpoint B.  */
8536
8537 static void
8538 mention (struct breakpoint *b)
8539 {
8540   b->ops->print_mention (b);
8541   current_uiout->text ("\n");
8542 }
8543 \f
8544
8545 static int bp_loc_is_permanent (struct bp_location *loc);
8546
8547 static struct bp_location *
8548 add_location_to_breakpoint (struct breakpoint *b,
8549                             const struct symtab_and_line *sal)
8550 {
8551   struct bp_location *loc, **tmp;
8552   CORE_ADDR adjusted_address;
8553   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8554
8555   if (loc_gdbarch == NULL)
8556     loc_gdbarch = b->gdbarch;
8557
8558   /* Adjust the breakpoint's address prior to allocating a location.
8559      Once we call allocate_bp_location(), that mostly uninitialized
8560      location will be placed on the location chain.  Adjustment of the
8561      breakpoint may cause target_read_memory() to be called and we do
8562      not want its scan of the location chain to find a breakpoint and
8563      location that's only been partially initialized.  */
8564   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8565                                                 sal->pc, b->type);
8566
8567   /* Sort the locations by their ADDRESS.  */
8568   loc = allocate_bp_location (b);
8569   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8570        tmp = &((*tmp)->next))
8571     ;
8572   loc->next = *tmp;
8573   *tmp = loc;
8574
8575   loc->requested_address = sal->pc;
8576   loc->address = adjusted_address;
8577   loc->pspace = sal->pspace;
8578   loc->probe.prob = sal->prob;
8579   loc->probe.objfile = sal->objfile;
8580   gdb_assert (loc->pspace != NULL);
8581   loc->section = sal->section;
8582   loc->gdbarch = loc_gdbarch;
8583   loc->line_number = sal->line;
8584   loc->symtab = sal->symtab;
8585   loc->symbol = sal->symbol;
8586   loc->msymbol = sal->msymbol;
8587   loc->objfile = sal->objfile;
8588
8589   set_breakpoint_location_function (loc,
8590                                     sal->explicit_pc || sal->explicit_line);
8591
8592   /* While by definition, permanent breakpoints are already present in the
8593      code, we don't mark the location as inserted.  Normally one would expect
8594      that GDB could rely on that breakpoint instruction to stop the program,
8595      thus removing the need to insert its own breakpoint, except that executing
8596      the breakpoint instruction can kill the target instead of reporting a
8597      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8598      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8599      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8600      breakpoint be inserted normally results in QEMU knowing about the GDB
8601      breakpoint, and thus trap before the breakpoint instruction is executed.
8602      (If GDB later needs to continue execution past the permanent breakpoint,
8603      it manually increments the PC, thus avoiding executing the breakpoint
8604      instruction.)  */
8605   if (bp_loc_is_permanent (loc))
8606     loc->permanent = 1;
8607
8608   return loc;
8609 }
8610 \f
8611
8612 /* See breakpoint.h.  */
8613
8614 int
8615 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
8616 {
8617   int len;
8618   CORE_ADDR addr;
8619   const gdb_byte *bpoint;
8620   gdb_byte *target_mem;
8621
8622   addr = address;
8623   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
8624
8625   /* Software breakpoints unsupported?  */
8626   if (bpoint == NULL)
8627     return 0;
8628
8629   target_mem = (gdb_byte *) alloca (len);
8630
8631   /* Enable the automatic memory restoration from breakpoints while
8632      we read the memory.  Otherwise we could say about our temporary
8633      breakpoints they are permanent.  */
8634   scoped_restore restore_memory
8635     = make_scoped_restore_show_memory_breakpoints (0);
8636
8637   if (target_read_memory (address, target_mem, len) == 0
8638       && memcmp (target_mem, bpoint, len) == 0)
8639     return 1;
8640
8641   return 0;
8642 }
8643
8644 /* Return 1 if LOC is pointing to a permanent breakpoint,
8645    return 0 otherwise.  */
8646
8647 static int
8648 bp_loc_is_permanent (struct bp_location *loc)
8649 {
8650   gdb_assert (loc != NULL);
8651
8652   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
8653      attempt to read from the addresses the locations of these breakpoint types
8654      point to.  program_breakpoint_here_p, below, will attempt to read
8655      memory.  */
8656   if (!breakpoint_address_is_meaningful (loc->owner))
8657     return 0;
8658
8659   scoped_restore_current_pspace_and_thread restore_pspace_thread;
8660   switch_to_program_space_and_thread (loc->pspace);
8661   return program_breakpoint_here_p (loc->gdbarch, loc->address);
8662 }
8663
8664 /* Build a command list for the dprintf corresponding to the current
8665    settings of the dprintf style options.  */
8666
8667 static void
8668 update_dprintf_command_list (struct breakpoint *b)
8669 {
8670   char *dprintf_args = b->extra_string;
8671   char *printf_line = NULL;
8672
8673   if (!dprintf_args)
8674     return;
8675
8676   dprintf_args = skip_spaces (dprintf_args);
8677
8678   /* Allow a comma, as it may have terminated a location, but don't
8679      insist on it.  */
8680   if (*dprintf_args == ',')
8681     ++dprintf_args;
8682   dprintf_args = skip_spaces (dprintf_args);
8683
8684   if (*dprintf_args != '"')
8685     error (_("Bad format string, missing '\"'."));
8686
8687   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8688     printf_line = xstrprintf ("printf %s", dprintf_args);
8689   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8690     {
8691       if (!dprintf_function)
8692         error (_("No function supplied for dprintf call"));
8693
8694       if (dprintf_channel && strlen (dprintf_channel) > 0)
8695         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8696                                   dprintf_function,
8697                                   dprintf_channel,
8698                                   dprintf_args);
8699       else
8700         printf_line = xstrprintf ("call (void) %s (%s)",
8701                                   dprintf_function,
8702                                   dprintf_args);
8703     }
8704   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8705     {
8706       if (target_can_run_breakpoint_commands ())
8707         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8708       else
8709         {
8710           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8711           printf_line = xstrprintf ("printf %s", dprintf_args);
8712         }
8713     }
8714   else
8715     internal_error (__FILE__, __LINE__,
8716                     _("Invalid dprintf style."));
8717
8718   gdb_assert (printf_line != NULL);
8719
8720   /* Manufacture a printf sequence.  */
8721   struct command_line *printf_cmd_line
8722     = new struct command_line (simple_control, printf_line);
8723   breakpoint_set_commands (b, counted_command_line (printf_cmd_line,
8724                                                     command_lines_deleter ()));
8725 }
8726
8727 /* Update all dprintf commands, making their command lists reflect
8728    current style settings.  */
8729
8730 static void
8731 update_dprintf_commands (const char *args, int from_tty,
8732                          struct cmd_list_element *c)
8733 {
8734   struct breakpoint *b;
8735
8736   ALL_BREAKPOINTS (b)
8737     {
8738       if (b->type == bp_dprintf)
8739         update_dprintf_command_list (b);
8740     }
8741 }
8742
8743 /* Create a breakpoint with SAL as location.  Use LOCATION
8744    as a description of the location, and COND_STRING
8745    as condition expression.  If LOCATION is NULL then create an
8746    "address location" from the address in the SAL.  */
8747
8748 static void
8749 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8750                      gdb::array_view<const symtab_and_line> sals,
8751                      event_location_up &&location,
8752                      gdb::unique_xmalloc_ptr<char> filter,
8753                      gdb::unique_xmalloc_ptr<char> cond_string,
8754                      gdb::unique_xmalloc_ptr<char> extra_string,
8755                      enum bptype type, enum bpdisp disposition,
8756                      int thread, int task, int ignore_count,
8757                      const struct breakpoint_ops *ops, int from_tty,
8758                      int enabled, int internal, unsigned flags,
8759                      int display_canonical)
8760 {
8761   int i;
8762
8763   if (type == bp_hardware_breakpoint)
8764     {
8765       int target_resources_ok;
8766
8767       i = hw_breakpoint_used_count ();
8768       target_resources_ok =
8769         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8770                                             i + 1, 0);
8771       if (target_resources_ok == 0)
8772         error (_("No hardware breakpoint support in the target."));
8773       else if (target_resources_ok < 0)
8774         error (_("Hardware breakpoints used exceeds limit."));
8775     }
8776
8777   gdb_assert (!sals.empty ());
8778
8779   for (const auto &sal : sals)
8780     {
8781       struct bp_location *loc;
8782
8783       if (from_tty)
8784         {
8785           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8786           if (!loc_gdbarch)
8787             loc_gdbarch = gdbarch;
8788
8789           describe_other_breakpoints (loc_gdbarch,
8790                                       sal.pspace, sal.pc, sal.section, thread);
8791         }
8792
8793       if (&sal == &sals[0])
8794         {
8795           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8796           b->thread = thread;
8797           b->task = task;
8798
8799           b->cond_string = cond_string.release ();
8800           b->extra_string = extra_string.release ();
8801           b->ignore_count = ignore_count;
8802           b->enable_state = enabled ? bp_enabled : bp_disabled;
8803           b->disposition = disposition;
8804
8805           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8806             b->loc->inserted = 1;
8807
8808           if (type == bp_static_tracepoint)
8809             {
8810               struct tracepoint *t = (struct tracepoint *) b;
8811               struct static_tracepoint_marker marker;
8812
8813               if (strace_marker_p (b))
8814                 {
8815                   /* We already know the marker exists, otherwise, we
8816                      wouldn't see a sal for it.  */
8817                   const char *p
8818                     = &event_location_to_string (b->location.get ())[3];
8819                   const char *endp;
8820
8821                   p = skip_spaces (p);
8822
8823                   endp = skip_to_space (p);
8824
8825                   t->static_trace_marker_id.assign (p, endp - p);
8826
8827                   printf_filtered (_("Probed static tracepoint "
8828                                      "marker \"%s\"\n"),
8829                                    t->static_trace_marker_id.c_str ());
8830                 }
8831               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8832                 {
8833                   t->static_trace_marker_id = std::move (marker.str_id);
8834
8835                   printf_filtered (_("Probed static tracepoint "
8836                                      "marker \"%s\"\n"),
8837                                    t->static_trace_marker_id.c_str ());
8838                 }
8839               else
8840                 warning (_("Couldn't determine the static "
8841                            "tracepoint marker to probe"));
8842             }
8843
8844           loc = b->loc;
8845         }
8846       else
8847         {
8848           loc = add_location_to_breakpoint (b, &sal);
8849           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8850             loc->inserted = 1;
8851         }
8852
8853       if (b->cond_string)
8854         {
8855           const char *arg = b->cond_string;
8856
8857           loc->cond = parse_exp_1 (&arg, loc->address,
8858                                    block_for_pc (loc->address), 0);
8859           if (*arg)
8860               error (_("Garbage '%s' follows condition"), arg);
8861         }
8862
8863       /* Dynamic printf requires and uses additional arguments on the
8864          command line, otherwise it's an error.  */
8865       if (type == bp_dprintf)
8866         {
8867           if (b->extra_string)
8868             update_dprintf_command_list (b);
8869           else
8870             error (_("Format string required"));
8871         }
8872       else if (b->extra_string)
8873         error (_("Garbage '%s' at end of command"), b->extra_string);
8874     }
8875
8876   b->display_canonical = display_canonical;
8877   if (location != NULL)
8878     b->location = std::move (location);
8879   else
8880     b->location = new_address_location (b->loc->address, NULL, 0);
8881   b->filter = filter.release ();
8882 }
8883
8884 static void
8885 create_breakpoint_sal (struct gdbarch *gdbarch,
8886                        gdb::array_view<const symtab_and_line> sals,
8887                        event_location_up &&location,
8888                        gdb::unique_xmalloc_ptr<char> filter,
8889                        gdb::unique_xmalloc_ptr<char> cond_string,
8890                        gdb::unique_xmalloc_ptr<char> extra_string,
8891                        enum bptype type, enum bpdisp disposition,
8892                        int thread, int task, int ignore_count,
8893                        const struct breakpoint_ops *ops, int from_tty,
8894                        int enabled, int internal, unsigned flags,
8895                        int display_canonical)
8896 {
8897   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (type);
8898
8899   init_breakpoint_sal (b.get (), gdbarch,
8900                        sals, std::move (location),
8901                        std::move (filter),
8902                        std::move (cond_string),
8903                        std::move (extra_string),
8904                        type, disposition,
8905                        thread, task, ignore_count,
8906                        ops, from_tty,
8907                        enabled, internal, flags,
8908                        display_canonical);
8909
8910   install_breakpoint (internal, std::move (b), 0);
8911 }
8912
8913 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
8914    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8915    value.  COND_STRING, if not NULL, specified the condition to be
8916    used for all breakpoints.  Essentially the only case where
8917    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8918    function.  In that case, it's still not possible to specify
8919    separate conditions for different overloaded functions, so
8920    we take just a single condition string.
8921    
8922    NOTE: If the function succeeds, the caller is expected to cleanup
8923    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8924    array contents).  If the function fails (error() is called), the
8925    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8926    COND and SALS arrays and each of those arrays contents.  */
8927
8928 static void
8929 create_breakpoints_sal (struct gdbarch *gdbarch,
8930                         struct linespec_result *canonical,
8931                         gdb::unique_xmalloc_ptr<char> cond_string,
8932                         gdb::unique_xmalloc_ptr<char> extra_string,
8933                         enum bptype type, enum bpdisp disposition,
8934                         int thread, int task, int ignore_count,
8935                         const struct breakpoint_ops *ops, int from_tty,
8936                         int enabled, int internal, unsigned flags)
8937 {
8938   if (canonical->pre_expanded)
8939     gdb_assert (canonical->lsals.size () == 1);
8940
8941   for (const auto &lsal : canonical->lsals)
8942     {
8943       /* Note that 'location' can be NULL in the case of a plain
8944          'break', without arguments.  */
8945       event_location_up location
8946         = (canonical->location != NULL
8947            ? copy_event_location (canonical->location.get ()) : NULL);
8948       gdb::unique_xmalloc_ptr<char> filter_string
8949         (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
8950
8951       create_breakpoint_sal (gdbarch, lsal.sals,
8952                              std::move (location),
8953                              std::move (filter_string),
8954                              std::move (cond_string),
8955                              std::move (extra_string),
8956                              type, disposition,
8957                              thread, task, ignore_count, ops,
8958                              from_tty, enabled, internal, flags,
8959                              canonical->special_display);
8960     }
8961 }
8962
8963 /* Parse LOCATION which is assumed to be a SAL specification possibly
8964    followed by conditionals.  On return, SALS contains an array of SAL
8965    addresses found.  LOCATION points to the end of the SAL (for
8966    linespec locations).
8967
8968    The array and the line spec strings are allocated on the heap, it is
8969    the caller's responsibility to free them.  */
8970
8971 static void
8972 parse_breakpoint_sals (const struct event_location *location,
8973                        struct linespec_result *canonical)
8974 {
8975   struct symtab_and_line cursal;
8976
8977   if (event_location_type (location) == LINESPEC_LOCATION)
8978     {
8979       const char *spec = get_linespec_location (location)->spec_string;
8980
8981       if (spec == NULL)
8982         {
8983           /* The last displayed codepoint, if it's valid, is our default
8984              breakpoint address.  */
8985           if (last_displayed_sal_is_valid ())
8986             {
8987               /* Set sal's pspace, pc, symtab, and line to the values
8988                  corresponding to the last call to print_frame_info.
8989                  Be sure to reinitialize LINE with NOTCURRENT == 0
8990                  as the breakpoint line number is inappropriate otherwise.
8991                  find_pc_line would adjust PC, re-set it back.  */
8992               symtab_and_line sal = get_last_displayed_sal ();
8993               CORE_ADDR pc = sal.pc;
8994
8995               sal = find_pc_line (pc, 0);
8996
8997               /* "break" without arguments is equivalent to "break *PC"
8998                  where PC is the last displayed codepoint's address.  So
8999                  make sure to set sal.explicit_pc to prevent GDB from
9000                  trying to expand the list of sals to include all other
9001                  instances with the same symtab and line.  */
9002               sal.pc = pc;
9003               sal.explicit_pc = 1;
9004
9005               struct linespec_sals lsal;
9006               lsal.sals = {sal};
9007               lsal.canonical = NULL;
9008
9009               canonical->lsals.push_back (std::move (lsal));
9010               return;
9011             }
9012           else
9013             error (_("No default breakpoint address now."));
9014         }
9015     }
9016
9017   /* Force almost all breakpoints to be in terms of the
9018      current_source_symtab (which is decode_line_1's default).
9019      This should produce the results we want almost all of the
9020      time while leaving default_breakpoint_* alone.
9021
9022      ObjC: However, don't match an Objective-C method name which
9023      may have a '+' or '-' succeeded by a '['.  */
9024   cursal = get_current_source_symtab_and_line ();
9025   if (last_displayed_sal_is_valid ())
9026     {
9027       const char *spec = NULL;
9028
9029       if (event_location_type (location) == LINESPEC_LOCATION)
9030         spec = get_linespec_location (location)->spec_string;
9031
9032       if (!cursal.symtab
9033           || (spec != NULL
9034               && strchr ("+-", spec[0]) != NULL
9035               && spec[1] != '['))
9036         {
9037           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9038                             get_last_displayed_symtab (),
9039                             get_last_displayed_line (),
9040                             canonical, NULL, NULL);
9041           return;
9042         }
9043     }
9044
9045   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9046                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9047 }
9048
9049
9050 /* Convert each SAL into a real PC.  Verify that the PC can be
9051    inserted as a breakpoint.  If it can't throw an error.  */
9052
9053 static void
9054 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
9055 {    
9056   for (auto &sal : sals)
9057     resolve_sal_pc (&sal);
9058 }
9059
9060 /* Fast tracepoints may have restrictions on valid locations.  For
9061    instance, a fast tracepoint using a jump instead of a trap will
9062    likely have to overwrite more bytes than a trap would, and so can
9063    only be placed where the instruction is longer than the jump, or a
9064    multi-instruction sequence does not have a jump into the middle of
9065    it, etc.  */
9066
9067 static void
9068 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9069                             gdb::array_view<const symtab_and_line> sals)
9070 {
9071   for (const auto &sal : sals)
9072     {
9073       struct gdbarch *sarch;
9074
9075       sarch = get_sal_arch (sal);
9076       /* We fall back to GDBARCH if there is no architecture
9077          associated with SAL.  */
9078       if (sarch == NULL)
9079         sarch = gdbarch;
9080       std::string msg;
9081       if (!gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg))
9082         error (_("May not have a fast tracepoint at %s%s"),
9083                paddress (sarch, sal.pc), msg.c_str ());
9084     }
9085 }
9086
9087 /* Given TOK, a string specification of condition and thread, as
9088    accepted by the 'break' command, extract the condition
9089    string and thread number and set *COND_STRING and *THREAD.
9090    PC identifies the context at which the condition should be parsed.
9091    If no condition is found, *COND_STRING is set to NULL.
9092    If no thread is found, *THREAD is set to -1.  */
9093
9094 static void
9095 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9096                            char **cond_string, int *thread, int *task,
9097                            char **rest)
9098 {
9099   *cond_string = NULL;
9100   *thread = -1;
9101   *task = 0;
9102   *rest = NULL;
9103
9104   while (tok && *tok)
9105     {
9106       const char *end_tok;
9107       int toklen;
9108       const char *cond_start = NULL;
9109       const char *cond_end = NULL;
9110
9111       tok = skip_spaces (tok);
9112
9113       if ((*tok == '"' || *tok == ',') && rest)
9114         {
9115           *rest = savestring (tok, strlen (tok));
9116           return;
9117         }
9118
9119       end_tok = skip_to_space (tok);
9120
9121       toklen = end_tok - tok;
9122
9123       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9124         {
9125           tok = cond_start = end_tok + 1;
9126           parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9127           cond_end = tok;
9128           *cond_string = savestring (cond_start, cond_end - cond_start);
9129         }
9130       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9131         {
9132           const char *tmptok;
9133           struct thread_info *thr;
9134
9135           tok = end_tok + 1;
9136           thr = parse_thread_id (tok, &tmptok);
9137           if (tok == tmptok)
9138             error (_("Junk after thread keyword."));
9139           *thread = thr->global_num;
9140           tok = tmptok;
9141         }
9142       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9143         {
9144           char *tmptok;
9145
9146           tok = end_tok + 1;
9147           *task = strtol (tok, &tmptok, 0);
9148           if (tok == tmptok)
9149             error (_("Junk after task keyword."));
9150           if (!valid_task_id (*task))
9151             error (_("Unknown task %d."), *task);
9152           tok = tmptok;
9153         }
9154       else if (rest)
9155         {
9156           *rest = savestring (tok, strlen (tok));
9157           return;
9158         }
9159       else
9160         error (_("Junk at end of arguments."));
9161     }
9162 }
9163
9164 /* Decode a static tracepoint marker spec.  */
9165
9166 static std::vector<symtab_and_line>
9167 decode_static_tracepoint_spec (const char **arg_p)
9168 {
9169   const char *p = &(*arg_p)[3];
9170   const char *endp;
9171
9172   p = skip_spaces (p);
9173
9174   endp = skip_to_space (p);
9175
9176   std::string marker_str (p, endp - p);
9177
9178   std::vector<static_tracepoint_marker> markers
9179     = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
9180   if (markers.empty ())
9181     error (_("No known static tracepoint marker named %s"),
9182            marker_str.c_str ());
9183
9184   std::vector<symtab_and_line> sals;
9185   sals.reserve (markers.size ());
9186
9187   for (const static_tracepoint_marker &marker : markers)
9188     {
9189       symtab_and_line sal = find_pc_line (marker.address, 0);
9190       sal.pc = marker.address;
9191       sals.push_back (sal);
9192    }
9193
9194   *arg_p = endp;
9195   return sals;
9196 }
9197
9198 /* See breakpoint.h.  */
9199
9200 int
9201 create_breakpoint (struct gdbarch *gdbarch,
9202                    const struct event_location *location,
9203                    const char *cond_string,
9204                    int thread, const char *extra_string,
9205                    int parse_extra,
9206                    int tempflag, enum bptype type_wanted,
9207                    int ignore_count,
9208                    enum auto_boolean pending_break_support,
9209                    const struct breakpoint_ops *ops,
9210                    int from_tty, int enabled, int internal,
9211                    unsigned flags)
9212 {
9213   struct linespec_result canonical;
9214   int pending = 0;
9215   int task = 0;
9216   int prev_bkpt_count = breakpoint_count;
9217
9218   gdb_assert (ops != NULL);
9219
9220   /* If extra_string isn't useful, set it to NULL.  */
9221   if (extra_string != NULL && *extra_string == '\0')
9222     extra_string = NULL;
9223
9224   try
9225     {
9226       ops->create_sals_from_location (location, &canonical, type_wanted);
9227     }
9228   catch (const gdb_exception_error &e)
9229     {
9230       /* If caller is interested in rc value from parse, set
9231          value.  */
9232       if (e.error == NOT_FOUND_ERROR)
9233         {
9234           /* If pending breakpoint support is turned off, throw
9235              error.  */
9236
9237           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9238             throw;
9239
9240           exception_print (gdb_stderr, e);
9241
9242           /* If pending breakpoint support is auto query and the user
9243              selects no, then simply return the error code.  */
9244           if (pending_break_support == AUTO_BOOLEAN_AUTO
9245               && !nquery (_("Make %s pending on future shared library load? "),
9246                           bptype_string (type_wanted)))
9247             return 0;
9248
9249           /* At this point, either the user was queried about setting
9250              a pending breakpoint and selected yes, or pending
9251              breakpoint behavior is on and thus a pending breakpoint
9252              is defaulted on behalf of the user.  */
9253           pending = 1;
9254         }
9255       else
9256         throw;
9257     }
9258
9259   if (!pending && canonical.lsals.empty ())
9260     return 0;
9261
9262   /* Resolve all line numbers to PC's and verify that the addresses
9263      are ok for the target.  */
9264   if (!pending)
9265     {
9266       for (auto &lsal : canonical.lsals)
9267         breakpoint_sals_to_pc (lsal.sals);
9268     }
9269
9270   /* Fast tracepoints may have additional restrictions on location.  */
9271   if (!pending && type_wanted == bp_fast_tracepoint)
9272     {
9273       for (const auto &lsal : canonical.lsals)
9274         check_fast_tracepoint_sals (gdbarch, lsal.sals);
9275     }
9276
9277   /* Verify that condition can be parsed, before setting any
9278      breakpoints.  Allocate a separate condition expression for each
9279      breakpoint.  */
9280   if (!pending)
9281     {
9282       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9283       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9284
9285       if (parse_extra)
9286         {
9287           char *rest;
9288           char *cond;
9289
9290           const linespec_sals &lsal = canonical.lsals[0];
9291
9292           /* Here we only parse 'arg' to separate condition
9293              from thread number, so parsing in context of first
9294              sal is OK.  When setting the breakpoint we'll
9295              re-parse it in context of each sal.  */
9296
9297           find_condition_and_thread (extra_string, lsal.sals[0].pc,
9298                                      &cond, &thread, &task, &rest);
9299           cond_string_copy.reset (cond);
9300           extra_string_copy.reset (rest);
9301         }
9302       else
9303         {
9304           if (type_wanted != bp_dprintf
9305               && extra_string != NULL && *extra_string != '\0')
9306                 error (_("Garbage '%s' at end of location"), extra_string);
9307
9308           /* Create a private copy of condition string.  */
9309           if (cond_string)
9310             cond_string_copy.reset (xstrdup (cond_string));
9311           /* Create a private copy of any extra string.  */
9312           if (extra_string)
9313             extra_string_copy.reset (xstrdup (extra_string));
9314         }
9315
9316       ops->create_breakpoints_sal (gdbarch, &canonical,
9317                                    std::move (cond_string_copy),
9318                                    std::move (extra_string_copy),
9319                                    type_wanted,
9320                                    tempflag ? disp_del : disp_donttouch,
9321                                    thread, task, ignore_count, ops,
9322                                    from_tty, enabled, internal, flags);
9323     }
9324   else
9325     {
9326       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (type_wanted);
9327
9328       init_raw_breakpoint_without_location (b.get (), gdbarch, type_wanted, ops);
9329       b->location = copy_event_location (location);
9330
9331       if (parse_extra)
9332         b->cond_string = NULL;
9333       else
9334         {
9335           /* Create a private copy of condition string.  */
9336           b->cond_string = cond_string != NULL ? xstrdup (cond_string) : NULL;
9337           b->thread = thread;
9338         }
9339
9340       /* Create a private copy of any extra string.  */
9341       b->extra_string = extra_string != NULL ? xstrdup (extra_string) : NULL;
9342       b->ignore_count = ignore_count;
9343       b->disposition = tempflag ? disp_del : disp_donttouch;
9344       b->condition_not_parsed = 1;
9345       b->enable_state = enabled ? bp_enabled : bp_disabled;
9346       if ((type_wanted != bp_breakpoint
9347            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9348         b->pspace = current_program_space;
9349
9350       install_breakpoint (internal, std::move (b), 0);
9351     }
9352   
9353   if (canonical.lsals.size () > 1)
9354     {
9355       warning (_("Multiple breakpoints were set.\nUse the "
9356                  "\"delete\" command to delete unwanted breakpoints."));
9357       prev_breakpoint_count = prev_bkpt_count;
9358     }
9359
9360   update_global_location_list (UGLL_MAY_INSERT);
9361
9362   return 1;
9363 }
9364
9365 /* Set a breakpoint.
9366    ARG is a string describing breakpoint address,
9367    condition, and thread.
9368    FLAG specifies if a breakpoint is hardware on,
9369    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9370    and BP_TEMPFLAG.  */
9371
9372 static void
9373 break_command_1 (const char *arg, int flag, int from_tty)
9374 {
9375   int tempflag = flag & BP_TEMPFLAG;
9376   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9377                              ? bp_hardware_breakpoint
9378                              : bp_breakpoint);
9379   struct breakpoint_ops *ops;
9380
9381   event_location_up location = string_to_event_location (&arg, current_language);
9382
9383   /* Matching breakpoints on probes.  */
9384   if (location != NULL
9385       && event_location_type (location.get ()) == PROBE_LOCATION)
9386     ops = &bkpt_probe_breakpoint_ops;
9387   else
9388     ops = &bkpt_breakpoint_ops;
9389
9390   create_breakpoint (get_current_arch (),
9391                      location.get (),
9392                      NULL, 0, arg, 1 /* parse arg */,
9393                      tempflag, type_wanted,
9394                      0 /* Ignore count */,
9395                      pending_break_support,
9396                      ops,
9397                      from_tty,
9398                      1 /* enabled */,
9399                      0 /* internal */,
9400                      0);
9401 }
9402
9403 /* Helper function for break_command_1 and disassemble_command.  */
9404
9405 void
9406 resolve_sal_pc (struct symtab_and_line *sal)
9407 {
9408   CORE_ADDR pc;
9409
9410   if (sal->pc == 0 && sal->symtab != NULL)
9411     {
9412       if (!find_line_pc (sal->symtab, sal->line, &pc))
9413         error (_("No line %d in file \"%s\"."),
9414                sal->line, symtab_to_filename_for_display (sal->symtab));
9415       sal->pc = pc;
9416
9417       /* If this SAL corresponds to a breakpoint inserted using a line
9418          number, then skip the function prologue if necessary.  */
9419       if (sal->explicit_line)
9420         skip_prologue_sal (sal);
9421     }
9422
9423   if (sal->section == 0 && sal->symtab != NULL)
9424     {
9425       const struct blockvector *bv;
9426       const struct block *b;
9427       struct symbol *sym;
9428
9429       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9430                                     SYMTAB_COMPUNIT (sal->symtab));
9431       if (bv != NULL)
9432         {
9433           sym = block_linkage_function (b);
9434           if (sym != NULL)
9435             {
9436               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9437               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9438                                                  sym);
9439             }
9440           else
9441             {
9442               /* It really is worthwhile to have the section, so we'll
9443                  just have to look harder. This case can be executed
9444                  if we have line numbers but no functions (as can
9445                  happen in assembly source).  */
9446
9447               scoped_restore_current_pspace_and_thread restore_pspace_thread;
9448               switch_to_program_space_and_thread (sal->pspace);
9449
9450               bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9451               if (msym.minsym)
9452                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9453             }
9454         }
9455     }
9456 }
9457
9458 void
9459 break_command (const char *arg, int from_tty)
9460 {
9461   break_command_1 (arg, 0, from_tty);
9462 }
9463
9464 void
9465 tbreak_command (const char *arg, int from_tty)
9466 {
9467   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9468 }
9469
9470 static void
9471 hbreak_command (const char *arg, int from_tty)
9472 {
9473   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9474 }
9475
9476 static void
9477 thbreak_command (const char *arg, int from_tty)
9478 {
9479   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9480 }
9481
9482 static void
9483 stop_command (const char *arg, int from_tty)
9484 {
9485   printf_filtered (_("Specify the type of breakpoint to set.\n\
9486 Usage: stop in <function | address>\n\
9487        stop at <line>\n"));
9488 }
9489
9490 static void
9491 stopin_command (const char *arg, int from_tty)
9492 {
9493   int badInput = 0;
9494
9495   if (arg == NULL)
9496     badInput = 1;
9497   else if (*arg != '*')
9498     {
9499       const char *argptr = arg;
9500       int hasColon = 0;
9501
9502       /* Look for a ':'.  If this is a line number specification, then
9503          say it is bad, otherwise, it should be an address or
9504          function/method name.  */
9505       while (*argptr && !hasColon)
9506         {
9507           hasColon = (*argptr == ':');
9508           argptr++;
9509         }
9510
9511       if (hasColon)
9512         badInput = (*argptr != ':');    /* Not a class::method */
9513       else
9514         badInput = isdigit (*arg);      /* a simple line number */
9515     }
9516
9517   if (badInput)
9518     printf_filtered (_("Usage: stop in <function | address>\n"));
9519   else
9520     break_command_1 (arg, 0, from_tty);
9521 }
9522
9523 static void
9524 stopat_command (const char *arg, int from_tty)
9525 {
9526   int badInput = 0;
9527
9528   if (arg == NULL || *arg == '*')       /* no line number */
9529     badInput = 1;
9530   else
9531     {
9532       const char *argptr = arg;
9533       int hasColon = 0;
9534
9535       /* Look for a ':'.  If there is a '::' then get out, otherwise
9536          it is probably a line number.  */
9537       while (*argptr && !hasColon)
9538         {
9539           hasColon = (*argptr == ':');
9540           argptr++;
9541         }
9542
9543       if (hasColon)
9544         badInput = (*argptr == ':');    /* we have class::method */
9545       else
9546         badInput = !isdigit (*arg);     /* not a line number */
9547     }
9548
9549   if (badInput)
9550     printf_filtered (_("Usage: stop at LINE\n"));
9551   else
9552     break_command_1 (arg, 0, from_tty);
9553 }
9554
9555 /* The dynamic printf command is mostly like a regular breakpoint, but
9556    with a prewired command list consisting of a single output command,
9557    built from extra arguments supplied on the dprintf command
9558    line.  */
9559
9560 static void
9561 dprintf_command (const char *arg, int from_tty)
9562 {
9563   event_location_up location = string_to_event_location (&arg, current_language);
9564
9565   /* If non-NULL, ARG should have been advanced past the location;
9566      the next character must be ','.  */
9567   if (arg != NULL)
9568     {
9569       if (arg[0] != ',' || arg[1] == '\0')
9570         error (_("Format string required"));
9571       else
9572         {
9573           /* Skip the comma.  */
9574           ++arg;
9575         }
9576     }
9577
9578   create_breakpoint (get_current_arch (),
9579                      location.get (),
9580                      NULL, 0, arg, 1 /* parse arg */,
9581                      0, bp_dprintf,
9582                      0 /* Ignore count */,
9583                      pending_break_support,
9584                      &dprintf_breakpoint_ops,
9585                      from_tty,
9586                      1 /* enabled */,
9587                      0 /* internal */,
9588                      0);
9589 }
9590
9591 static void
9592 agent_printf_command (const char *arg, int from_tty)
9593 {
9594   error (_("May only run agent-printf on the target"));
9595 }
9596
9597 /* Implement the "breakpoint_hit" breakpoint_ops method for
9598    ranged breakpoints.  */
9599
9600 static int
9601 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9602                                   const address_space *aspace,
9603                                   CORE_ADDR bp_addr,
9604                                   const struct target_waitstatus *ws)
9605 {
9606   if (ws->kind != TARGET_WAITKIND_STOPPED
9607       || ws->value.sig != GDB_SIGNAL_TRAP)
9608     return 0;
9609
9610   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9611                                          bl->length, aspace, bp_addr);
9612 }
9613
9614 /* Implement the "resources_needed" breakpoint_ops method for
9615    ranged breakpoints.  */
9616
9617 static int
9618 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9619 {
9620   return target_ranged_break_num_registers ();
9621 }
9622
9623 /* Implement the "print_it" breakpoint_ops method for
9624    ranged breakpoints.  */
9625
9626 static enum print_stop_action
9627 print_it_ranged_breakpoint (bpstat bs)
9628 {
9629   struct breakpoint *b = bs->breakpoint_at;
9630   struct bp_location *bl = b->loc;
9631   struct ui_out *uiout = current_uiout;
9632
9633   gdb_assert (b->type == bp_hardware_breakpoint);
9634
9635   /* Ranged breakpoints have only one location.  */
9636   gdb_assert (bl && bl->next == NULL);
9637
9638   annotate_breakpoint (b->number);
9639
9640   maybe_print_thread_hit_breakpoint (uiout);
9641
9642   if (b->disposition == disp_del)
9643     uiout->text ("Temporary ranged breakpoint ");
9644   else
9645     uiout->text ("Ranged breakpoint ");
9646   if (uiout->is_mi_like_p ())
9647     {
9648       uiout->field_string ("reason",
9649                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9650       uiout->field_string ("disp", bpdisp_text (b->disposition));
9651     }
9652   uiout->field_int ("bkptno", b->number);
9653   uiout->text (", ");
9654
9655   return PRINT_SRC_AND_LOC;
9656 }
9657
9658 /* Implement the "print_one" breakpoint_ops method for
9659    ranged breakpoints.  */
9660
9661 static void
9662 print_one_ranged_breakpoint (struct breakpoint *b,
9663                              struct bp_location **last_loc)
9664 {
9665   struct bp_location *bl = b->loc;
9666   struct value_print_options opts;
9667   struct ui_out *uiout = current_uiout;
9668
9669   /* Ranged breakpoints have only one location.  */
9670   gdb_assert (bl && bl->next == NULL);
9671
9672   get_user_print_options (&opts);
9673
9674   if (opts.addressprint)
9675     /* We don't print the address range here, it will be printed later
9676        by print_one_detail_ranged_breakpoint.  */
9677     uiout->field_skip ("addr");
9678   annotate_field (5);
9679   print_breakpoint_location (b, bl);
9680   *last_loc = bl;
9681 }
9682
9683 /* Implement the "print_one_detail" breakpoint_ops method for
9684    ranged breakpoints.  */
9685
9686 static void
9687 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9688                                     struct ui_out *uiout)
9689 {
9690   CORE_ADDR address_start, address_end;
9691   struct bp_location *bl = b->loc;
9692   string_file stb;
9693
9694   gdb_assert (bl);
9695
9696   address_start = bl->address;
9697   address_end = address_start + bl->length - 1;
9698
9699   uiout->text ("\taddress range: ");
9700   stb.printf ("[%s, %s]",
9701               print_core_address (bl->gdbarch, address_start),
9702               print_core_address (bl->gdbarch, address_end));
9703   uiout->field_stream ("addr", stb);
9704   uiout->text ("\n");
9705 }
9706
9707 /* Implement the "print_mention" breakpoint_ops method for
9708    ranged breakpoints.  */
9709
9710 static void
9711 print_mention_ranged_breakpoint (struct breakpoint *b)
9712 {
9713   struct bp_location *bl = b->loc;
9714   struct ui_out *uiout = current_uiout;
9715
9716   gdb_assert (bl);
9717   gdb_assert (b->type == bp_hardware_breakpoint);
9718
9719   uiout->message (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9720                   b->number, paddress (bl->gdbarch, bl->address),
9721                   paddress (bl->gdbarch, bl->address + bl->length - 1));
9722 }
9723
9724 /* Implement the "print_recreate" breakpoint_ops method for
9725    ranged breakpoints.  */
9726
9727 static void
9728 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9729 {
9730   fprintf_unfiltered (fp, "break-range %s, %s",
9731                       event_location_to_string (b->location.get ()),
9732                       event_location_to_string (b->location_range_end.get ()));
9733   print_recreate_thread (b, fp);
9734 }
9735
9736 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9737
9738 static struct breakpoint_ops ranged_breakpoint_ops;
9739
9740 /* Find the address where the end of the breakpoint range should be
9741    placed, given the SAL of the end of the range.  This is so that if
9742    the user provides a line number, the end of the range is set to the
9743    last instruction of the given line.  */
9744
9745 static CORE_ADDR
9746 find_breakpoint_range_end (struct symtab_and_line sal)
9747 {
9748   CORE_ADDR end;
9749
9750   /* If the user provided a PC value, use it.  Otherwise,
9751      find the address of the end of the given location.  */
9752   if (sal.explicit_pc)
9753     end = sal.pc;
9754   else
9755     {
9756       int ret;
9757       CORE_ADDR start;
9758
9759       ret = find_line_pc_range (sal, &start, &end);
9760       if (!ret)
9761         error (_("Could not find location of the end of the range."));
9762
9763       /* find_line_pc_range returns the start of the next line.  */
9764       end--;
9765     }
9766
9767   return end;
9768 }
9769
9770 /* Implement the "break-range" CLI command.  */
9771
9772 static void
9773 break_range_command (const char *arg, int from_tty)
9774 {
9775   const char *arg_start;
9776   struct linespec_result canonical_start, canonical_end;
9777   int bp_count, can_use_bp, length;
9778   CORE_ADDR end;
9779   struct breakpoint *b;
9780
9781   /* We don't support software ranged breakpoints.  */
9782   if (target_ranged_break_num_registers () < 0)
9783     error (_("This target does not support hardware ranged breakpoints."));
9784
9785   bp_count = hw_breakpoint_used_count ();
9786   bp_count += target_ranged_break_num_registers ();
9787   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9788                                                    bp_count, 0);
9789   if (can_use_bp < 0)
9790     error (_("Hardware breakpoints used exceeds limit."));
9791
9792   arg = skip_spaces (arg);
9793   if (arg == NULL || arg[0] == '\0')
9794     error(_("No address range specified."));
9795
9796   arg_start = arg;
9797   event_location_up start_location = string_to_event_location (&arg,
9798                                                                current_language);
9799   parse_breakpoint_sals (start_location.get (), &canonical_start);
9800
9801   if (arg[0] != ',')
9802     error (_("Too few arguments."));
9803   else if (canonical_start.lsals.empty ())
9804     error (_("Could not find location of the beginning of the range."));
9805
9806   const linespec_sals &lsal_start = canonical_start.lsals[0];
9807
9808   if (canonical_start.lsals.size () > 1
9809       || lsal_start.sals.size () != 1)
9810     error (_("Cannot create a ranged breakpoint with multiple locations."));
9811
9812   const symtab_and_line &sal_start = lsal_start.sals[0];
9813   std::string addr_string_start (arg_start, arg - arg_start);
9814
9815   arg++;        /* Skip the comma.  */
9816   arg = skip_spaces (arg);
9817
9818   /* Parse the end location.  */
9819
9820   arg_start = arg;
9821
9822   /* We call decode_line_full directly here instead of using
9823      parse_breakpoint_sals because we need to specify the start location's
9824      symtab and line as the default symtab and line for the end of the
9825      range.  This makes it possible to have ranges like "foo.c:27, +14",
9826      where +14 means 14 lines from the start location.  */
9827   event_location_up end_location = string_to_event_location (&arg,
9828                                                              current_language);
9829   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
9830                     sal_start.symtab, sal_start.line,
9831                     &canonical_end, NULL, NULL);
9832
9833   if (canonical_end.lsals.empty ())
9834     error (_("Could not find location of the end of the range."));
9835
9836   const linespec_sals &lsal_end = canonical_end.lsals[0];
9837   if (canonical_end.lsals.size () > 1
9838       || lsal_end.sals.size () != 1)
9839     error (_("Cannot create a ranged breakpoint with multiple locations."));
9840
9841   const symtab_and_line &sal_end = lsal_end.sals[0];
9842
9843   end = find_breakpoint_range_end (sal_end);
9844   if (sal_start.pc > end)
9845     error (_("Invalid address range, end precedes start."));
9846
9847   length = end - sal_start.pc + 1;
9848   if (length < 0)
9849     /* Length overflowed.  */
9850     error (_("Address range too large."));
9851   else if (length == 1)
9852     {
9853       /* This range is simple enough to be handled by
9854          the `hbreak' command.  */
9855       hbreak_command (&addr_string_start[0], 1);
9856
9857       return;
9858     }
9859
9860   /* Now set up the breakpoint.  */
9861   b = set_raw_breakpoint (get_current_arch (), sal_start,
9862                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
9863   set_breakpoint_count (breakpoint_count + 1);
9864   b->number = breakpoint_count;
9865   b->disposition = disp_donttouch;
9866   b->location = std::move (start_location);
9867   b->location_range_end = std::move (end_location);
9868   b->loc->length = length;
9869
9870   mention (b);
9871   gdb::observers::breakpoint_created.notify (b);
9872   update_global_location_list (UGLL_MAY_INSERT);
9873 }
9874
9875 /*  Return non-zero if EXP is verified as constant.  Returned zero
9876     means EXP is variable.  Also the constant detection may fail for
9877     some constant expressions and in such case still falsely return
9878     zero.  */
9879
9880 static int
9881 watchpoint_exp_is_const (const struct expression *exp)
9882 {
9883   int i = exp->nelts;
9884
9885   while (i > 0)
9886     {
9887       int oplenp, argsp;
9888
9889       /* We are only interested in the descriptor of each element.  */
9890       operator_length (exp, i, &oplenp, &argsp);
9891       i -= oplenp;
9892
9893       switch (exp->elts[i].opcode)
9894         {
9895         case BINOP_ADD:
9896         case BINOP_SUB:
9897         case BINOP_MUL:
9898         case BINOP_DIV:
9899         case BINOP_REM:
9900         case BINOP_MOD:
9901         case BINOP_LSH:
9902         case BINOP_RSH:
9903         case BINOP_LOGICAL_AND:
9904         case BINOP_LOGICAL_OR:
9905         case BINOP_BITWISE_AND:
9906         case BINOP_BITWISE_IOR:
9907         case BINOP_BITWISE_XOR:
9908         case BINOP_EQUAL:
9909         case BINOP_NOTEQUAL:
9910         case BINOP_LESS:
9911         case BINOP_GTR:
9912         case BINOP_LEQ:
9913         case BINOP_GEQ:
9914         case BINOP_REPEAT:
9915         case BINOP_COMMA:
9916         case BINOP_EXP:
9917         case BINOP_MIN:
9918         case BINOP_MAX:
9919         case BINOP_INTDIV:
9920         case BINOP_CONCAT:
9921         case TERNOP_COND:
9922         case TERNOP_SLICE:
9923
9924         case OP_LONG:
9925         case OP_FLOAT:
9926         case OP_LAST:
9927         case OP_COMPLEX:
9928         case OP_STRING:
9929         case OP_ARRAY:
9930         case OP_TYPE:
9931         case OP_TYPEOF:
9932         case OP_DECLTYPE:
9933         case OP_TYPEID:
9934         case OP_NAME:
9935         case OP_OBJC_NSSTRING:
9936
9937         case UNOP_NEG:
9938         case UNOP_LOGICAL_NOT:
9939         case UNOP_COMPLEMENT:
9940         case UNOP_ADDR:
9941         case UNOP_HIGH:
9942         case UNOP_CAST:
9943
9944         case UNOP_CAST_TYPE:
9945         case UNOP_REINTERPRET_CAST:
9946         case UNOP_DYNAMIC_CAST:
9947           /* Unary, binary and ternary operators: We have to check
9948              their operands.  If they are constant, then so is the
9949              result of that operation.  For instance, if A and B are
9950              determined to be constants, then so is "A + B".
9951
9952              UNOP_IND is one exception to the rule above, because the
9953              value of *ADDR is not necessarily a constant, even when
9954              ADDR is.  */
9955           break;
9956
9957         case OP_VAR_VALUE:
9958           /* Check whether the associated symbol is a constant.
9959
9960              We use SYMBOL_CLASS rather than TYPE_CONST because it's
9961              possible that a buggy compiler could mark a variable as
9962              constant even when it is not, and TYPE_CONST would return
9963              true in this case, while SYMBOL_CLASS wouldn't.
9964
9965              We also have to check for function symbols because they
9966              are always constant.  */
9967           {
9968             struct symbol *s = exp->elts[i + 2].symbol;
9969
9970             if (SYMBOL_CLASS (s) != LOC_BLOCK
9971                 && SYMBOL_CLASS (s) != LOC_CONST
9972                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
9973               return 0;
9974             break;
9975           }
9976
9977         /* The default action is to return 0 because we are using
9978            the optimistic approach here: If we don't know something,
9979            then it is not a constant.  */
9980         default:
9981           return 0;
9982         }
9983     }
9984
9985   return 1;
9986 }
9987
9988 /* Watchpoint destructor.  */
9989
9990 watchpoint::~watchpoint ()
9991 {
9992   xfree (this->exp_string);
9993   xfree (this->exp_string_reparse);
9994 }
9995
9996 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
9997
9998 static void
9999 re_set_watchpoint (struct breakpoint *b)
10000 {
10001   struct watchpoint *w = (struct watchpoint *) b;
10002
10003   /* Watchpoint can be either on expression using entirely global
10004      variables, or it can be on local variables.
10005
10006      Watchpoints of the first kind are never auto-deleted, and even
10007      persist across program restarts.  Since they can use variables
10008      from shared libraries, we need to reparse expression as libraries
10009      are loaded and unloaded.
10010
10011      Watchpoints on local variables can also change meaning as result
10012      of solib event.  For example, if a watchpoint uses both a local
10013      and a global variables in expression, it's a local watchpoint,
10014      but unloading of a shared library will make the expression
10015      invalid.  This is not a very common use case, but we still
10016      re-evaluate expression, to avoid surprises to the user.
10017
10018      Note that for local watchpoints, we re-evaluate it only if
10019      watchpoints frame id is still valid.  If it's not, it means the
10020      watchpoint is out of scope and will be deleted soon.  In fact,
10021      I'm not sure we'll ever be called in this case.
10022
10023      If a local watchpoint's frame id is still valid, then
10024      w->exp_valid_block is likewise valid, and we can safely use it.
10025
10026      Don't do anything about disabled watchpoints, since they will be
10027      reevaluated again when enabled.  */
10028   update_watchpoint (w, 1 /* reparse */);
10029 }
10030
10031 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10032
10033 static int
10034 insert_watchpoint (struct bp_location *bl)
10035 {
10036   struct watchpoint *w = (struct watchpoint *) bl->owner;
10037   int length = w->exact ? 1 : bl->length;
10038
10039   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10040                                    w->cond_exp.get ());
10041 }
10042
10043 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10044
10045 static int
10046 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10047 {
10048   struct watchpoint *w = (struct watchpoint *) bl->owner;
10049   int length = w->exact ? 1 : bl->length;
10050
10051   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10052                                    w->cond_exp.get ());
10053 }
10054
10055 static int
10056 breakpoint_hit_watchpoint (const struct bp_location *bl,
10057                            const address_space *aspace, CORE_ADDR bp_addr,
10058                            const struct target_waitstatus *ws)
10059 {
10060   struct breakpoint *b = bl->owner;
10061   struct watchpoint *w = (struct watchpoint *) b;
10062
10063   /* Continuable hardware watchpoints are treated as non-existent if the
10064      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10065      some data address).  Otherwise gdb won't stop on a break instruction
10066      in the code (not from a breakpoint) when a hardware watchpoint has
10067      been defined.  Also skip watchpoints which we know did not trigger
10068      (did not match the data address).  */
10069   if (is_hardware_watchpoint (b)
10070       && w->watchpoint_triggered == watch_triggered_no)
10071     return 0;
10072
10073   return 1;
10074 }
10075
10076 static void
10077 check_status_watchpoint (bpstat bs)
10078 {
10079   gdb_assert (is_watchpoint (bs->breakpoint_at));
10080
10081   bpstat_check_watchpoint (bs);
10082 }
10083
10084 /* Implement the "resources_needed" breakpoint_ops method for
10085    hardware watchpoints.  */
10086
10087 static int
10088 resources_needed_watchpoint (const struct bp_location *bl)
10089 {
10090   struct watchpoint *w = (struct watchpoint *) bl->owner;
10091   int length = w->exact? 1 : bl->length;
10092
10093   return target_region_ok_for_hw_watchpoint (bl->address, length);
10094 }
10095
10096 /* Implement the "works_in_software_mode" breakpoint_ops method for
10097    hardware watchpoints.  */
10098
10099 static int
10100 works_in_software_mode_watchpoint (const struct breakpoint *b)
10101 {
10102   /* Read and access watchpoints only work with hardware support.  */
10103   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10104 }
10105
10106 static enum print_stop_action
10107 print_it_watchpoint (bpstat bs)
10108 {
10109   struct breakpoint *b;
10110   enum print_stop_action result;
10111   struct watchpoint *w;
10112   struct ui_out *uiout = current_uiout;
10113
10114   gdb_assert (bs->bp_location_at != NULL);
10115
10116   b = bs->breakpoint_at;
10117   w = (struct watchpoint *) b;
10118
10119   annotate_watchpoint (b->number);
10120   maybe_print_thread_hit_breakpoint (uiout);
10121
10122   string_file stb;
10123
10124   gdb::optional<ui_out_emit_tuple> tuple_emitter;
10125   switch (b->type)
10126     {
10127     case bp_watchpoint:
10128     case bp_hardware_watchpoint:
10129       if (uiout->is_mi_like_p ())
10130         uiout->field_string
10131           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10132       mention (b);
10133       tuple_emitter.emplace (uiout, "value");
10134       uiout->text ("\nOld value = ");
10135       watchpoint_value_print (bs->old_val.get (), &stb);
10136       uiout->field_stream ("old", stb);
10137       uiout->text ("\nNew value = ");
10138       watchpoint_value_print (w->val.get (), &stb);
10139       uiout->field_stream ("new", stb);
10140       uiout->text ("\n");
10141       /* More than one watchpoint may have been triggered.  */
10142       result = PRINT_UNKNOWN;
10143       break;
10144
10145     case bp_read_watchpoint:
10146       if (uiout->is_mi_like_p ())
10147         uiout->field_string
10148           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10149       mention (b);
10150       tuple_emitter.emplace (uiout, "value");
10151       uiout->text ("\nValue = ");
10152       watchpoint_value_print (w->val.get (), &stb);
10153       uiout->field_stream ("value", stb);
10154       uiout->text ("\n");
10155       result = PRINT_UNKNOWN;
10156       break;
10157
10158     case bp_access_watchpoint:
10159       if (bs->old_val != NULL)
10160         {
10161           if (uiout->is_mi_like_p ())
10162             uiout->field_string
10163               ("reason",
10164                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10165           mention (b);
10166           tuple_emitter.emplace (uiout, "value");
10167           uiout->text ("\nOld value = ");
10168           watchpoint_value_print (bs->old_val.get (), &stb);
10169           uiout->field_stream ("old", stb);
10170           uiout->text ("\nNew value = ");
10171         }
10172       else
10173         {
10174           mention (b);
10175           if (uiout->is_mi_like_p ())
10176             uiout->field_string
10177               ("reason",
10178                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10179           tuple_emitter.emplace (uiout, "value");
10180           uiout->text ("\nValue = ");
10181         }
10182       watchpoint_value_print (w->val.get (), &stb);
10183       uiout->field_stream ("new", stb);
10184       uiout->text ("\n");
10185       result = PRINT_UNKNOWN;
10186       break;
10187     default:
10188       result = PRINT_UNKNOWN;
10189     }
10190
10191   return result;
10192 }
10193
10194 /* Implement the "print_mention" breakpoint_ops method for hardware
10195    watchpoints.  */
10196
10197 static void
10198 print_mention_watchpoint (struct breakpoint *b)
10199 {
10200   struct watchpoint *w = (struct watchpoint *) b;
10201   struct ui_out *uiout = current_uiout;
10202   const char *tuple_name;
10203
10204   switch (b->type)
10205     {
10206     case bp_watchpoint:
10207       uiout->text ("Watchpoint ");
10208       tuple_name = "wpt";
10209       break;
10210     case bp_hardware_watchpoint:
10211       uiout->text ("Hardware watchpoint ");
10212       tuple_name = "wpt";
10213       break;
10214     case bp_read_watchpoint:
10215       uiout->text ("Hardware read watchpoint ");
10216       tuple_name = "hw-rwpt";
10217       break;
10218     case bp_access_watchpoint:
10219       uiout->text ("Hardware access (read/write) watchpoint ");
10220       tuple_name = "hw-awpt";
10221       break;
10222     default:
10223       internal_error (__FILE__, __LINE__,
10224                       _("Invalid hardware watchpoint type."));
10225     }
10226
10227   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10228   uiout->field_int ("number", b->number);
10229   uiout->text (": ");
10230   uiout->field_string ("exp", w->exp_string);
10231 }
10232
10233 /* Implement the "print_recreate" breakpoint_ops method for
10234    watchpoints.  */
10235
10236 static void
10237 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10238 {
10239   struct watchpoint *w = (struct watchpoint *) b;
10240
10241   switch (b->type)
10242     {
10243     case bp_watchpoint:
10244     case bp_hardware_watchpoint:
10245       fprintf_unfiltered (fp, "watch");
10246       break;
10247     case bp_read_watchpoint:
10248       fprintf_unfiltered (fp, "rwatch");
10249       break;
10250     case bp_access_watchpoint:
10251       fprintf_unfiltered (fp, "awatch");
10252       break;
10253     default:
10254       internal_error (__FILE__, __LINE__,
10255                       _("Invalid watchpoint type."));
10256     }
10257
10258   fprintf_unfiltered (fp, " %s", w->exp_string);
10259   print_recreate_thread (b, fp);
10260 }
10261
10262 /* Implement the "explains_signal" breakpoint_ops method for
10263    watchpoints.  */
10264
10265 static int
10266 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10267 {
10268   /* A software watchpoint cannot cause a signal other than
10269      GDB_SIGNAL_TRAP.  */
10270   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10271     return 0;
10272
10273   return 1;
10274 }
10275
10276 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10277
10278 static struct breakpoint_ops watchpoint_breakpoint_ops;
10279
10280 /* Implement the "insert" breakpoint_ops method for
10281    masked hardware watchpoints.  */
10282
10283 static int
10284 insert_masked_watchpoint (struct bp_location *bl)
10285 {
10286   struct watchpoint *w = (struct watchpoint *) bl->owner;
10287
10288   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10289                                         bl->watchpoint_type);
10290 }
10291
10292 /* Implement the "remove" breakpoint_ops method for
10293    masked hardware watchpoints.  */
10294
10295 static int
10296 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10297 {
10298   struct watchpoint *w = (struct watchpoint *) bl->owner;
10299
10300   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10301                                         bl->watchpoint_type);
10302 }
10303
10304 /* Implement the "resources_needed" breakpoint_ops method for
10305    masked hardware watchpoints.  */
10306
10307 static int
10308 resources_needed_masked_watchpoint (const struct bp_location *bl)
10309 {
10310   struct watchpoint *w = (struct watchpoint *) bl->owner;
10311
10312   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10313 }
10314
10315 /* Implement the "works_in_software_mode" breakpoint_ops method for
10316    masked hardware watchpoints.  */
10317
10318 static int
10319 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10320 {
10321   return 0;
10322 }
10323
10324 /* Implement the "print_it" breakpoint_ops method for
10325    masked hardware watchpoints.  */
10326
10327 static enum print_stop_action
10328 print_it_masked_watchpoint (bpstat bs)
10329 {
10330   struct breakpoint *b = bs->breakpoint_at;
10331   struct ui_out *uiout = current_uiout;
10332
10333   /* Masked watchpoints have only one location.  */
10334   gdb_assert (b->loc && b->loc->next == NULL);
10335
10336   annotate_watchpoint (b->number);
10337   maybe_print_thread_hit_breakpoint (uiout);
10338
10339   switch (b->type)
10340     {
10341     case bp_hardware_watchpoint:
10342       if (uiout->is_mi_like_p ())
10343         uiout->field_string
10344           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10345       break;
10346
10347     case bp_read_watchpoint:
10348       if (uiout->is_mi_like_p ())
10349         uiout->field_string
10350           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10351       break;
10352
10353     case bp_access_watchpoint:
10354       if (uiout->is_mi_like_p ())
10355         uiout->field_string
10356           ("reason",
10357            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10358       break;
10359     default:
10360       internal_error (__FILE__, __LINE__,
10361                       _("Invalid hardware watchpoint type."));
10362     }
10363
10364   mention (b);
10365   uiout->text (_("\n\
10366 Check the underlying instruction at PC for the memory\n\
10367 address and value which triggered this watchpoint.\n"));
10368   uiout->text ("\n");
10369
10370   /* More than one watchpoint may have been triggered.  */
10371   return PRINT_UNKNOWN;
10372 }
10373
10374 /* Implement the "print_one_detail" breakpoint_ops method for
10375    masked hardware watchpoints.  */
10376
10377 static void
10378 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10379                                     struct ui_out *uiout)
10380 {
10381   struct watchpoint *w = (struct watchpoint *) b;
10382
10383   /* Masked watchpoints have only one location.  */
10384   gdb_assert (b->loc && b->loc->next == NULL);
10385
10386   uiout->text ("\tmask ");
10387   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10388   uiout->text ("\n");
10389 }
10390
10391 /* Implement the "print_mention" breakpoint_ops method for
10392    masked hardware watchpoints.  */
10393
10394 static void
10395 print_mention_masked_watchpoint (struct breakpoint *b)
10396 {
10397   struct watchpoint *w = (struct watchpoint *) b;
10398   struct ui_out *uiout = current_uiout;
10399   const char *tuple_name;
10400
10401   switch (b->type)
10402     {
10403     case bp_hardware_watchpoint:
10404       uiout->text ("Masked hardware watchpoint ");
10405       tuple_name = "wpt";
10406       break;
10407     case bp_read_watchpoint:
10408       uiout->text ("Masked hardware read watchpoint ");
10409       tuple_name = "hw-rwpt";
10410       break;
10411     case bp_access_watchpoint:
10412       uiout->text ("Masked hardware access (read/write) watchpoint ");
10413       tuple_name = "hw-awpt";
10414       break;
10415     default:
10416       internal_error (__FILE__, __LINE__,
10417                       _("Invalid hardware watchpoint type."));
10418     }
10419
10420   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10421   uiout->field_int ("number", b->number);
10422   uiout->text (": ");
10423   uiout->field_string ("exp", w->exp_string);
10424 }
10425
10426 /* Implement the "print_recreate" breakpoint_ops method for
10427    masked hardware watchpoints.  */
10428
10429 static void
10430 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10431 {
10432   struct watchpoint *w = (struct watchpoint *) b;
10433   char tmp[40];
10434
10435   switch (b->type)
10436     {
10437     case bp_hardware_watchpoint:
10438       fprintf_unfiltered (fp, "watch");
10439       break;
10440     case bp_read_watchpoint:
10441       fprintf_unfiltered (fp, "rwatch");
10442       break;
10443     case bp_access_watchpoint:
10444       fprintf_unfiltered (fp, "awatch");
10445       break;
10446     default:
10447       internal_error (__FILE__, __LINE__,
10448                       _("Invalid hardware watchpoint type."));
10449     }
10450
10451   sprintf_vma (tmp, w->hw_wp_mask);
10452   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10453   print_recreate_thread (b, fp);
10454 }
10455
10456 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10457
10458 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10459
10460 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10461
10462 static int
10463 is_masked_watchpoint (const struct breakpoint *b)
10464 {
10465   return b->ops == &masked_watchpoint_breakpoint_ops;
10466 }
10467
10468 /* accessflag:  hw_write:  watch write, 
10469                 hw_read:   watch read, 
10470                 hw_access: watch access (read or write) */
10471 static void
10472 watch_command_1 (const char *arg, int accessflag, int from_tty,
10473                  int just_location, int internal)
10474 {
10475   struct breakpoint *scope_breakpoint = NULL;
10476   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10477   struct value *result;
10478   int saved_bitpos = 0, saved_bitsize = 0;
10479   const char *exp_start = NULL;
10480   const char *exp_end = NULL;
10481   const char *tok, *end_tok;
10482   int toklen = -1;
10483   const char *cond_start = NULL;
10484   const char *cond_end = NULL;
10485   enum bptype bp_type;
10486   int thread = -1;
10487   int pc = 0;
10488   /* Flag to indicate whether we are going to use masks for
10489      the hardware watchpoint.  */
10490   int use_mask = 0;
10491   CORE_ADDR mask = 0;
10492
10493   /* Make sure that we actually have parameters to parse.  */
10494   if (arg != NULL && arg[0] != '\0')
10495     {
10496       const char *value_start;
10497
10498       exp_end = arg + strlen (arg);
10499
10500       /* Look for "parameter value" pairs at the end
10501          of the arguments string.  */
10502       for (tok = exp_end - 1; tok > arg; tok--)
10503         {
10504           /* Skip whitespace at the end of the argument list.  */
10505           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10506             tok--;
10507
10508           /* Find the beginning of the last token.
10509              This is the value of the parameter.  */
10510           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10511             tok--;
10512           value_start = tok + 1;
10513
10514           /* Skip whitespace.  */
10515           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10516             tok--;
10517
10518           end_tok = tok;
10519
10520           /* Find the beginning of the second to last token.
10521              This is the parameter itself.  */
10522           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10523             tok--;
10524           tok++;
10525           toklen = end_tok - tok + 1;
10526
10527           if (toklen == 6 && startswith (tok, "thread"))
10528             {
10529               struct thread_info *thr;
10530               /* At this point we've found a "thread" token, which means
10531                  the user is trying to set a watchpoint that triggers
10532                  only in a specific thread.  */
10533               const char *endp;
10534
10535               if (thread != -1)
10536                 error(_("You can specify only one thread."));
10537
10538               /* Extract the thread ID from the next token.  */
10539               thr = parse_thread_id (value_start, &endp);
10540
10541               /* Check if the user provided a valid thread ID.  */
10542               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10543                 invalid_thread_id_error (value_start);
10544
10545               thread = thr->global_num;
10546             }
10547           else if (toklen == 4 && startswith (tok, "mask"))
10548             {
10549               /* We've found a "mask" token, which means the user wants to
10550                  create a hardware watchpoint that is going to have the mask
10551                  facility.  */
10552               struct value *mask_value, *mark;
10553
10554               if (use_mask)
10555                 error(_("You can specify only one mask."));
10556
10557               use_mask = just_location = 1;
10558
10559               mark = value_mark ();
10560               mask_value = parse_to_comma_and_eval (&value_start);
10561               mask = value_as_address (mask_value);
10562               value_free_to_mark (mark);
10563             }
10564           else
10565             /* We didn't recognize what we found.  We should stop here.  */
10566             break;
10567
10568           /* Truncate the string and get rid of the "parameter value" pair before
10569              the arguments string is parsed by the parse_exp_1 function.  */
10570           exp_end = tok;
10571         }
10572     }
10573   else
10574     exp_end = arg;
10575
10576   /* Parse the rest of the arguments.  From here on out, everything
10577      is in terms of a newly allocated string instead of the original
10578      ARG.  */
10579   std::string expression (arg, exp_end - arg);
10580   exp_start = arg = expression.c_str ();
10581   innermost_block_tracker tracker;
10582   expression_up exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
10583   exp_end = arg;
10584   /* Remove trailing whitespace from the expression before saving it.
10585      This makes the eventual display of the expression string a bit
10586      prettier.  */
10587   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10588     --exp_end;
10589
10590   /* Checking if the expression is not constant.  */
10591   if (watchpoint_exp_is_const (exp.get ()))
10592     {
10593       int len;
10594
10595       len = exp_end - exp_start;
10596       while (len > 0 && isspace (exp_start[len - 1]))
10597         len--;
10598       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10599     }
10600
10601   exp_valid_block = tracker.block ();
10602   struct value *mark = value_mark ();
10603   struct value *val_as_value = nullptr;
10604   fetch_subexp_value (exp.get (), &pc, &val_as_value, &result, NULL,
10605                       just_location);
10606
10607   if (val_as_value != NULL && just_location)
10608     {
10609       saved_bitpos = value_bitpos (val_as_value);
10610       saved_bitsize = value_bitsize (val_as_value);
10611     }
10612
10613   value_ref_ptr val;
10614   if (just_location)
10615     {
10616       int ret;
10617
10618       exp_valid_block = NULL;
10619       val = release_value (value_addr (result));
10620       value_free_to_mark (mark);
10621
10622       if (use_mask)
10623         {
10624           ret = target_masked_watch_num_registers (value_as_address (val.get ()),
10625                                                    mask);
10626           if (ret == -1)
10627             error (_("This target does not support masked watchpoints."));
10628           else if (ret == -2)
10629             error (_("Invalid mask or memory region."));
10630         }
10631     }
10632   else if (val_as_value != NULL)
10633     val = release_value (val_as_value);
10634
10635   tok = skip_spaces (arg);
10636   end_tok = skip_to_space (tok);
10637
10638   toklen = end_tok - tok;
10639   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10640     {
10641       tok = cond_start = end_tok + 1;
10642       innermost_block_tracker if_tracker;
10643       parse_exp_1 (&tok, 0, 0, 0, &if_tracker);
10644
10645       /* The watchpoint expression may not be local, but the condition
10646          may still be.  E.g.: `watch global if local > 0'.  */
10647       cond_exp_valid_block = if_tracker.block ();
10648
10649       cond_end = tok;
10650     }
10651   if (*tok)
10652     error (_("Junk at end of command."));
10653
10654   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
10655
10656   /* Save this because create_internal_breakpoint below invalidates
10657      'wp_frame'.  */
10658   frame_id watchpoint_frame = get_frame_id (wp_frame);
10659
10660   /* If the expression is "local", then set up a "watchpoint scope"
10661      breakpoint at the point where we've left the scope of the watchpoint
10662      expression.  Create the scope breakpoint before the watchpoint, so
10663      that we will encounter it first in bpstat_stop_status.  */
10664   if (exp_valid_block != NULL && wp_frame != NULL)
10665     {
10666       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10667
10668       if (frame_id_p (caller_frame_id))
10669         {
10670           gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10671           CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10672
10673           scope_breakpoint
10674             = create_internal_breakpoint (caller_arch, caller_pc,
10675                                           bp_watchpoint_scope,
10676                                           &momentary_breakpoint_ops);
10677
10678           /* create_internal_breakpoint could invalidate WP_FRAME.  */
10679           wp_frame = NULL;
10680
10681           scope_breakpoint->enable_state = bp_enabled;
10682
10683           /* Automatically delete the breakpoint when it hits.  */
10684           scope_breakpoint->disposition = disp_del;
10685
10686           /* Only break in the proper frame (help with recursion).  */
10687           scope_breakpoint->frame_id = caller_frame_id;
10688
10689           /* Set the address at which we will stop.  */
10690           scope_breakpoint->loc->gdbarch = caller_arch;
10691           scope_breakpoint->loc->requested_address = caller_pc;
10692           scope_breakpoint->loc->address
10693             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10694                                          scope_breakpoint->loc->requested_address,
10695                                          scope_breakpoint->type);
10696         }
10697     }
10698
10699   /* Now set up the breakpoint.  We create all watchpoints as hardware
10700      watchpoints here even if hardware watchpoints are turned off, a call
10701      to update_watchpoint later in this function will cause the type to
10702      drop back to bp_watchpoint (software watchpoint) if required.  */
10703
10704   if (accessflag == hw_read)
10705     bp_type = bp_read_watchpoint;
10706   else if (accessflag == hw_access)
10707     bp_type = bp_access_watchpoint;
10708   else
10709     bp_type = bp_hardware_watchpoint;
10710
10711   std::unique_ptr<watchpoint> w (new watchpoint ());
10712
10713   if (use_mask)
10714     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10715                                           &masked_watchpoint_breakpoint_ops);
10716   else
10717     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10718                                           &watchpoint_breakpoint_ops);
10719   w->thread = thread;
10720   w->disposition = disp_donttouch;
10721   w->pspace = current_program_space;
10722   w->exp = std::move (exp);
10723   w->exp_valid_block = exp_valid_block;
10724   w->cond_exp_valid_block = cond_exp_valid_block;
10725   if (just_location)
10726     {
10727       struct type *t = value_type (val.get ());
10728       CORE_ADDR addr = value_as_address (val.get ());
10729
10730       w->exp_string_reparse
10731         = current_language->la_watch_location_expression (t, addr).release ();
10732
10733       w->exp_string = xstrprintf ("-location %.*s",
10734                                   (int) (exp_end - exp_start), exp_start);
10735     }
10736   else
10737     w->exp_string = savestring (exp_start, exp_end - exp_start);
10738
10739   if (use_mask)
10740     {
10741       w->hw_wp_mask = mask;
10742     }
10743   else
10744     {
10745       w->val = val;
10746       w->val_bitpos = saved_bitpos;
10747       w->val_bitsize = saved_bitsize;
10748       w->val_valid = 1;
10749     }
10750
10751   if (cond_start)
10752     w->cond_string = savestring (cond_start, cond_end - cond_start);
10753   else
10754     w->cond_string = 0;
10755
10756   if (frame_id_p (watchpoint_frame))
10757     {
10758       w->watchpoint_frame = watchpoint_frame;
10759       w->watchpoint_thread = inferior_ptid;
10760     }
10761   else
10762     {
10763       w->watchpoint_frame = null_frame_id;
10764       w->watchpoint_thread = null_ptid;
10765     }
10766
10767   if (scope_breakpoint != NULL)
10768     {
10769       /* The scope breakpoint is related to the watchpoint.  We will
10770          need to act on them together.  */
10771       w->related_breakpoint = scope_breakpoint;
10772       scope_breakpoint->related_breakpoint = w.get ();
10773     }
10774
10775   if (!just_location)
10776     value_free_to_mark (mark);
10777
10778   /* Finally update the new watchpoint.  This creates the locations
10779      that should be inserted.  */
10780   update_watchpoint (w.get (), 1);
10781
10782   install_breakpoint (internal, std::move (w), 1);
10783 }
10784
10785 /* Return count of debug registers needed to watch the given expression.
10786    If the watchpoint cannot be handled in hardware return zero.  */
10787
10788 static int
10789 can_use_hardware_watchpoint (const std::vector<value_ref_ptr> &vals)
10790 {
10791   int found_memory_cnt = 0;
10792
10793   /* Did the user specifically forbid us to use hardware watchpoints? */
10794   if (!can_use_hw_watchpoints)
10795     return 0;
10796
10797   gdb_assert (!vals.empty ());
10798   struct value *head = vals[0].get ();
10799
10800   /* Make sure that the value of the expression depends only upon
10801      memory contents, and values computed from them within GDB.  If we
10802      find any register references or function calls, we can't use a
10803      hardware watchpoint.
10804
10805      The idea here is that evaluating an expression generates a series
10806      of values, one holding the value of every subexpression.  (The
10807      expression a*b+c has five subexpressions: a, b, a*b, c, and
10808      a*b+c.)  GDB's values hold almost enough information to establish
10809      the criteria given above --- they identify memory lvalues,
10810      register lvalues, computed values, etcetera.  So we can evaluate
10811      the expression, and then scan the chain of values that leaves
10812      behind to decide whether we can detect any possible change to the
10813      expression's final value using only hardware watchpoints.
10814
10815      However, I don't think that the values returned by inferior
10816      function calls are special in any way.  So this function may not
10817      notice that an expression involving an inferior function call
10818      can't be watched with hardware watchpoints.  FIXME.  */
10819   for (const value_ref_ptr &iter : vals)
10820     {
10821       struct value *v = iter.get ();
10822
10823       if (VALUE_LVAL (v) == lval_memory)
10824         {
10825           if (v != head && value_lazy (v))
10826             /* A lazy memory lvalue in the chain is one that GDB never
10827                needed to fetch; we either just used its address (e.g.,
10828                `a' in `a.b') or we never needed it at all (e.g., `a'
10829                in `a,b').  This doesn't apply to HEAD; if that is
10830                lazy then it was not readable, but watch it anyway.  */
10831             ;
10832           else
10833             {
10834               /* Ahh, memory we actually used!  Check if we can cover
10835                  it with hardware watchpoints.  */
10836               struct type *vtype = check_typedef (value_type (v));
10837
10838               /* We only watch structs and arrays if user asked for it
10839                  explicitly, never if they just happen to appear in a
10840                  middle of some value chain.  */
10841               if (v == head
10842                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
10843                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
10844                 {
10845                   CORE_ADDR vaddr = value_address (v);
10846                   int len;
10847                   int num_regs;
10848
10849                   len = (target_exact_watchpoints
10850                          && is_scalar_type_recursive (vtype))?
10851                     1 : TYPE_LENGTH (value_type (v));
10852
10853                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10854                   if (!num_regs)
10855                     return 0;
10856                   else
10857                     found_memory_cnt += num_regs;
10858                 }
10859             }
10860         }
10861       else if (VALUE_LVAL (v) != not_lval
10862                && deprecated_value_modifiable (v) == 0)
10863         return 0;       /* These are values from the history (e.g., $1).  */
10864       else if (VALUE_LVAL (v) == lval_register)
10865         return 0;       /* Cannot watch a register with a HW watchpoint.  */
10866     }
10867
10868   /* The expression itself looks suitable for using a hardware
10869      watchpoint, but give the target machine a chance to reject it.  */
10870   return found_memory_cnt;
10871 }
10872
10873 void
10874 watch_command_wrapper (const char *arg, int from_tty, int internal)
10875 {
10876   watch_command_1 (arg, hw_write, from_tty, 0, internal);
10877 }
10878
10879 /* A helper function that looks for the "-location" argument and then
10880    calls watch_command_1.  */
10881
10882 static void
10883 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
10884 {
10885   int just_location = 0;
10886
10887   if (arg
10888       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
10889           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
10890     just_location = 1;
10891
10892   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
10893 }
10894
10895 static void
10896 watch_command (const char *arg, int from_tty)
10897 {
10898   watch_maybe_just_location (arg, hw_write, from_tty);
10899 }
10900
10901 void
10902 rwatch_command_wrapper (const char *arg, int from_tty, int internal)
10903 {
10904   watch_command_1 (arg, hw_read, from_tty, 0, internal);
10905 }
10906
10907 static void
10908 rwatch_command (const char *arg, int from_tty)
10909 {
10910   watch_maybe_just_location (arg, hw_read, from_tty);
10911 }
10912
10913 void
10914 awatch_command_wrapper (const char *arg, int from_tty, int internal)
10915 {
10916   watch_command_1 (arg, hw_access, from_tty, 0, internal);
10917 }
10918
10919 static void
10920 awatch_command (const char *arg, int from_tty)
10921 {
10922   watch_maybe_just_location (arg, hw_access, from_tty);
10923 }
10924 \f
10925
10926 /* Data for the FSM that manages the until(location)/advance commands
10927    in infcmd.c.  Here because it uses the mechanisms of
10928    breakpoints.  */
10929
10930 struct until_break_fsm : public thread_fsm
10931 {
10932   /* The thread that was current when the command was executed.  */
10933   int thread;
10934
10935   /* The breakpoint set at the destination location.  */
10936   breakpoint_up location_breakpoint;
10937
10938   /* Breakpoint set at the return address in the caller frame.  May be
10939      NULL.  */
10940   breakpoint_up caller_breakpoint;
10941
10942   until_break_fsm (struct interp *cmd_interp, int thread,
10943                    breakpoint_up &&location_breakpoint,
10944                    breakpoint_up &&caller_breakpoint)
10945     : thread_fsm (cmd_interp),
10946       thread (thread),
10947       location_breakpoint (std::move (location_breakpoint)),
10948       caller_breakpoint (std::move (caller_breakpoint))
10949   {
10950   }
10951
10952   void clean_up (struct thread_info *thread) override;
10953   bool should_stop (struct thread_info *thread) override;
10954   enum async_reply_reason do_async_reply_reason () override;
10955 };
10956
10957 /* Implementation of the 'should_stop' FSM method for the
10958    until(location)/advance commands.  */
10959
10960 bool
10961 until_break_fsm::should_stop (struct thread_info *tp)
10962 {
10963   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
10964                               location_breakpoint.get ()) != NULL
10965       || (caller_breakpoint != NULL
10966           && bpstat_find_breakpoint (tp->control.stop_bpstat,
10967                                      caller_breakpoint.get ()) != NULL))
10968     set_finished ();
10969
10970   return true;
10971 }
10972
10973 /* Implementation of the 'clean_up' FSM method for the
10974    until(location)/advance commands.  */
10975
10976 void
10977 until_break_fsm::clean_up (struct thread_info *)
10978 {
10979   /* Clean up our temporary breakpoints.  */
10980   location_breakpoint.reset ();
10981   caller_breakpoint.reset ();
10982   delete_longjmp_breakpoint (thread);
10983 }
10984
10985 /* Implementation of the 'async_reply_reason' FSM method for the
10986    until(location)/advance commands.  */
10987
10988 enum async_reply_reason
10989 until_break_fsm::do_async_reply_reason ()
10990 {
10991   return EXEC_ASYNC_LOCATION_REACHED;
10992 }
10993
10994 void
10995 until_break_command (const char *arg, int from_tty, int anywhere)
10996 {
10997   struct frame_info *frame;
10998   struct gdbarch *frame_gdbarch;
10999   struct frame_id stack_frame_id;
11000   struct frame_id caller_frame_id;
11001   int thread;
11002   struct thread_info *tp;
11003
11004   clear_proceed_status (0);
11005
11006   /* Set a breakpoint where the user wants it and at return from
11007      this function.  */
11008
11009   event_location_up location = string_to_event_location (&arg, current_language);
11010
11011   std::vector<symtab_and_line> sals
11012     = (last_displayed_sal_is_valid ()
11013        ? decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
11014                         get_last_displayed_symtab (),
11015                         get_last_displayed_line ())
11016        : decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
11017                         NULL, NULL, 0));
11018
11019   if (sals.size () != 1)
11020     error (_("Couldn't get information on specified line."));
11021
11022   symtab_and_line &sal = sals[0];
11023
11024   if (*arg)
11025     error (_("Junk at end of arguments."));
11026
11027   resolve_sal_pc (&sal);
11028
11029   tp = inferior_thread ();
11030   thread = tp->global_num;
11031
11032   /* Note linespec handling above invalidates the frame chain.
11033      Installing a breakpoint also invalidates the frame chain (as it
11034      may need to switch threads), so do any frame handling before
11035      that.  */
11036
11037   frame = get_selected_frame (NULL);
11038   frame_gdbarch = get_frame_arch (frame);
11039   stack_frame_id = get_stack_frame_id (frame);
11040   caller_frame_id = frame_unwind_caller_id (frame);
11041
11042   /* Keep within the current frame, or in frames called by the current
11043      one.  */
11044
11045   breakpoint_up caller_breakpoint;
11046
11047   gdb::optional<delete_longjmp_breakpoint_cleanup> lj_deleter;
11048
11049   if (frame_id_p (caller_frame_id))
11050     {
11051       struct symtab_and_line sal2;
11052       struct gdbarch *caller_gdbarch;
11053
11054       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11055       sal2.pc = frame_unwind_caller_pc (frame);
11056       caller_gdbarch = frame_unwind_caller_arch (frame);
11057       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11058                                                     sal2,
11059                                                     caller_frame_id,
11060                                                     bp_until);
11061
11062       set_longjmp_breakpoint (tp, caller_frame_id);
11063       lj_deleter.emplace (thread);
11064     }
11065
11066   /* set_momentary_breakpoint could invalidate FRAME.  */
11067   frame = NULL;
11068
11069   breakpoint_up location_breakpoint;
11070   if (anywhere)
11071     /* If the user told us to continue until a specified location,
11072        we don't specify a frame at which we need to stop.  */
11073     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11074                                                     null_frame_id, bp_until);
11075   else
11076     /* Otherwise, specify the selected frame, because we want to stop
11077        only at the very same frame.  */
11078     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11079                                                     stack_frame_id, bp_until);
11080
11081   tp->thread_fsm = new until_break_fsm (command_interp (), tp->global_num,
11082                                         std::move (location_breakpoint),
11083                                         std::move (caller_breakpoint));
11084
11085   if (lj_deleter)
11086     lj_deleter->release ();
11087
11088   proceed (-1, GDB_SIGNAL_DEFAULT);
11089 }
11090
11091 /* This function attempts to parse an optional "if <cond>" clause
11092    from the arg string.  If one is not found, it returns NULL.
11093
11094    Else, it returns a pointer to the condition string.  (It does not
11095    attempt to evaluate the string against a particular block.)  And,
11096    it updates arg to point to the first character following the parsed
11097    if clause in the arg string.  */
11098
11099 const char *
11100 ep_parse_optional_if_clause (const char **arg)
11101 {
11102   const char *cond_string;
11103
11104   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11105     return NULL;
11106
11107   /* Skip the "if" keyword.  */
11108   (*arg) += 2;
11109
11110   /* Skip any extra leading whitespace, and record the start of the
11111      condition string.  */
11112   *arg = skip_spaces (*arg);
11113   cond_string = *arg;
11114
11115   /* Assume that the condition occupies the remainder of the arg
11116      string.  */
11117   (*arg) += strlen (cond_string);
11118
11119   return cond_string;
11120 }
11121
11122 /* Commands to deal with catching events, such as signals, exceptions,
11123    process start/exit, etc.  */
11124
11125 typedef enum
11126 {
11127   catch_fork_temporary, catch_vfork_temporary,
11128   catch_fork_permanent, catch_vfork_permanent
11129 }
11130 catch_fork_kind;
11131
11132 static void
11133 catch_fork_command_1 (const char *arg, int from_tty,
11134                       struct cmd_list_element *command)
11135 {
11136   struct gdbarch *gdbarch = get_current_arch ();
11137   const char *cond_string = NULL;
11138   catch_fork_kind fork_kind;
11139   int tempflag;
11140
11141   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11142   tempflag = (fork_kind == catch_fork_temporary
11143               || fork_kind == catch_vfork_temporary);
11144
11145   if (!arg)
11146     arg = "";
11147   arg = skip_spaces (arg);
11148
11149   /* The allowed syntax is:
11150      catch [v]fork
11151      catch [v]fork if <cond>
11152
11153      First, check if there's an if clause.  */
11154   cond_string = ep_parse_optional_if_clause (&arg);
11155
11156   if ((*arg != '\0') && !isspace (*arg))
11157     error (_("Junk at end of arguments."));
11158
11159   /* If this target supports it, create a fork or vfork catchpoint
11160      and enable reporting of such events.  */
11161   switch (fork_kind)
11162     {
11163     case catch_fork_temporary:
11164     case catch_fork_permanent:
11165       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11166                                           &catch_fork_breakpoint_ops);
11167       break;
11168     case catch_vfork_temporary:
11169     case catch_vfork_permanent:
11170       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11171                                           &catch_vfork_breakpoint_ops);
11172       break;
11173     default:
11174       error (_("unsupported or unknown fork kind; cannot catch it"));
11175       break;
11176     }
11177 }
11178
11179 static void
11180 catch_exec_command_1 (const char *arg, int from_tty,
11181                       struct cmd_list_element *command)
11182 {
11183   struct gdbarch *gdbarch = get_current_arch ();
11184   int tempflag;
11185   const char *cond_string = NULL;
11186
11187   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11188
11189   if (!arg)
11190     arg = "";
11191   arg = skip_spaces (arg);
11192
11193   /* The allowed syntax is:
11194      catch exec
11195      catch exec if <cond>
11196
11197      First, check if there's an if clause.  */
11198   cond_string = ep_parse_optional_if_clause (&arg);
11199
11200   if ((*arg != '\0') && !isspace (*arg))
11201     error (_("Junk at end of arguments."));
11202
11203   std::unique_ptr<exec_catchpoint> c (new exec_catchpoint ());
11204   init_catchpoint (c.get (), gdbarch, tempflag, cond_string,
11205                    &catch_exec_breakpoint_ops);
11206   c->exec_pathname = NULL;
11207
11208   install_breakpoint (0, std::move (c), 1);
11209 }
11210
11211 void
11212 init_ada_exception_breakpoint (struct breakpoint *b,
11213                                struct gdbarch *gdbarch,
11214                                struct symtab_and_line sal,
11215                                const char *addr_string,
11216                                const struct breakpoint_ops *ops,
11217                                int tempflag,
11218                                int enabled,
11219                                int from_tty)
11220 {
11221   if (from_tty)
11222     {
11223       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11224       if (!loc_gdbarch)
11225         loc_gdbarch = gdbarch;
11226
11227       describe_other_breakpoints (loc_gdbarch,
11228                                   sal.pspace, sal.pc, sal.section, -1);
11229       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11230          version for exception catchpoints, because two catchpoints
11231          used for different exception names will use the same address.
11232          In this case, a "breakpoint ... also set at..." warning is
11233          unproductive.  Besides, the warning phrasing is also a bit
11234          inappropriate, we should use the word catchpoint, and tell
11235          the user what type of catchpoint it is.  The above is good
11236          enough for now, though.  */
11237     }
11238
11239   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11240
11241   b->enable_state = enabled ? bp_enabled : bp_disabled;
11242   b->disposition = tempflag ? disp_del : disp_donttouch;
11243   b->location = string_to_event_location (&addr_string,
11244                                           language_def (language_ada));
11245   b->language = language_ada;
11246 }
11247
11248 static void
11249 catch_command (const char *arg, int from_tty)
11250 {
11251   error (_("Catch requires an event name."));
11252 }
11253 \f
11254
11255 static void
11256 tcatch_command (const char *arg, int from_tty)
11257 {
11258   error (_("Catch requires an event name."));
11259 }
11260
11261 /* Compare two breakpoints and return a strcmp-like result.  */
11262
11263 static int
11264 compare_breakpoints (const breakpoint *a, const breakpoint *b)
11265 {
11266   uintptr_t ua = (uintptr_t) a;
11267   uintptr_t ub = (uintptr_t) b;
11268
11269   if (a->number < b->number)
11270     return -1;
11271   else if (a->number > b->number)
11272     return 1;
11273
11274   /* Now sort by address, in case we see, e..g, two breakpoints with
11275      the number 0.  */
11276   if (ua < ub)
11277     return -1;
11278   return ua > ub ? 1 : 0;
11279 }
11280
11281 /* Delete breakpoints by address or line.  */
11282
11283 static void
11284 clear_command (const char *arg, int from_tty)
11285 {
11286   struct breakpoint *b;
11287   int default_match;
11288
11289   std::vector<symtab_and_line> decoded_sals;
11290   symtab_and_line last_sal;
11291   gdb::array_view<symtab_and_line> sals;
11292   if (arg)
11293     {
11294       decoded_sals
11295         = decode_line_with_current_source (arg,
11296                                            (DECODE_LINE_FUNFIRSTLINE
11297                                             | DECODE_LINE_LIST_MODE));
11298       default_match = 0;
11299       sals = decoded_sals;
11300     }
11301   else
11302     {
11303       /* Set sal's line, symtab, pc, and pspace to the values
11304          corresponding to the last call to print_frame_info.  If the
11305          codepoint is not valid, this will set all the fields to 0.  */
11306       last_sal = get_last_displayed_sal ();
11307       if (last_sal.symtab == 0)
11308         error (_("No source file specified."));
11309
11310       default_match = 1;
11311       sals = last_sal;
11312     }
11313
11314   /* We don't call resolve_sal_pc here.  That's not as bad as it
11315      seems, because all existing breakpoints typically have both
11316      file/line and pc set.  So, if clear is given file/line, we can
11317      match this to existing breakpoint without obtaining pc at all.
11318
11319      We only support clearing given the address explicitly 
11320      present in breakpoint table.  Say, we've set breakpoint 
11321      at file:line.  There were several PC values for that file:line,
11322      due to optimization, all in one block.
11323
11324      We've picked one PC value.  If "clear" is issued with another
11325      PC corresponding to the same file:line, the breakpoint won't
11326      be cleared.  We probably can still clear the breakpoint, but 
11327      since the other PC value is never presented to user, user
11328      can only find it by guessing, and it does not seem important
11329      to support that.  */
11330
11331   /* For each line spec given, delete bps which correspond to it.  Do
11332      it in two passes, solely to preserve the current behavior that
11333      from_tty is forced true if we delete more than one
11334      breakpoint.  */
11335
11336   std::vector<struct breakpoint *> found;
11337   for (const auto &sal : sals)
11338     {
11339       const char *sal_fullname;
11340
11341       /* If exact pc given, clear bpts at that pc.
11342          If line given (pc == 0), clear all bpts on specified line.
11343          If defaulting, clear all bpts on default line
11344          or at default pc.
11345
11346          defaulting    sal.pc != 0    tests to do
11347
11348          0              1             pc
11349          1              1             pc _and_ line
11350          0              0             line
11351          1              0             <can't happen> */
11352
11353       sal_fullname = (sal.symtab == NULL
11354                       ? NULL : symtab_to_fullname (sal.symtab));
11355
11356       /* Find all matching breakpoints and add them to 'found'.  */
11357       ALL_BREAKPOINTS (b)
11358         {
11359           int match = 0;
11360           /* Are we going to delete b?  */
11361           if (b->type != bp_none && !is_watchpoint (b))
11362             {
11363               struct bp_location *loc = b->loc;
11364               for (; loc; loc = loc->next)
11365                 {
11366                   /* If the user specified file:line, don't allow a PC
11367                      match.  This matches historical gdb behavior.  */
11368                   int pc_match = (!sal.explicit_line
11369                                   && sal.pc
11370                                   && (loc->pspace == sal.pspace)
11371                                   && (loc->address == sal.pc)
11372                                   && (!section_is_overlay (loc->section)
11373                                       || loc->section == sal.section));
11374                   int line_match = 0;
11375
11376                   if ((default_match || sal.explicit_line)
11377                       && loc->symtab != NULL
11378                       && sal_fullname != NULL
11379                       && sal.pspace == loc->pspace
11380                       && loc->line_number == sal.line
11381                       && filename_cmp (symtab_to_fullname (loc->symtab),
11382                                        sal_fullname) == 0)
11383                     line_match = 1;
11384
11385                   if (pc_match || line_match)
11386                     {
11387                       match = 1;
11388                       break;
11389                     }
11390                 }
11391             }
11392
11393           if (match)
11394             found.push_back (b);
11395         }
11396     }
11397
11398   /* Now go thru the 'found' chain and delete them.  */
11399   if (found.empty ())
11400     {
11401       if (arg)
11402         error (_("No breakpoint at %s."), arg);
11403       else
11404         error (_("No breakpoint at this line."));
11405     }
11406
11407   /* Remove duplicates from the vec.  */
11408   std::sort (found.begin (), found.end (),
11409              [] (const breakpoint *bp_a, const breakpoint *bp_b)
11410              {
11411                return compare_breakpoints (bp_a, bp_b) < 0;
11412              });
11413   found.erase (std::unique (found.begin (), found.end (),
11414                             [] (const breakpoint *bp_a, const breakpoint *bp_b)
11415                             {
11416                               return compare_breakpoints (bp_a, bp_b) == 0;
11417                             }),
11418                found.end ());
11419
11420   if (found.size () > 1)
11421     from_tty = 1;       /* Always report if deleted more than one.  */
11422   if (from_tty)
11423     {
11424       if (found.size () == 1)
11425         printf_unfiltered (_("Deleted breakpoint "));
11426       else
11427         printf_unfiltered (_("Deleted breakpoints "));
11428     }
11429
11430   for (breakpoint *iter : found)
11431     {
11432       if (from_tty)
11433         printf_unfiltered ("%d ", iter->number);
11434       delete_breakpoint (iter);
11435     }
11436   if (from_tty)
11437     putchar_unfiltered ('\n');
11438 }
11439 \f
11440 /* Delete breakpoint in BS if they are `delete' breakpoints and
11441    all breakpoints that are marked for deletion, whether hit or not.
11442    This is called after any breakpoint is hit, or after errors.  */
11443
11444 void
11445 breakpoint_auto_delete (bpstat bs)
11446 {
11447   struct breakpoint *b, *b_tmp;
11448
11449   for (; bs; bs = bs->next)
11450     if (bs->breakpoint_at
11451         && bs->breakpoint_at->disposition == disp_del
11452         && bs->stop)
11453       delete_breakpoint (bs->breakpoint_at);
11454
11455   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11456   {
11457     if (b->disposition == disp_del_at_next_stop)
11458       delete_breakpoint (b);
11459   }
11460 }
11461
11462 /* A comparison function for bp_location AP and BP being interfaced to
11463    qsort.  Sort elements primarily by their ADDRESS (no matter what
11464    does breakpoint_address_is_meaningful say for its OWNER),
11465    secondarily by ordering first permanent elements and
11466    terciarily just ensuring the array is sorted stable way despite
11467    qsort being an unstable algorithm.  */
11468
11469 static int
11470 bp_locations_compare (const void *ap, const void *bp)
11471 {
11472   const struct bp_location *a = *(const struct bp_location **) ap;
11473   const struct bp_location *b = *(const struct bp_location **) bp;
11474
11475   if (a->address != b->address)
11476     return (a->address > b->address) - (a->address < b->address);
11477
11478   /* Sort locations at the same address by their pspace number, keeping
11479      locations of the same inferior (in a multi-inferior environment)
11480      grouped.  */
11481
11482   if (a->pspace->num != b->pspace->num)
11483     return ((a->pspace->num > b->pspace->num)
11484             - (a->pspace->num < b->pspace->num));
11485
11486   /* Sort permanent breakpoints first.  */
11487   if (a->permanent != b->permanent)
11488     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
11489
11490   /* Make the internal GDB representation stable across GDB runs
11491      where A and B memory inside GDB can differ.  Breakpoint locations of
11492      the same type at the same address can be sorted in arbitrary order.  */
11493
11494   if (a->owner->number != b->owner->number)
11495     return ((a->owner->number > b->owner->number)
11496             - (a->owner->number < b->owner->number));
11497
11498   return (a > b) - (a < b);
11499 }
11500
11501 /* Set bp_locations_placed_address_before_address_max and
11502    bp_locations_shadow_len_after_address_max according to the current
11503    content of the bp_locations array.  */
11504
11505 static void
11506 bp_locations_target_extensions_update (void)
11507 {
11508   struct bp_location *bl, **blp_tmp;
11509
11510   bp_locations_placed_address_before_address_max = 0;
11511   bp_locations_shadow_len_after_address_max = 0;
11512
11513   ALL_BP_LOCATIONS (bl, blp_tmp)
11514     {
11515       CORE_ADDR start, end, addr;
11516
11517       if (!bp_location_has_shadow (bl))
11518         continue;
11519
11520       start = bl->target_info.placed_address;
11521       end = start + bl->target_info.shadow_len;
11522
11523       gdb_assert (bl->address >= start);
11524       addr = bl->address - start;
11525       if (addr > bp_locations_placed_address_before_address_max)
11526         bp_locations_placed_address_before_address_max = addr;
11527
11528       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11529
11530       gdb_assert (bl->address < end);
11531       addr = end - bl->address;
11532       if (addr > bp_locations_shadow_len_after_address_max)
11533         bp_locations_shadow_len_after_address_max = addr;
11534     }
11535 }
11536
11537 /* Download tracepoint locations if they haven't been.  */
11538
11539 static void
11540 download_tracepoint_locations (void)
11541 {
11542   struct breakpoint *b;
11543   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11544
11545   scoped_restore_current_pspace_and_thread restore_pspace_thread;
11546
11547   ALL_TRACEPOINTS (b)
11548     {
11549       struct bp_location *bl;
11550       struct tracepoint *t;
11551       int bp_location_downloaded = 0;
11552
11553       if ((b->type == bp_fast_tracepoint
11554            ? !may_insert_fast_tracepoints
11555            : !may_insert_tracepoints))
11556         continue;
11557
11558       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11559         {
11560           if (target_can_download_tracepoint ())
11561             can_download_tracepoint = TRIBOOL_TRUE;
11562           else
11563             can_download_tracepoint = TRIBOOL_FALSE;
11564         }
11565
11566       if (can_download_tracepoint == TRIBOOL_FALSE)
11567         break;
11568
11569       for (bl = b->loc; bl; bl = bl->next)
11570         {
11571           /* In tracepoint, locations are _never_ duplicated, so
11572              should_be_inserted is equivalent to
11573              unduplicated_should_be_inserted.  */
11574           if (!should_be_inserted (bl) || bl->inserted)
11575             continue;
11576
11577           switch_to_program_space_and_thread (bl->pspace);
11578
11579           target_download_tracepoint (bl);
11580
11581           bl->inserted = 1;
11582           bp_location_downloaded = 1;
11583         }
11584       t = (struct tracepoint *) b;
11585       t->number_on_target = b->number;
11586       if (bp_location_downloaded)
11587         gdb::observers::breakpoint_modified.notify (b);
11588     }
11589 }
11590
11591 /* Swap the insertion/duplication state between two locations.  */
11592
11593 static void
11594 swap_insertion (struct bp_location *left, struct bp_location *right)
11595 {
11596   const int left_inserted = left->inserted;
11597   const int left_duplicate = left->duplicate;
11598   const int left_needs_update = left->needs_update;
11599   const struct bp_target_info left_target_info = left->target_info;
11600
11601   /* Locations of tracepoints can never be duplicated.  */
11602   if (is_tracepoint (left->owner))
11603     gdb_assert (!left->duplicate);
11604   if (is_tracepoint (right->owner))
11605     gdb_assert (!right->duplicate);
11606
11607   left->inserted = right->inserted;
11608   left->duplicate = right->duplicate;
11609   left->needs_update = right->needs_update;
11610   left->target_info = right->target_info;
11611   right->inserted = left_inserted;
11612   right->duplicate = left_duplicate;
11613   right->needs_update = left_needs_update;
11614   right->target_info = left_target_info;
11615 }
11616
11617 /* Force the re-insertion of the locations at ADDRESS.  This is called
11618    once a new/deleted/modified duplicate location is found and we are evaluating
11619    conditions on the target's side.  Such conditions need to be updated on
11620    the target.  */
11621
11622 static void
11623 force_breakpoint_reinsertion (struct bp_location *bl)
11624 {
11625   struct bp_location **locp = NULL, **loc2p;
11626   struct bp_location *loc;
11627   CORE_ADDR address = 0;
11628   int pspace_num;
11629
11630   address = bl->address;
11631   pspace_num = bl->pspace->num;
11632
11633   /* This is only meaningful if the target is
11634      evaluating conditions and if the user has
11635      opted for condition evaluation on the target's
11636      side.  */
11637   if (gdb_evaluates_breakpoint_condition_p ()
11638       || !target_supports_evaluation_of_breakpoint_conditions ())
11639     return;
11640
11641   /* Flag all breakpoint locations with this address and
11642      the same program space as the location
11643      as "its condition has changed".  We need to
11644      update the conditions on the target's side.  */
11645   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11646     {
11647       loc = *loc2p;
11648
11649       if (!is_breakpoint (loc->owner)
11650           || pspace_num != loc->pspace->num)
11651         continue;
11652
11653       /* Flag the location appropriately.  We use a different state to
11654          let everyone know that we already updated the set of locations
11655          with addr bl->address and program space bl->pspace.  This is so
11656          we don't have to keep calling these functions just to mark locations
11657          that have already been marked.  */
11658       loc->condition_changed = condition_updated;
11659
11660       /* Free the agent expression bytecode as well.  We will compute
11661          it later on.  */
11662       loc->cond_bytecode.reset ();
11663     }
11664 }
11665 /* Called whether new breakpoints are created, or existing breakpoints
11666    deleted, to update the global location list and recompute which
11667    locations are duplicate of which.
11668
11669    The INSERT_MODE flag determines whether locations may not, may, or
11670    shall be inserted now.  See 'enum ugll_insert_mode' for more
11671    info.  */
11672
11673 static void
11674 update_global_location_list (enum ugll_insert_mode insert_mode)
11675 {
11676   struct breakpoint *b;
11677   struct bp_location **locp, *loc;
11678   /* Last breakpoint location address that was marked for update.  */
11679   CORE_ADDR last_addr = 0;
11680   /* Last breakpoint location program space that was marked for update.  */
11681   int last_pspace_num = -1;
11682
11683   /* Used in the duplicates detection below.  When iterating over all
11684      bp_locations, points to the first bp_location of a given address.
11685      Breakpoints and watchpoints of different types are never
11686      duplicates of each other.  Keep one pointer for each type of
11687      breakpoint/watchpoint, so we only need to loop over all locations
11688      once.  */
11689   struct bp_location *bp_loc_first;  /* breakpoint */
11690   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11691   struct bp_location *awp_loc_first; /* access watchpoint */
11692   struct bp_location *rwp_loc_first; /* read watchpoint */
11693
11694   /* Saved former bp_locations array which we compare against the newly
11695      built bp_locations from the current state of ALL_BREAKPOINTS.  */
11696   struct bp_location **old_locp;
11697   unsigned old_locations_count;
11698   gdb::unique_xmalloc_ptr<struct bp_location *> old_locations (bp_locations);
11699
11700   old_locations_count = bp_locations_count;
11701   bp_locations = NULL;
11702   bp_locations_count = 0;
11703
11704   ALL_BREAKPOINTS (b)
11705     for (loc = b->loc; loc; loc = loc->next)
11706       bp_locations_count++;
11707
11708   bp_locations = XNEWVEC (struct bp_location *, bp_locations_count);
11709   locp = bp_locations;
11710   ALL_BREAKPOINTS (b)
11711     for (loc = b->loc; loc; loc = loc->next)
11712       *locp++ = loc;
11713   qsort (bp_locations, bp_locations_count, sizeof (*bp_locations),
11714          bp_locations_compare);
11715
11716   bp_locations_target_extensions_update ();
11717
11718   /* Identify bp_location instances that are no longer present in the
11719      new list, and therefore should be freed.  Note that it's not
11720      necessary that those locations should be removed from inferior --
11721      if there's another location at the same address (previously
11722      marked as duplicate), we don't need to remove/insert the
11723      location.
11724      
11725      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11726      and former bp_location array state respectively.  */
11727
11728   locp = bp_locations;
11729   for (old_locp = old_locations.get ();
11730        old_locp < old_locations.get () + old_locations_count;
11731        old_locp++)
11732     {
11733       struct bp_location *old_loc = *old_locp;
11734       struct bp_location **loc2p;
11735
11736       /* Tells if 'old_loc' is found among the new locations.  If
11737          not, we have to free it.  */
11738       int found_object = 0;
11739       /* Tells if the location should remain inserted in the target.  */
11740       int keep_in_target = 0;
11741       int removed = 0;
11742
11743       /* Skip LOCP entries which will definitely never be needed.
11744          Stop either at or being the one matching OLD_LOC.  */
11745       while (locp < bp_locations + bp_locations_count
11746              && (*locp)->address < old_loc->address)
11747         locp++;
11748
11749       for (loc2p = locp;
11750            (loc2p < bp_locations + bp_locations_count
11751             && (*loc2p)->address == old_loc->address);
11752            loc2p++)
11753         {
11754           /* Check if this is a new/duplicated location or a duplicated
11755              location that had its condition modified.  If so, we want to send
11756              its condition to the target if evaluation of conditions is taking
11757              place there.  */
11758           if ((*loc2p)->condition_changed == condition_modified
11759               && (last_addr != old_loc->address
11760                   || last_pspace_num != old_loc->pspace->num))
11761             {
11762               force_breakpoint_reinsertion (*loc2p);
11763               last_pspace_num = old_loc->pspace->num;
11764             }
11765
11766           if (*loc2p == old_loc)
11767             found_object = 1;
11768         }
11769
11770       /* We have already handled this address, update it so that we don't
11771          have to go through updates again.  */
11772       last_addr = old_loc->address;
11773
11774       /* Target-side condition evaluation: Handle deleted locations.  */
11775       if (!found_object)
11776         force_breakpoint_reinsertion (old_loc);
11777
11778       /* If this location is no longer present, and inserted, look if
11779          there's maybe a new location at the same address.  If so,
11780          mark that one inserted, and don't remove this one.  This is
11781          needed so that we don't have a time window where a breakpoint
11782          at certain location is not inserted.  */
11783
11784       if (old_loc->inserted)
11785         {
11786           /* If the location is inserted now, we might have to remove
11787              it.  */
11788
11789           if (found_object && should_be_inserted (old_loc))
11790             {
11791               /* The location is still present in the location list,
11792                  and still should be inserted.  Don't do anything.  */
11793               keep_in_target = 1;
11794             }
11795           else
11796             {
11797               /* This location still exists, but it won't be kept in the
11798                  target since it may have been disabled.  We proceed to
11799                  remove its target-side condition.  */
11800
11801               /* The location is either no longer present, or got
11802                  disabled.  See if there's another location at the
11803                  same address, in which case we don't need to remove
11804                  this one from the target.  */
11805
11806               /* OLD_LOC comes from existing struct breakpoint.  */
11807               if (breakpoint_address_is_meaningful (old_loc->owner))
11808                 {
11809                   for (loc2p = locp;
11810                        (loc2p < bp_locations + bp_locations_count
11811                         && (*loc2p)->address == old_loc->address);
11812                        loc2p++)
11813                     {
11814                       struct bp_location *loc2 = *loc2p;
11815
11816                       if (breakpoint_locations_match (loc2, old_loc))
11817                         {
11818                           /* Read watchpoint locations are switched to
11819                              access watchpoints, if the former are not
11820                              supported, but the latter are.  */
11821                           if (is_hardware_watchpoint (old_loc->owner))
11822                             {
11823                               gdb_assert (is_hardware_watchpoint (loc2->owner));
11824                               loc2->watchpoint_type = old_loc->watchpoint_type;
11825                             }
11826
11827                           /* loc2 is a duplicated location. We need to check
11828                              if it should be inserted in case it will be
11829                              unduplicated.  */
11830                           if (loc2 != old_loc
11831                               && unduplicated_should_be_inserted (loc2))
11832                             {
11833                               swap_insertion (old_loc, loc2);
11834                               keep_in_target = 1;
11835                               break;
11836                             }
11837                         }
11838                     }
11839                 }
11840             }
11841
11842           if (!keep_in_target)
11843             {
11844               if (remove_breakpoint (old_loc))
11845                 {
11846                   /* This is just about all we can do.  We could keep
11847                      this location on the global list, and try to
11848                      remove it next time, but there's no particular
11849                      reason why we will succeed next time.
11850                      
11851                      Note that at this point, old_loc->owner is still
11852                      valid, as delete_breakpoint frees the breakpoint
11853                      only after calling us.  */
11854                   printf_filtered (_("warning: Error removing "
11855                                      "breakpoint %d\n"), 
11856                                    old_loc->owner->number);
11857                 }
11858               removed = 1;
11859             }
11860         }
11861
11862       if (!found_object)
11863         {
11864           if (removed && target_is_non_stop_p ()
11865               && need_moribund_for_location_type (old_loc))
11866             {
11867               /* This location was removed from the target.  In
11868                  non-stop mode, a race condition is possible where
11869                  we've removed a breakpoint, but stop events for that
11870                  breakpoint are already queued and will arrive later.
11871                  We apply an heuristic to be able to distinguish such
11872                  SIGTRAPs from other random SIGTRAPs: we keep this
11873                  breakpoint location for a bit, and will retire it
11874                  after we see some number of events.  The theory here
11875                  is that reporting of events should, "on the average",
11876                  be fair, so after a while we'll see events from all
11877                  threads that have anything of interest, and no longer
11878                  need to keep this breakpoint location around.  We
11879                  don't hold locations forever so to reduce chances of
11880                  mistaking a non-breakpoint SIGTRAP for a breakpoint
11881                  SIGTRAP.
11882
11883                  The heuristic failing can be disastrous on
11884                  decr_pc_after_break targets.
11885
11886                  On decr_pc_after_break targets, like e.g., x86-linux,
11887                  if we fail to recognize a late breakpoint SIGTRAP,
11888                  because events_till_retirement has reached 0 too
11889                  soon, we'll fail to do the PC adjustment, and report
11890                  a random SIGTRAP to the user.  When the user resumes
11891                  the inferior, it will most likely immediately crash
11892                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
11893                  corrupted, because of being resumed e.g., in the
11894                  middle of a multi-byte instruction, or skipped a
11895                  one-byte instruction.  This was actually seen happen
11896                  on native x86-linux, and should be less rare on
11897                  targets that do not support new thread events, like
11898                  remote, due to the heuristic depending on
11899                  thread_count.
11900
11901                  Mistaking a random SIGTRAP for a breakpoint trap
11902                  causes similar symptoms (PC adjustment applied when
11903                  it shouldn't), but then again, playing with SIGTRAPs
11904                  behind the debugger's back is asking for trouble.
11905
11906                  Since hardware watchpoint traps are always
11907                  distinguishable from other traps, so we don't need to
11908                  apply keep hardware watchpoint moribund locations
11909                  around.  We simply always ignore hardware watchpoint
11910                  traps we can no longer explain.  */
11911
11912               old_loc->events_till_retirement = 3 * (thread_count () + 1);
11913               old_loc->owner = NULL;
11914
11915               moribund_locations.push_back (old_loc);
11916             }
11917           else
11918             {
11919               old_loc->owner = NULL;
11920               decref_bp_location (&old_loc);
11921             }
11922         }
11923     }
11924
11925   /* Rescan breakpoints at the same address and section, marking the
11926      first one as "first" and any others as "duplicates".  This is so
11927      that the bpt instruction is only inserted once.  If we have a
11928      permanent breakpoint at the same place as BPT, make that one the
11929      official one, and the rest as duplicates.  Permanent breakpoints
11930      are sorted first for the same address.
11931
11932      Do the same for hardware watchpoints, but also considering the
11933      watchpoint's type (regular/access/read) and length.  */
11934
11935   bp_loc_first = NULL;
11936   wp_loc_first = NULL;
11937   awp_loc_first = NULL;
11938   rwp_loc_first = NULL;
11939   ALL_BP_LOCATIONS (loc, locp)
11940     {
11941       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
11942          non-NULL.  */
11943       struct bp_location **loc_first_p;
11944       b = loc->owner;
11945
11946       if (!unduplicated_should_be_inserted (loc)
11947           || !breakpoint_address_is_meaningful (b)
11948           /* Don't detect duplicate for tracepoint locations because they are
11949            never duplicated.  See the comments in field `duplicate' of
11950            `struct bp_location'.  */
11951           || is_tracepoint (b))
11952         {
11953           /* Clear the condition modification flag.  */
11954           loc->condition_changed = condition_unchanged;
11955           continue;
11956         }
11957
11958       if (b->type == bp_hardware_watchpoint)
11959         loc_first_p = &wp_loc_first;
11960       else if (b->type == bp_read_watchpoint)
11961         loc_first_p = &rwp_loc_first;
11962       else if (b->type == bp_access_watchpoint)
11963         loc_first_p = &awp_loc_first;
11964       else
11965         loc_first_p = &bp_loc_first;
11966
11967       if (*loc_first_p == NULL
11968           || (overlay_debugging && loc->section != (*loc_first_p)->section)
11969           || !breakpoint_locations_match (loc, *loc_first_p))
11970         {
11971           *loc_first_p = loc;
11972           loc->duplicate = 0;
11973
11974           if (is_breakpoint (loc->owner) && loc->condition_changed)
11975             {
11976               loc->needs_update = 1;
11977               /* Clear the condition modification flag.  */
11978               loc->condition_changed = condition_unchanged;
11979             }
11980           continue;
11981         }
11982
11983
11984       /* This and the above ensure the invariant that the first location
11985          is not duplicated, and is the inserted one.
11986          All following are marked as duplicated, and are not inserted.  */
11987       if (loc->inserted)
11988         swap_insertion (loc, *loc_first_p);
11989       loc->duplicate = 1;
11990
11991       /* Clear the condition modification flag.  */
11992       loc->condition_changed = condition_unchanged;
11993     }
11994
11995   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
11996     {
11997       if (insert_mode != UGLL_DONT_INSERT)
11998         insert_breakpoint_locations ();
11999       else
12000         {
12001           /* Even though the caller told us to not insert new
12002              locations, we may still need to update conditions on the
12003              target's side of breakpoints that were already inserted
12004              if the target is evaluating breakpoint conditions.  We
12005              only update conditions for locations that are marked
12006              "needs_update".  */
12007           update_inserted_breakpoint_locations ();
12008         }
12009     }
12010
12011   if (insert_mode != UGLL_DONT_INSERT)
12012     download_tracepoint_locations ();
12013 }
12014
12015 void
12016 breakpoint_retire_moribund (void)
12017 {
12018   for (int ix = 0; ix < moribund_locations.size (); ++ix)
12019     {
12020       struct bp_location *loc = moribund_locations[ix];
12021       if (--(loc->events_till_retirement) == 0)
12022         {
12023           decref_bp_location (&loc);
12024           unordered_remove (moribund_locations, ix);
12025           --ix;
12026         }
12027     }
12028 }
12029
12030 static void
12031 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12032 {
12033
12034   try
12035     {
12036       update_global_location_list (insert_mode);
12037     }
12038   catch (const gdb_exception_error &e)
12039     {
12040     }
12041 }
12042
12043 /* Clear BKP from a BPS.  */
12044
12045 static void
12046 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12047 {
12048   bpstat bs;
12049
12050   for (bs = bps; bs; bs = bs->next)
12051     if (bs->breakpoint_at == bpt)
12052       {
12053         bs->breakpoint_at = NULL;
12054         bs->old_val = NULL;
12055         /* bs->commands will be freed later.  */
12056       }
12057 }
12058
12059 /* Callback for iterate_over_threads.  */
12060 static int
12061 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12062 {
12063   struct breakpoint *bpt = (struct breakpoint *) data;
12064
12065   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12066   return 0;
12067 }
12068
12069 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12070    callbacks.  */
12071
12072 static void
12073 say_where (struct breakpoint *b)
12074 {
12075   struct value_print_options opts;
12076
12077   get_user_print_options (&opts);
12078
12079   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12080      single string.  */
12081   if (b->loc == NULL)
12082     {
12083       /* For pending locations, the output differs slightly based
12084          on b->extra_string.  If this is non-NULL, it contains either
12085          a condition or dprintf arguments.  */
12086       if (b->extra_string == NULL)
12087         {
12088           printf_filtered (_(" (%s) pending."),
12089                            event_location_to_string (b->location.get ()));
12090         }
12091       else if (b->type == bp_dprintf)
12092         {
12093           printf_filtered (_(" (%s,%s) pending."),
12094                            event_location_to_string (b->location.get ()),
12095                            b->extra_string);
12096         }
12097       else
12098         {
12099           printf_filtered (_(" (%s %s) pending."),
12100                            event_location_to_string (b->location.get ()),
12101                            b->extra_string);
12102         }
12103     }
12104   else
12105     {
12106       if (opts.addressprint || b->loc->symtab == NULL)
12107         {
12108           printf_filtered (" at ");
12109           fputs_styled (paddress (b->loc->gdbarch, b->loc->address),
12110                         address_style.style (),
12111                         gdb_stdout);
12112         }
12113       if (b->loc->symtab != NULL)
12114         {
12115           /* If there is a single location, we can print the location
12116              more nicely.  */
12117           if (b->loc->next == NULL)
12118             {
12119               puts_filtered (": file ");
12120               fputs_styled (symtab_to_filename_for_display (b->loc->symtab),
12121                             file_name_style.style (),
12122                             gdb_stdout);
12123               printf_filtered (", line %d.",
12124                                b->loc->line_number);
12125             }
12126           else
12127             /* This is not ideal, but each location may have a
12128                different file name, and this at least reflects the
12129                real situation somewhat.  */
12130             printf_filtered (": %s.",
12131                              event_location_to_string (b->location.get ()));
12132         }
12133
12134       if (b->loc->next)
12135         {
12136           struct bp_location *loc = b->loc;
12137           int n = 0;
12138           for (; loc; loc = loc->next)
12139             ++n;
12140           printf_filtered (" (%d locations)", n);
12141         }
12142     }
12143 }
12144
12145 bp_location::~bp_location ()
12146 {
12147   xfree (function_name);
12148 }
12149
12150 /* Destructor for the breakpoint base class.  */
12151
12152 breakpoint::~breakpoint ()
12153 {
12154   xfree (this->cond_string);
12155   xfree (this->extra_string);
12156   xfree (this->filter);
12157 }
12158
12159 static struct bp_location *
12160 base_breakpoint_allocate_location (struct breakpoint *self)
12161 {
12162   return new bp_location (self);
12163 }
12164
12165 static void
12166 base_breakpoint_re_set (struct breakpoint *b)
12167 {
12168   /* Nothing to re-set. */
12169 }
12170
12171 #define internal_error_pure_virtual_called() \
12172   gdb_assert_not_reached ("pure virtual function called")
12173
12174 static int
12175 base_breakpoint_insert_location (struct bp_location *bl)
12176 {
12177   internal_error_pure_virtual_called ();
12178 }
12179
12180 static int
12181 base_breakpoint_remove_location (struct bp_location *bl,
12182                                  enum remove_bp_reason reason)
12183 {
12184   internal_error_pure_virtual_called ();
12185 }
12186
12187 static int
12188 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12189                                 const address_space *aspace,
12190                                 CORE_ADDR bp_addr,
12191                                 const struct target_waitstatus *ws)
12192 {
12193   internal_error_pure_virtual_called ();
12194 }
12195
12196 static void
12197 base_breakpoint_check_status (bpstat bs)
12198 {
12199   /* Always stop.   */
12200 }
12201
12202 /* A "works_in_software_mode" breakpoint_ops method that just internal
12203    errors.  */
12204
12205 static int
12206 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12207 {
12208   internal_error_pure_virtual_called ();
12209 }
12210
12211 /* A "resources_needed" breakpoint_ops method that just internal
12212    errors.  */
12213
12214 static int
12215 base_breakpoint_resources_needed (const struct bp_location *bl)
12216 {
12217   internal_error_pure_virtual_called ();
12218 }
12219
12220 static enum print_stop_action
12221 base_breakpoint_print_it (bpstat bs)
12222 {
12223   internal_error_pure_virtual_called ();
12224 }
12225
12226 static void
12227 base_breakpoint_print_one_detail (const struct breakpoint *self,
12228                                   struct ui_out *uiout)
12229 {
12230   /* nothing */
12231 }
12232
12233 static void
12234 base_breakpoint_print_mention (struct breakpoint *b)
12235 {
12236   internal_error_pure_virtual_called ();
12237 }
12238
12239 static void
12240 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12241 {
12242   internal_error_pure_virtual_called ();
12243 }
12244
12245 static void
12246 base_breakpoint_create_sals_from_location
12247   (const struct event_location *location,
12248    struct linespec_result *canonical,
12249    enum bptype type_wanted)
12250 {
12251   internal_error_pure_virtual_called ();
12252 }
12253
12254 static void
12255 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12256                                         struct linespec_result *c,
12257                                         gdb::unique_xmalloc_ptr<char> cond_string,
12258                                         gdb::unique_xmalloc_ptr<char> extra_string,
12259                                         enum bptype type_wanted,
12260                                         enum bpdisp disposition,
12261                                         int thread,
12262                                         int task, int ignore_count,
12263                                         const struct breakpoint_ops *o,
12264                                         int from_tty, int enabled,
12265                                         int internal, unsigned flags)
12266 {
12267   internal_error_pure_virtual_called ();
12268 }
12269
12270 static std::vector<symtab_and_line>
12271 base_breakpoint_decode_location (struct breakpoint *b,
12272                                  const struct event_location *location,
12273                                  struct program_space *search_pspace)
12274 {
12275   internal_error_pure_virtual_called ();
12276 }
12277
12278 /* The default 'explains_signal' method.  */
12279
12280 static int
12281 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12282 {
12283   return 1;
12284 }
12285
12286 /* The default "after_condition_true" method.  */
12287
12288 static void
12289 base_breakpoint_after_condition_true (struct bpstats *bs)
12290 {
12291   /* Nothing to do.   */
12292 }
12293
12294 struct breakpoint_ops base_breakpoint_ops =
12295 {
12296   base_breakpoint_allocate_location,
12297   base_breakpoint_re_set,
12298   base_breakpoint_insert_location,
12299   base_breakpoint_remove_location,
12300   base_breakpoint_breakpoint_hit,
12301   base_breakpoint_check_status,
12302   base_breakpoint_resources_needed,
12303   base_breakpoint_works_in_software_mode,
12304   base_breakpoint_print_it,
12305   NULL,
12306   base_breakpoint_print_one_detail,
12307   base_breakpoint_print_mention,
12308   base_breakpoint_print_recreate,
12309   base_breakpoint_create_sals_from_location,
12310   base_breakpoint_create_breakpoints_sal,
12311   base_breakpoint_decode_location,
12312   base_breakpoint_explains_signal,
12313   base_breakpoint_after_condition_true,
12314 };
12315
12316 /* Default breakpoint_ops methods.  */
12317
12318 static void
12319 bkpt_re_set (struct breakpoint *b)
12320 {
12321   /* FIXME: is this still reachable?  */
12322   if (breakpoint_event_location_empty_p (b))
12323     {
12324       /* Anything without a location can't be re-set.  */
12325       delete_breakpoint (b);
12326       return;
12327     }
12328
12329   breakpoint_re_set_default (b);
12330 }
12331
12332 static int
12333 bkpt_insert_location (struct bp_location *bl)
12334 {
12335   CORE_ADDR addr = bl->target_info.reqstd_address;
12336
12337   bl->target_info.kind = breakpoint_kind (bl, &addr);
12338   bl->target_info.placed_address = addr;
12339
12340   if (bl->loc_type == bp_loc_hardware_breakpoint)
12341     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12342   else
12343     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12344 }
12345
12346 static int
12347 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
12348 {
12349   if (bl->loc_type == bp_loc_hardware_breakpoint)
12350     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12351   else
12352     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12353 }
12354
12355 static int
12356 bkpt_breakpoint_hit (const struct bp_location *bl,
12357                      const address_space *aspace, CORE_ADDR bp_addr,
12358                      const struct target_waitstatus *ws)
12359 {
12360   if (ws->kind != TARGET_WAITKIND_STOPPED
12361       || ws->value.sig != GDB_SIGNAL_TRAP)
12362     return 0;
12363
12364   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12365                                  aspace, bp_addr))
12366     return 0;
12367
12368   if (overlay_debugging         /* unmapped overlay section */
12369       && section_is_overlay (bl->section)
12370       && !section_is_mapped (bl->section))
12371     return 0;
12372
12373   return 1;
12374 }
12375
12376 static int
12377 dprintf_breakpoint_hit (const struct bp_location *bl,
12378                         const address_space *aspace, CORE_ADDR bp_addr,
12379                         const struct target_waitstatus *ws)
12380 {
12381   if (dprintf_style == dprintf_style_agent
12382       && target_can_run_breakpoint_commands ())
12383     {
12384       /* An agent-style dprintf never causes a stop.  If we see a trap
12385          for this address it must be for a breakpoint that happens to
12386          be set at the same address.  */
12387       return 0;
12388     }
12389
12390   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12391 }
12392
12393 static int
12394 bkpt_resources_needed (const struct bp_location *bl)
12395 {
12396   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12397
12398   return 1;
12399 }
12400
12401 static enum print_stop_action
12402 bkpt_print_it (bpstat bs)
12403 {
12404   struct breakpoint *b;
12405   const struct bp_location *bl;
12406   int bp_temp;
12407   struct ui_out *uiout = current_uiout;
12408
12409   gdb_assert (bs->bp_location_at != NULL);
12410
12411   bl = bs->bp_location_at;
12412   b = bs->breakpoint_at;
12413
12414   bp_temp = b->disposition == disp_del;
12415   if (bl->address != bl->requested_address)
12416     breakpoint_adjustment_warning (bl->requested_address,
12417                                    bl->address,
12418                                    b->number, 1);
12419   annotate_breakpoint (b->number);
12420   maybe_print_thread_hit_breakpoint (uiout);
12421
12422   if (bp_temp)
12423     uiout->text ("Temporary breakpoint ");
12424   else
12425     uiout->text ("Breakpoint ");
12426   if (uiout->is_mi_like_p ())
12427     {
12428       uiout->field_string ("reason",
12429                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12430       uiout->field_string ("disp", bpdisp_text (b->disposition));
12431     }
12432   uiout->field_int ("bkptno", b->number);
12433   uiout->text (", ");
12434
12435   return PRINT_SRC_AND_LOC;
12436 }
12437
12438 static void
12439 bkpt_print_mention (struct breakpoint *b)
12440 {
12441   if (current_uiout->is_mi_like_p ())
12442     return;
12443
12444   switch (b->type)
12445     {
12446     case bp_breakpoint:
12447     case bp_gnu_ifunc_resolver:
12448       if (b->disposition == disp_del)
12449         printf_filtered (_("Temporary breakpoint"));
12450       else
12451         printf_filtered (_("Breakpoint"));
12452       printf_filtered (_(" %d"), b->number);
12453       if (b->type == bp_gnu_ifunc_resolver)
12454         printf_filtered (_(" at gnu-indirect-function resolver"));
12455       break;
12456     case bp_hardware_breakpoint:
12457       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12458       break;
12459     case bp_dprintf:
12460       printf_filtered (_("Dprintf %d"), b->number);
12461       break;
12462     }
12463
12464   say_where (b);
12465 }
12466
12467 static void
12468 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12469 {
12470   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12471     fprintf_unfiltered (fp, "tbreak");
12472   else if (tp->type == bp_breakpoint)
12473     fprintf_unfiltered (fp, "break");
12474   else if (tp->type == bp_hardware_breakpoint
12475            && tp->disposition == disp_del)
12476     fprintf_unfiltered (fp, "thbreak");
12477   else if (tp->type == bp_hardware_breakpoint)
12478     fprintf_unfiltered (fp, "hbreak");
12479   else
12480     internal_error (__FILE__, __LINE__,
12481                     _("unhandled breakpoint type %d"), (int) tp->type);
12482
12483   fprintf_unfiltered (fp, " %s",
12484                       event_location_to_string (tp->location.get ()));
12485
12486   /* Print out extra_string if this breakpoint is pending.  It might
12487      contain, for example, conditions that were set by the user.  */
12488   if (tp->loc == NULL && tp->extra_string != NULL)
12489     fprintf_unfiltered (fp, " %s", tp->extra_string);
12490
12491   print_recreate_thread (tp, fp);
12492 }
12493
12494 static void
12495 bkpt_create_sals_from_location (const struct event_location *location,
12496                                 struct linespec_result *canonical,
12497                                 enum bptype type_wanted)
12498 {
12499   create_sals_from_location_default (location, canonical, type_wanted);
12500 }
12501
12502 static void
12503 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12504                              struct linespec_result *canonical,
12505                              gdb::unique_xmalloc_ptr<char> cond_string,
12506                              gdb::unique_xmalloc_ptr<char> extra_string,
12507                              enum bptype type_wanted,
12508                              enum bpdisp disposition,
12509                              int thread,
12510                              int task, int ignore_count,
12511                              const struct breakpoint_ops *ops,
12512                              int from_tty, int enabled,
12513                              int internal, unsigned flags)
12514 {
12515   create_breakpoints_sal_default (gdbarch, canonical,
12516                                   std::move (cond_string),
12517                                   std::move (extra_string),
12518                                   type_wanted,
12519                                   disposition, thread, task,
12520                                   ignore_count, ops, from_tty,
12521                                   enabled, internal, flags);
12522 }
12523
12524 static std::vector<symtab_and_line>
12525 bkpt_decode_location (struct breakpoint *b,
12526                       const struct event_location *location,
12527                       struct program_space *search_pspace)
12528 {
12529   return decode_location_default (b, location, search_pspace);
12530 }
12531
12532 /* Virtual table for internal breakpoints.  */
12533
12534 static void
12535 internal_bkpt_re_set (struct breakpoint *b)
12536 {
12537   switch (b->type)
12538     {
12539       /* Delete overlay event and longjmp master breakpoints; they
12540          will be reset later by breakpoint_re_set.  */
12541     case bp_overlay_event:
12542     case bp_longjmp_master:
12543     case bp_std_terminate_master:
12544     case bp_exception_master:
12545       delete_breakpoint (b);
12546       break;
12547
12548       /* This breakpoint is special, it's set up when the inferior
12549          starts and we really don't want to touch it.  */
12550     case bp_shlib_event:
12551
12552       /* Like bp_shlib_event, this breakpoint type is special.  Once
12553          it is set up, we do not want to touch it.  */
12554     case bp_thread_event:
12555       break;
12556     }
12557 }
12558
12559 static void
12560 internal_bkpt_check_status (bpstat bs)
12561 {
12562   if (bs->breakpoint_at->type == bp_shlib_event)
12563     {
12564       /* If requested, stop when the dynamic linker notifies GDB of
12565          events.  This allows the user to get control and place
12566          breakpoints in initializer routines for dynamically loaded
12567          objects (among other things).  */
12568       bs->stop = stop_on_solib_events;
12569       bs->print = stop_on_solib_events;
12570     }
12571   else
12572     bs->stop = 0;
12573 }
12574
12575 static enum print_stop_action
12576 internal_bkpt_print_it (bpstat bs)
12577 {
12578   struct breakpoint *b;
12579
12580   b = bs->breakpoint_at;
12581
12582   switch (b->type)
12583     {
12584     case bp_shlib_event:
12585       /* Did we stop because the user set the stop_on_solib_events
12586          variable?  (If so, we report this as a generic, "Stopped due
12587          to shlib event" message.) */
12588       print_solib_event (0);
12589       break;
12590
12591     case bp_thread_event:
12592       /* Not sure how we will get here.
12593          GDB should not stop for these breakpoints.  */
12594       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12595       break;
12596
12597     case bp_overlay_event:
12598       /* By analogy with the thread event, GDB should not stop for these.  */
12599       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12600       break;
12601
12602     case bp_longjmp_master:
12603       /* These should never be enabled.  */
12604       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12605       break;
12606
12607     case bp_std_terminate_master:
12608       /* These should never be enabled.  */
12609       printf_filtered (_("std::terminate Master Breakpoint: "
12610                          "gdb should not stop!\n"));
12611       break;
12612
12613     case bp_exception_master:
12614       /* These should never be enabled.  */
12615       printf_filtered (_("Exception Master Breakpoint: "
12616                          "gdb should not stop!\n"));
12617       break;
12618     }
12619
12620   return PRINT_NOTHING;
12621 }
12622
12623 static void
12624 internal_bkpt_print_mention (struct breakpoint *b)
12625 {
12626   /* Nothing to mention.  These breakpoints are internal.  */
12627 }
12628
12629 /* Virtual table for momentary breakpoints  */
12630
12631 static void
12632 momentary_bkpt_re_set (struct breakpoint *b)
12633 {
12634   /* Keep temporary breakpoints, which can be encountered when we step
12635      over a dlopen call and solib_add is resetting the breakpoints.
12636      Otherwise these should have been blown away via the cleanup chain
12637      or by breakpoint_init_inferior when we rerun the executable.  */
12638 }
12639
12640 static void
12641 momentary_bkpt_check_status (bpstat bs)
12642 {
12643   /* Nothing.  The point of these breakpoints is causing a stop.  */
12644 }
12645
12646 static enum print_stop_action
12647 momentary_bkpt_print_it (bpstat bs)
12648 {
12649   return PRINT_UNKNOWN;
12650 }
12651
12652 static void
12653 momentary_bkpt_print_mention (struct breakpoint *b)
12654 {
12655   /* Nothing to mention.  These breakpoints are internal.  */
12656 }
12657
12658 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12659
12660    It gets cleared already on the removal of the first one of such placed
12661    breakpoints.  This is OK as they get all removed altogether.  */
12662
12663 longjmp_breakpoint::~longjmp_breakpoint ()
12664 {
12665   thread_info *tp = find_thread_global_id (this->thread);
12666
12667   if (tp != NULL)
12668     tp->initiating_frame = null_frame_id;
12669 }
12670
12671 /* Specific methods for probe breakpoints.  */
12672
12673 static int
12674 bkpt_probe_insert_location (struct bp_location *bl)
12675 {
12676   int v = bkpt_insert_location (bl);
12677
12678   if (v == 0)
12679     {
12680       /* The insertion was successful, now let's set the probe's semaphore
12681          if needed.  */
12682       bl->probe.prob->set_semaphore (bl->probe.objfile, bl->gdbarch);
12683     }
12684
12685   return v;
12686 }
12687
12688 static int
12689 bkpt_probe_remove_location (struct bp_location *bl,
12690                             enum remove_bp_reason reason)
12691 {
12692   /* Let's clear the semaphore before removing the location.  */
12693   bl->probe.prob->clear_semaphore (bl->probe.objfile, bl->gdbarch);
12694
12695   return bkpt_remove_location (bl, reason);
12696 }
12697
12698 static void
12699 bkpt_probe_create_sals_from_location (const struct event_location *location,
12700                                       struct linespec_result *canonical,
12701                                       enum bptype type_wanted)
12702 {
12703   struct linespec_sals lsal;
12704
12705   lsal.sals = parse_probes (location, NULL, canonical);
12706   lsal.canonical
12707     = xstrdup (event_location_to_string (canonical->location.get ()));
12708   canonical->lsals.push_back (std::move (lsal));
12709 }
12710
12711 static std::vector<symtab_and_line>
12712 bkpt_probe_decode_location (struct breakpoint *b,
12713                             const struct event_location *location,
12714                             struct program_space *search_pspace)
12715 {
12716   std::vector<symtab_and_line> sals = parse_probes (location, search_pspace, NULL);
12717   if (sals.empty ())
12718     error (_("probe not found"));
12719   return sals;
12720 }
12721
12722 /* The breakpoint_ops structure to be used in tracepoints.  */
12723
12724 static void
12725 tracepoint_re_set (struct breakpoint *b)
12726 {
12727   breakpoint_re_set_default (b);
12728 }
12729
12730 static int
12731 tracepoint_breakpoint_hit (const struct bp_location *bl,
12732                            const address_space *aspace, CORE_ADDR bp_addr,
12733                            const struct target_waitstatus *ws)
12734 {
12735   /* By definition, the inferior does not report stops at
12736      tracepoints.  */
12737   return 0;
12738 }
12739
12740 static void
12741 tracepoint_print_one_detail (const struct breakpoint *self,
12742                              struct ui_out *uiout)
12743 {
12744   struct tracepoint *tp = (struct tracepoint *) self;
12745   if (!tp->static_trace_marker_id.empty ())
12746     {
12747       gdb_assert (self->type == bp_static_tracepoint);
12748
12749       uiout->text ("\tmarker id is ");
12750       uiout->field_string ("static-tracepoint-marker-string-id",
12751                            tp->static_trace_marker_id);
12752       uiout->text ("\n");
12753     }
12754 }
12755
12756 static void
12757 tracepoint_print_mention (struct breakpoint *b)
12758 {
12759   if (current_uiout->is_mi_like_p ())
12760     return;
12761
12762   switch (b->type)
12763     {
12764     case bp_tracepoint:
12765       printf_filtered (_("Tracepoint"));
12766       printf_filtered (_(" %d"), b->number);
12767       break;
12768     case bp_fast_tracepoint:
12769       printf_filtered (_("Fast tracepoint"));
12770       printf_filtered (_(" %d"), b->number);
12771       break;
12772     case bp_static_tracepoint:
12773       printf_filtered (_("Static tracepoint"));
12774       printf_filtered (_(" %d"), b->number);
12775       break;
12776     default:
12777       internal_error (__FILE__, __LINE__,
12778                       _("unhandled tracepoint type %d"), (int) b->type);
12779     }
12780
12781   say_where (b);
12782 }
12783
12784 static void
12785 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
12786 {
12787   struct tracepoint *tp = (struct tracepoint *) self;
12788
12789   if (self->type == bp_fast_tracepoint)
12790     fprintf_unfiltered (fp, "ftrace");
12791   else if (self->type == bp_static_tracepoint)
12792     fprintf_unfiltered (fp, "strace");
12793   else if (self->type == bp_tracepoint)
12794     fprintf_unfiltered (fp, "trace");
12795   else
12796     internal_error (__FILE__, __LINE__,
12797                     _("unhandled tracepoint type %d"), (int) self->type);
12798
12799   fprintf_unfiltered (fp, " %s",
12800                       event_location_to_string (self->location.get ()));
12801   print_recreate_thread (self, fp);
12802
12803   if (tp->pass_count)
12804     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
12805 }
12806
12807 static void
12808 tracepoint_create_sals_from_location (const struct event_location *location,
12809                                       struct linespec_result *canonical,
12810                                       enum bptype type_wanted)
12811 {
12812   create_sals_from_location_default (location, canonical, type_wanted);
12813 }
12814
12815 static void
12816 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12817                                    struct linespec_result *canonical,
12818                                    gdb::unique_xmalloc_ptr<char> cond_string,
12819                                    gdb::unique_xmalloc_ptr<char> extra_string,
12820                                    enum bptype type_wanted,
12821                                    enum bpdisp disposition,
12822                                    int thread,
12823                                    int task, int ignore_count,
12824                                    const struct breakpoint_ops *ops,
12825                                    int from_tty, int enabled,
12826                                    int internal, unsigned flags)
12827 {
12828   create_breakpoints_sal_default (gdbarch, canonical,
12829                                   std::move (cond_string),
12830                                   std::move (extra_string),
12831                                   type_wanted,
12832                                   disposition, thread, task,
12833                                   ignore_count, ops, from_tty,
12834                                   enabled, internal, flags);
12835 }
12836
12837 static std::vector<symtab_and_line>
12838 tracepoint_decode_location (struct breakpoint *b,
12839                             const struct event_location *location,
12840                             struct program_space *search_pspace)
12841 {
12842   return decode_location_default (b, location, search_pspace);
12843 }
12844
12845 struct breakpoint_ops tracepoint_breakpoint_ops;
12846
12847 /* The breakpoint_ops structure to be use on tracepoints placed in a
12848    static probe.  */
12849
12850 static void
12851 tracepoint_probe_create_sals_from_location
12852   (const struct event_location *location,
12853    struct linespec_result *canonical,
12854    enum bptype type_wanted)
12855 {
12856   /* We use the same method for breakpoint on probes.  */
12857   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
12858 }
12859
12860 static std::vector<symtab_and_line>
12861 tracepoint_probe_decode_location (struct breakpoint *b,
12862                                   const struct event_location *location,
12863                                   struct program_space *search_pspace)
12864 {
12865   /* We use the same method for breakpoint on probes.  */
12866   return bkpt_probe_decode_location (b, location, search_pspace);
12867 }
12868
12869 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
12870
12871 /* Dprintf breakpoint_ops methods.  */
12872
12873 static void
12874 dprintf_re_set (struct breakpoint *b)
12875 {
12876   breakpoint_re_set_default (b);
12877
12878   /* extra_string should never be non-NULL for dprintf.  */
12879   gdb_assert (b->extra_string != NULL);
12880
12881   /* 1 - connect to target 1, that can run breakpoint commands.
12882      2 - create a dprintf, which resolves fine.
12883      3 - disconnect from target 1
12884      4 - connect to target 2, that can NOT run breakpoint commands.
12885
12886      After steps #3/#4, you'll want the dprintf command list to
12887      be updated, because target 1 and 2 may well return different
12888      answers for target_can_run_breakpoint_commands().
12889      Given absence of finer grained resetting, we get to do
12890      it all the time.  */
12891   if (b->extra_string != NULL)
12892     update_dprintf_command_list (b);
12893 }
12894
12895 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
12896
12897 static void
12898 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12899 {
12900   fprintf_unfiltered (fp, "dprintf %s,%s",
12901                       event_location_to_string (tp->location.get ()),
12902                       tp->extra_string);
12903   print_recreate_thread (tp, fp);
12904 }
12905
12906 /* Implement the "after_condition_true" breakpoint_ops method for
12907    dprintf.
12908
12909    dprintf's are implemented with regular commands in their command
12910    list, but we run the commands here instead of before presenting the
12911    stop to the user, as dprintf's don't actually cause a stop.  This
12912    also makes it so that the commands of multiple dprintfs at the same
12913    address are all handled.  */
12914
12915 static void
12916 dprintf_after_condition_true (struct bpstats *bs)
12917 {
12918   struct bpstats tmp_bs;
12919   struct bpstats *tmp_bs_p = &tmp_bs;
12920
12921   /* dprintf's never cause a stop.  This wasn't set in the
12922      check_status hook instead because that would make the dprintf's
12923      condition not be evaluated.  */
12924   bs->stop = 0;
12925
12926   /* Run the command list here.  Take ownership of it instead of
12927      copying.  We never want these commands to run later in
12928      bpstat_do_actions, if a breakpoint that causes a stop happens to
12929      be set at same address as this dprintf, or even if running the
12930      commands here throws.  */
12931   tmp_bs.commands = bs->commands;
12932   bs->commands = NULL;
12933
12934   bpstat_do_actions_1 (&tmp_bs_p);
12935
12936   /* 'tmp_bs.commands' will usually be NULL by now, but
12937      bpstat_do_actions_1 may return early without processing the whole
12938      list.  */
12939 }
12940
12941 /* The breakpoint_ops structure to be used on static tracepoints with
12942    markers (`-m').  */
12943
12944 static void
12945 strace_marker_create_sals_from_location (const struct event_location *location,
12946                                          struct linespec_result *canonical,
12947                                          enum bptype type_wanted)
12948 {
12949   struct linespec_sals lsal;
12950   const char *arg_start, *arg;
12951
12952   arg = arg_start = get_linespec_location (location)->spec_string;
12953   lsal.sals = decode_static_tracepoint_spec (&arg);
12954
12955   std::string str (arg_start, arg - arg_start);
12956   const char *ptr = str.c_str ();
12957   canonical->location
12958     = new_linespec_location (&ptr, symbol_name_match_type::FULL);
12959
12960   lsal.canonical
12961     = xstrdup (event_location_to_string (canonical->location.get ()));
12962   canonical->lsals.push_back (std::move (lsal));
12963 }
12964
12965 static void
12966 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
12967                                       struct linespec_result *canonical,
12968                                       gdb::unique_xmalloc_ptr<char> cond_string,
12969                                       gdb::unique_xmalloc_ptr<char> extra_string,
12970                                       enum bptype type_wanted,
12971                                       enum bpdisp disposition,
12972                                       int thread,
12973                                       int task, int ignore_count,
12974                                       const struct breakpoint_ops *ops,
12975                                       int from_tty, int enabled,
12976                                       int internal, unsigned flags)
12977 {
12978   const linespec_sals &lsal = canonical->lsals[0];
12979
12980   /* If the user is creating a static tracepoint by marker id
12981      (strace -m MARKER_ID), then store the sals index, so that
12982      breakpoint_re_set can try to match up which of the newly
12983      found markers corresponds to this one, and, don't try to
12984      expand multiple locations for each sal, given than SALS
12985      already should contain all sals for MARKER_ID.  */
12986
12987   for (size_t i = 0; i < lsal.sals.size (); i++)
12988     {
12989       event_location_up location
12990         = copy_event_location (canonical->location.get ());
12991
12992       std::unique_ptr<tracepoint> tp (new tracepoint ());
12993       init_breakpoint_sal (tp.get (), gdbarch, lsal.sals[i],
12994                            std::move (location), NULL,
12995                            std::move (cond_string),
12996                            std::move (extra_string),
12997                            type_wanted, disposition,
12998                            thread, task, ignore_count, ops,
12999                            from_tty, enabled, internal, flags,
13000                            canonical->special_display);
13001       /* Given that its possible to have multiple markers with
13002          the same string id, if the user is creating a static
13003          tracepoint by marker id ("strace -m MARKER_ID"), then
13004          store the sals index, so that breakpoint_re_set can
13005          try to match up which of the newly found markers
13006          corresponds to this one  */
13007       tp->static_trace_marker_id_idx = i;
13008
13009       install_breakpoint (internal, std::move (tp), 0);
13010     }
13011 }
13012
13013 static std::vector<symtab_and_line>
13014 strace_marker_decode_location (struct breakpoint *b,
13015                                const struct event_location *location,
13016                                struct program_space *search_pspace)
13017 {
13018   struct tracepoint *tp = (struct tracepoint *) b;
13019   const char *s = get_linespec_location (location)->spec_string;
13020
13021   std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
13022   if (sals.size () > tp->static_trace_marker_id_idx)
13023     {
13024       sals[0] = sals[tp->static_trace_marker_id_idx];
13025       sals.resize (1);
13026       return sals;
13027     }
13028   else
13029     error (_("marker %s not found"), tp->static_trace_marker_id.c_str ());
13030 }
13031
13032 static struct breakpoint_ops strace_marker_breakpoint_ops;
13033
13034 static int
13035 strace_marker_p (struct breakpoint *b)
13036 {
13037   return b->ops == &strace_marker_breakpoint_ops;
13038 }
13039
13040 /* Delete a breakpoint and clean up all traces of it in the data
13041    structures.  */
13042
13043 void
13044 delete_breakpoint (struct breakpoint *bpt)
13045 {
13046   struct breakpoint *b;
13047
13048   gdb_assert (bpt != NULL);
13049
13050   /* Has this bp already been deleted?  This can happen because
13051      multiple lists can hold pointers to bp's.  bpstat lists are
13052      especial culprits.
13053
13054      One example of this happening is a watchpoint's scope bp.  When
13055      the scope bp triggers, we notice that the watchpoint is out of
13056      scope, and delete it.  We also delete its scope bp.  But the
13057      scope bp is marked "auto-deleting", and is already on a bpstat.
13058      That bpstat is then checked for auto-deleting bp's, which are
13059      deleted.
13060
13061      A real solution to this problem might involve reference counts in
13062      bp's, and/or giving them pointers back to their referencing
13063      bpstat's, and teaching delete_breakpoint to only free a bp's
13064      storage when no more references were extent.  A cheaper bandaid
13065      was chosen.  */
13066   if (bpt->type == bp_none)
13067     return;
13068
13069   /* At least avoid this stale reference until the reference counting
13070      of breakpoints gets resolved.  */
13071   if (bpt->related_breakpoint != bpt)
13072     {
13073       struct breakpoint *related;
13074       struct watchpoint *w;
13075
13076       if (bpt->type == bp_watchpoint_scope)
13077         w = (struct watchpoint *) bpt->related_breakpoint;
13078       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13079         w = (struct watchpoint *) bpt;
13080       else
13081         w = NULL;
13082       if (w != NULL)
13083         watchpoint_del_at_next_stop (w);
13084
13085       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13086       for (related = bpt; related->related_breakpoint != bpt;
13087            related = related->related_breakpoint);
13088       related->related_breakpoint = bpt->related_breakpoint;
13089       bpt->related_breakpoint = bpt;
13090     }
13091
13092   /* watch_command_1 creates a watchpoint but only sets its number if
13093      update_watchpoint succeeds in creating its bp_locations.  If there's
13094      a problem in that process, we'll be asked to delete the half-created
13095      watchpoint.  In that case, don't announce the deletion.  */
13096   if (bpt->number)
13097     gdb::observers::breakpoint_deleted.notify (bpt);
13098
13099   if (breakpoint_chain == bpt)
13100     breakpoint_chain = bpt->next;
13101
13102   ALL_BREAKPOINTS (b)
13103     if (b->next == bpt)
13104     {
13105       b->next = bpt->next;
13106       break;
13107     }
13108
13109   /* Be sure no bpstat's are pointing at the breakpoint after it's
13110      been freed.  */
13111   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13112      in all threads for now.  Note that we cannot just remove bpstats
13113      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13114      commands are associated with the bpstat; if we remove it here,
13115      then the later call to bpstat_do_actions (&stop_bpstat); in
13116      event-top.c won't do anything, and temporary breakpoints with
13117      commands won't work.  */
13118
13119   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13120
13121   /* Now that breakpoint is removed from breakpoint list, update the
13122      global location list.  This will remove locations that used to
13123      belong to this breakpoint.  Do this before freeing the breakpoint
13124      itself, since remove_breakpoint looks at location's owner.  It
13125      might be better design to have location completely
13126      self-contained, but it's not the case now.  */
13127   update_global_location_list (UGLL_DONT_INSERT);
13128
13129   /* On the chance that someone will soon try again to delete this
13130      same bp, we mark it as deleted before freeing its storage.  */
13131   bpt->type = bp_none;
13132   delete bpt;
13133 }
13134
13135 /* Iterator function to call a user-provided callback function once
13136    for each of B and its related breakpoints.  */
13137
13138 static void
13139 iterate_over_related_breakpoints (struct breakpoint *b,
13140                                   gdb::function_view<void (breakpoint *)> function)
13141 {
13142   struct breakpoint *related;
13143
13144   related = b;
13145   do
13146     {
13147       struct breakpoint *next;
13148
13149       /* FUNCTION may delete RELATED.  */
13150       next = related->related_breakpoint;
13151
13152       if (next == related)
13153         {
13154           /* RELATED is the last ring entry.  */
13155           function (related);
13156
13157           /* FUNCTION may have deleted it, so we'd never reach back to
13158              B.  There's nothing left to do anyway, so just break
13159              out.  */
13160           break;
13161         }
13162       else
13163         function (related);
13164
13165       related = next;
13166     }
13167   while (related != b);
13168 }
13169
13170 static void
13171 delete_command (const char *arg, int from_tty)
13172 {
13173   struct breakpoint *b, *b_tmp;
13174
13175   dont_repeat ();
13176
13177   if (arg == 0)
13178     {
13179       int breaks_to_delete = 0;
13180
13181       /* Delete all breakpoints if no argument.  Do not delete
13182          internal breakpoints, these have to be deleted with an
13183          explicit breakpoint number argument.  */
13184       ALL_BREAKPOINTS (b)
13185         if (user_breakpoint_p (b))
13186           {
13187             breaks_to_delete = 1;
13188             break;
13189           }
13190
13191       /* Ask user only if there are some breakpoints to delete.  */
13192       if (!from_tty
13193           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13194         {
13195           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13196             if (user_breakpoint_p (b))
13197               delete_breakpoint (b);
13198         }
13199     }
13200   else
13201     map_breakpoint_numbers
13202       (arg, [&] (breakpoint *br)
13203        {
13204          iterate_over_related_breakpoints (br, delete_breakpoint);
13205        });
13206 }
13207
13208 /* Return true if all locations of B bound to PSPACE are pending.  If
13209    PSPACE is NULL, all locations of all program spaces are
13210    considered.  */
13211
13212 static int
13213 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13214 {
13215   struct bp_location *loc;
13216
13217   for (loc = b->loc; loc != NULL; loc = loc->next)
13218     if ((pspace == NULL
13219          || loc->pspace == pspace)
13220         && !loc->shlib_disabled
13221         && !loc->pspace->executing_startup)
13222       return 0;
13223   return 1;
13224 }
13225
13226 /* Subroutine of update_breakpoint_locations to simplify it.
13227    Return non-zero if multiple fns in list LOC have the same name.
13228    Null names are ignored.  */
13229
13230 static int
13231 ambiguous_names_p (struct bp_location *loc)
13232 {
13233   struct bp_location *l;
13234   htab_t htab = htab_create_alloc (13, htab_hash_string, streq_hash, NULL,
13235                                    xcalloc, xfree);
13236
13237   for (l = loc; l != NULL; l = l->next)
13238     {
13239       const char **slot;
13240       const char *name = l->function_name;
13241
13242       /* Allow for some names to be NULL, ignore them.  */
13243       if (name == NULL)
13244         continue;
13245
13246       slot = (const char **) htab_find_slot (htab, (const void *) name,
13247                                              INSERT);
13248       /* NOTE: We can assume slot != NULL here because xcalloc never
13249          returns NULL.  */
13250       if (*slot != NULL)
13251         {
13252           htab_delete (htab);
13253           return 1;
13254         }
13255       *slot = name;
13256     }
13257
13258   htab_delete (htab);
13259   return 0;
13260 }
13261
13262 /* When symbols change, it probably means the sources changed as well,
13263    and it might mean the static tracepoint markers are no longer at
13264    the same address or line numbers they used to be at last we
13265    checked.  Losing your static tracepoints whenever you rebuild is
13266    undesirable.  This function tries to resync/rematch gdb static
13267    tracepoints with the markers on the target, for static tracepoints
13268    that have not been set by marker id.  Static tracepoint that have
13269    been set by marker id are reset by marker id in breakpoint_re_set.
13270    The heuristic is:
13271
13272    1) For a tracepoint set at a specific address, look for a marker at
13273    the old PC.  If one is found there, assume to be the same marker.
13274    If the name / string id of the marker found is different from the
13275    previous known name, assume that means the user renamed the marker
13276    in the sources, and output a warning.
13277
13278    2) For a tracepoint set at a given line number, look for a marker
13279    at the new address of the old line number.  If one is found there,
13280    assume to be the same marker.  If the name / string id of the
13281    marker found is different from the previous known name, assume that
13282    means the user renamed the marker in the sources, and output a
13283    warning.
13284
13285    3) If a marker is no longer found at the same address or line, it
13286    may mean the marker no longer exists.  But it may also just mean
13287    the code changed a bit.  Maybe the user added a few lines of code
13288    that made the marker move up or down (in line number terms).  Ask
13289    the target for info about the marker with the string id as we knew
13290    it.  If found, update line number and address in the matching
13291    static tracepoint.  This will get confused if there's more than one
13292    marker with the same ID (possible in UST, although unadvised
13293    precisely because it confuses tools).  */
13294
13295 static struct symtab_and_line
13296 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13297 {
13298   struct tracepoint *tp = (struct tracepoint *) b;
13299   struct static_tracepoint_marker marker;
13300   CORE_ADDR pc;
13301
13302   pc = sal.pc;
13303   if (sal.line)
13304     find_line_pc (sal.symtab, sal.line, &pc);
13305
13306   if (target_static_tracepoint_marker_at (pc, &marker))
13307     {
13308       if (tp->static_trace_marker_id != marker.str_id)
13309         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13310                  b->number, tp->static_trace_marker_id.c_str (),
13311                  marker.str_id.c_str ());
13312
13313       tp->static_trace_marker_id = std::move (marker.str_id);
13314
13315       return sal;
13316     }
13317
13318   /* Old marker wasn't found on target at lineno.  Try looking it up
13319      by string ID.  */
13320   if (!sal.explicit_pc
13321       && sal.line != 0
13322       && sal.symtab != NULL
13323       && !tp->static_trace_marker_id.empty ())
13324     {
13325       std::vector<static_tracepoint_marker> markers
13326         = target_static_tracepoint_markers_by_strid
13327             (tp->static_trace_marker_id.c_str ());
13328
13329       if (!markers.empty ())
13330         {
13331           struct symbol *sym;
13332           struct static_tracepoint_marker *tpmarker;
13333           struct ui_out *uiout = current_uiout;
13334           struct explicit_location explicit_loc;
13335
13336           tpmarker = &markers[0];
13337
13338           tp->static_trace_marker_id = std::move (tpmarker->str_id);
13339
13340           warning (_("marker for static tracepoint %d (%s) not "
13341                      "found at previous line number"),
13342                    b->number, tp->static_trace_marker_id.c_str ());
13343
13344           symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
13345           sym = find_pc_sect_function (tpmarker->address, NULL);
13346           uiout->text ("Now in ");
13347           if (sym)
13348             {
13349               uiout->field_string ("func", SYMBOL_PRINT_NAME (sym),
13350                                    ui_out_style_kind::FUNCTION);
13351               uiout->text (" at ");
13352             }
13353           uiout->field_string ("file",
13354                                symtab_to_filename_for_display (sal2.symtab),
13355                                ui_out_style_kind::FILE);
13356           uiout->text (":");
13357
13358           if (uiout->is_mi_like_p ())
13359             {
13360               const char *fullname = symtab_to_fullname (sal2.symtab);
13361
13362               uiout->field_string ("fullname", fullname);
13363             }
13364
13365           uiout->field_int ("line", sal2.line);
13366           uiout->text ("\n");
13367
13368           b->loc->line_number = sal2.line;
13369           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13370
13371           b->location.reset (NULL);
13372           initialize_explicit_location (&explicit_loc);
13373           explicit_loc.source_filename
13374             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
13375           explicit_loc.line_offset.offset = b->loc->line_number;
13376           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
13377           b->location = new_explicit_location (&explicit_loc);
13378
13379           /* Might be nice to check if function changed, and warn if
13380              so.  */
13381         }
13382     }
13383   return sal;
13384 }
13385
13386 /* Returns 1 iff locations A and B are sufficiently same that
13387    we don't need to report breakpoint as changed.  */
13388
13389 static int
13390 locations_are_equal (struct bp_location *a, struct bp_location *b)
13391 {
13392   while (a && b)
13393     {
13394       if (a->address != b->address)
13395         return 0;
13396
13397       if (a->shlib_disabled != b->shlib_disabled)
13398         return 0;
13399
13400       if (a->enabled != b->enabled)
13401         return 0;
13402
13403       a = a->next;
13404       b = b->next;
13405     }
13406
13407   if ((a == NULL) != (b == NULL))
13408     return 0;
13409
13410   return 1;
13411 }
13412
13413 /* Split all locations of B that are bound to PSPACE out of B's
13414    location list to a separate list and return that list's head.  If
13415    PSPACE is NULL, hoist out all locations of B.  */
13416
13417 static struct bp_location *
13418 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
13419 {
13420   struct bp_location head;
13421   struct bp_location *i = b->loc;
13422   struct bp_location **i_link = &b->loc;
13423   struct bp_location *hoisted = &head;
13424
13425   if (pspace == NULL)
13426     {
13427       i = b->loc;
13428       b->loc = NULL;
13429       return i;
13430     }
13431
13432   head.next = NULL;
13433
13434   while (i != NULL)
13435     {
13436       if (i->pspace == pspace)
13437         {
13438           *i_link = i->next;
13439           i->next = NULL;
13440           hoisted->next = i;
13441           hoisted = i;
13442         }
13443       else
13444         i_link = &i->next;
13445       i = *i_link;
13446     }
13447
13448   return head.next;
13449 }
13450
13451 /* Create new breakpoint locations for B (a hardware or software
13452    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
13453    zero, then B is a ranged breakpoint.  Only recreates locations for
13454    FILTER_PSPACE.  Locations of other program spaces are left
13455    untouched.  */
13456
13457 void
13458 update_breakpoint_locations (struct breakpoint *b,
13459                              struct program_space *filter_pspace,
13460                              gdb::array_view<const symtab_and_line> sals,
13461                              gdb::array_view<const symtab_and_line> sals_end)
13462 {
13463   struct bp_location *existing_locations;
13464
13465   if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
13466     {
13467       /* Ranged breakpoints have only one start location and one end
13468          location.  */
13469       b->enable_state = bp_disabled;
13470       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13471                            "multiple locations found\n"),
13472                          b->number);
13473       return;
13474     }
13475
13476   /* If there's no new locations, and all existing locations are
13477      pending, don't do anything.  This optimizes the common case where
13478      all locations are in the same shared library, that was unloaded.
13479      We'd like to retain the location, so that when the library is
13480      loaded again, we don't loose the enabled/disabled status of the
13481      individual locations.  */
13482   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
13483     return;
13484
13485   existing_locations = hoist_existing_locations (b, filter_pspace);
13486
13487   for (const auto &sal : sals)
13488     {
13489       struct bp_location *new_loc;
13490
13491       switch_to_program_space_and_thread (sal.pspace);
13492
13493       new_loc = add_location_to_breakpoint (b, &sal);
13494
13495       /* Reparse conditions, they might contain references to the
13496          old symtab.  */
13497       if (b->cond_string != NULL)
13498         {
13499           const char *s;
13500
13501           s = b->cond_string;
13502           try
13503             {
13504               new_loc->cond = parse_exp_1 (&s, sal.pc,
13505                                            block_for_pc (sal.pc),
13506                                            0);
13507             }
13508           catch (const gdb_exception_error &e)
13509             {
13510               warning (_("failed to reevaluate condition "
13511                          "for breakpoint %d: %s"), 
13512                        b->number, e.what ());
13513               new_loc->enabled = 0;
13514             }
13515         }
13516
13517       if (!sals_end.empty ())
13518         {
13519           CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13520
13521           new_loc->length = end - sals[0].pc + 1;
13522         }
13523     }
13524
13525   /* If possible, carry over 'disable' status from existing
13526      breakpoints.  */
13527   {
13528     struct bp_location *e = existing_locations;
13529     /* If there are multiple breakpoints with the same function name,
13530        e.g. for inline functions, comparing function names won't work.
13531        Instead compare pc addresses; this is just a heuristic as things
13532        may have moved, but in practice it gives the correct answer
13533        often enough until a better solution is found.  */
13534     int have_ambiguous_names = ambiguous_names_p (b->loc);
13535
13536     for (; e; e = e->next)
13537       {
13538         if (!e->enabled && e->function_name)
13539           {
13540             struct bp_location *l = b->loc;
13541             if (have_ambiguous_names)
13542               {
13543                 for (; l; l = l->next)
13544                   if (breakpoint_locations_match (e, l))
13545                     {
13546                       l->enabled = 0;
13547                       break;
13548                     }
13549               }
13550             else
13551               {
13552                 for (; l; l = l->next)
13553                   if (l->function_name
13554                       && strcmp (e->function_name, l->function_name) == 0)
13555                     {
13556                       l->enabled = 0;
13557                       break;
13558                     }
13559               }
13560           }
13561       }
13562   }
13563
13564   if (!locations_are_equal (existing_locations, b->loc))
13565     gdb::observers::breakpoint_modified.notify (b);
13566 }
13567
13568 /* Find the SaL locations corresponding to the given LOCATION.
13569    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13570
13571 static std::vector<symtab_and_line>
13572 location_to_sals (struct breakpoint *b, struct event_location *location,
13573                   struct program_space *search_pspace, int *found)
13574 {
13575   struct gdb_exception exception;
13576
13577   gdb_assert (b->ops != NULL);
13578
13579   std::vector<symtab_and_line> sals;
13580
13581   try
13582     {
13583       sals = b->ops->decode_location (b, location, search_pspace);
13584     }
13585   catch (gdb_exception_error &e)
13586     {
13587       int not_found_and_ok = 0;
13588
13589       /* For pending breakpoints, it's expected that parsing will
13590          fail until the right shared library is loaded.  User has
13591          already told to create pending breakpoints and don't need
13592          extra messages.  If breakpoint is in bp_shlib_disabled
13593          state, then user already saw the message about that
13594          breakpoint being disabled, and don't want to see more
13595          errors.  */
13596       if (e.error == NOT_FOUND_ERROR
13597           && (b->condition_not_parsed
13598               || (b->loc != NULL
13599                   && search_pspace != NULL
13600                   && b->loc->pspace != search_pspace)
13601               || (b->loc && b->loc->shlib_disabled)
13602               || (b->loc && b->loc->pspace->executing_startup)
13603               || b->enable_state == bp_disabled))
13604         not_found_and_ok = 1;
13605
13606       if (!not_found_and_ok)
13607         {
13608           /* We surely don't want to warn about the same breakpoint
13609              10 times.  One solution, implemented here, is disable
13610              the breakpoint on error.  Another solution would be to
13611              have separate 'warning emitted' flag.  Since this
13612              happens only when a binary has changed, I don't know
13613              which approach is better.  */
13614           b->enable_state = bp_disabled;
13615           throw;
13616         }
13617
13618       exception = std::move (e);
13619     }
13620
13621   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13622     {
13623       for (auto &sal : sals)
13624         resolve_sal_pc (&sal);
13625       if (b->condition_not_parsed && b->extra_string != NULL)
13626         {
13627           char *cond_string, *extra_string;
13628           int thread, task;
13629
13630           find_condition_and_thread (b->extra_string, sals[0].pc,
13631                                      &cond_string, &thread, &task,
13632                                      &extra_string);
13633           gdb_assert (b->cond_string == NULL);
13634           if (cond_string)
13635             b->cond_string = cond_string;
13636           b->thread = thread;
13637           b->task = task;
13638           if (extra_string)
13639             {
13640               xfree (b->extra_string);
13641               b->extra_string = extra_string;
13642             }
13643           b->condition_not_parsed = 0;
13644         }
13645
13646       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13647         sals[0] = update_static_tracepoint (b, sals[0]);
13648
13649       *found = 1;
13650     }
13651   else
13652     *found = 0;
13653
13654   return sals;
13655 }
13656
13657 /* The default re_set method, for typical hardware or software
13658    breakpoints.  Reevaluate the breakpoint and recreate its
13659    locations.  */
13660
13661 static void
13662 breakpoint_re_set_default (struct breakpoint *b)
13663 {
13664   struct program_space *filter_pspace = current_program_space;
13665   std::vector<symtab_and_line> expanded, expanded_end;
13666
13667   int found;
13668   std::vector<symtab_and_line> sals = location_to_sals (b, b->location.get (),
13669                                                         filter_pspace, &found);
13670   if (found)
13671     expanded = std::move (sals);
13672
13673   if (b->location_range_end != NULL)
13674     {
13675       std::vector<symtab_and_line> sals_end
13676         = location_to_sals (b, b->location_range_end.get (),
13677                             filter_pspace, &found);
13678       if (found)
13679         expanded_end = std::move (sals_end);
13680     }
13681
13682   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
13683 }
13684
13685 /* Default method for creating SALs from an address string.  It basically
13686    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13687
13688 static void
13689 create_sals_from_location_default (const struct event_location *location,
13690                                    struct linespec_result *canonical,
13691                                    enum bptype type_wanted)
13692 {
13693   parse_breakpoint_sals (location, canonical);
13694 }
13695
13696 /* Call create_breakpoints_sal for the given arguments.  This is the default
13697    function for the `create_breakpoints_sal' method of
13698    breakpoint_ops.  */
13699
13700 static void
13701 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13702                                 struct linespec_result *canonical,
13703                                 gdb::unique_xmalloc_ptr<char> cond_string,
13704                                 gdb::unique_xmalloc_ptr<char> extra_string,
13705                                 enum bptype type_wanted,
13706                                 enum bpdisp disposition,
13707                                 int thread,
13708                                 int task, int ignore_count,
13709                                 const struct breakpoint_ops *ops,
13710                                 int from_tty, int enabled,
13711                                 int internal, unsigned flags)
13712 {
13713   create_breakpoints_sal (gdbarch, canonical,
13714                           std::move (cond_string),
13715                           std::move (extra_string),
13716                           type_wanted, disposition,
13717                           thread, task, ignore_count, ops, from_tty,
13718                           enabled, internal, flags);
13719 }
13720
13721 /* Decode the line represented by S by calling decode_line_full.  This is the
13722    default function for the `decode_location' method of breakpoint_ops.  */
13723
13724 static std::vector<symtab_and_line>
13725 decode_location_default (struct breakpoint *b,
13726                          const struct event_location *location,
13727                          struct program_space *search_pspace)
13728 {
13729   struct linespec_result canonical;
13730
13731   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
13732                     NULL, 0, &canonical, multiple_symbols_all,
13733                     b->filter);
13734
13735   /* We should get 0 or 1 resulting SALs.  */
13736   gdb_assert (canonical.lsals.size () < 2);
13737
13738   if (!canonical.lsals.empty ())
13739     {
13740       const linespec_sals &lsal = canonical.lsals[0];
13741       return std::move (lsal.sals);
13742     }
13743   return {};
13744 }
13745
13746 /* Reset a breakpoint.  */
13747
13748 static void
13749 breakpoint_re_set_one (breakpoint *b)
13750 {
13751   input_radix = b->input_radix;
13752   set_language (b->language);
13753
13754   b->ops->re_set (b);
13755 }
13756
13757 /* Re-set breakpoint locations for the current program space.
13758    Locations bound to other program spaces are left untouched.  */
13759
13760 void
13761 breakpoint_re_set (void)
13762 {
13763   struct breakpoint *b, *b_tmp;
13764
13765   {
13766     scoped_restore_current_language save_language;
13767     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
13768     scoped_restore_current_pspace_and_thread restore_pspace_thread;
13769
13770     /* breakpoint_re_set_one sets the current_language to the language
13771        of the breakpoint it is resetting (see prepare_re_set_context)
13772        before re-evaluating the breakpoint's location.  This change can
13773        unfortunately get undone by accident if the language_mode is set
13774        to auto, and we either switch frames, or more likely in this context,
13775        we select the current frame.
13776
13777        We prevent this by temporarily turning the language_mode to
13778        language_mode_manual.  We restore it once all breakpoints
13779        have been reset.  */
13780     scoped_restore save_language_mode = make_scoped_restore (&language_mode);
13781     language_mode = language_mode_manual;
13782
13783     /* Note: we must not try to insert locations until after all
13784        breakpoints have been re-set.  Otherwise, e.g., when re-setting
13785        breakpoint 1, we'd insert the locations of breakpoint 2, which
13786        hadn't been re-set yet, and thus may have stale locations.  */
13787
13788     ALL_BREAKPOINTS_SAFE (b, b_tmp)
13789       {
13790         try
13791           {
13792             breakpoint_re_set_one (b);
13793           }
13794         catch (const gdb_exception &ex)
13795           {
13796             exception_fprintf (gdb_stderr, ex,
13797                                "Error in re-setting breakpoint %d: ",
13798                                b->number);
13799           }
13800       }
13801
13802     jit_breakpoint_re_set ();
13803   }
13804
13805   create_overlay_event_breakpoint ();
13806   create_longjmp_master_breakpoint ();
13807   create_std_terminate_master_breakpoint ();
13808   create_exception_master_breakpoint ();
13809
13810   /* Now we can insert.  */
13811   update_global_location_list (UGLL_MAY_INSERT);
13812 }
13813 \f
13814 /* Reset the thread number of this breakpoint:
13815
13816    - If the breakpoint is for all threads, leave it as-is.
13817    - Else, reset it to the current thread for inferior_ptid.  */
13818 void
13819 breakpoint_re_set_thread (struct breakpoint *b)
13820 {
13821   if (b->thread != -1)
13822     {
13823       b->thread = inferior_thread ()->global_num;
13824
13825       /* We're being called after following a fork.  The new fork is
13826          selected as current, and unless this was a vfork will have a
13827          different program space from the original thread.  Reset that
13828          as well.  */
13829       b->loc->pspace = current_program_space;
13830     }
13831 }
13832
13833 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13834    If from_tty is nonzero, it prints a message to that effect,
13835    which ends with a period (no newline).  */
13836
13837 void
13838 set_ignore_count (int bptnum, int count, int from_tty)
13839 {
13840   struct breakpoint *b;
13841
13842   if (count < 0)
13843     count = 0;
13844
13845   ALL_BREAKPOINTS (b)
13846     if (b->number == bptnum)
13847     {
13848       if (is_tracepoint (b))
13849         {
13850           if (from_tty && count != 0)
13851             printf_filtered (_("Ignore count ignored for tracepoint %d."),
13852                              bptnum);
13853           return;
13854         }
13855       
13856       b->ignore_count = count;
13857       if (from_tty)
13858         {
13859           if (count == 0)
13860             printf_filtered (_("Will stop next time "
13861                                "breakpoint %d is reached."),
13862                              bptnum);
13863           else if (count == 1)
13864             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
13865                              bptnum);
13866           else
13867             printf_filtered (_("Will ignore next %d "
13868                                "crossings of breakpoint %d."),
13869                              count, bptnum);
13870         }
13871       gdb::observers::breakpoint_modified.notify (b);
13872       return;
13873     }
13874
13875   error (_("No breakpoint number %d."), bptnum);
13876 }
13877
13878 /* Command to set ignore-count of breakpoint N to COUNT.  */
13879
13880 static void
13881 ignore_command (const char *args, int from_tty)
13882 {
13883   const char *p = args;
13884   int num;
13885
13886   if (p == 0)
13887     error_no_arg (_("a breakpoint number"));
13888
13889   num = get_number (&p);
13890   if (num == 0)
13891     error (_("bad breakpoint number: '%s'"), args);
13892   if (*p == 0)
13893     error (_("Second argument (specified ignore-count) is missing."));
13894
13895   set_ignore_count (num,
13896                     longest_to_int (value_as_long (parse_and_eval (p))),
13897                     from_tty);
13898   if (from_tty)
13899     printf_filtered ("\n");
13900 }
13901 \f
13902
13903 /* Call FUNCTION on each of the breakpoints with numbers in the range
13904    defined by BP_NUM_RANGE (an inclusive range).  */
13905
13906 static void
13907 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
13908                              gdb::function_view<void (breakpoint *)> function)
13909 {
13910   if (bp_num_range.first == 0)
13911     {
13912       warning (_("bad breakpoint number at or near '%d'"),
13913                bp_num_range.first);
13914     }
13915   else
13916     {
13917       struct breakpoint *b, *tmp;
13918
13919       for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
13920         {
13921           bool match = false;
13922
13923           ALL_BREAKPOINTS_SAFE (b, tmp)
13924             if (b->number == i)
13925               {
13926                 match = true;
13927                 function (b);
13928                 break;
13929               }
13930           if (!match)
13931             printf_unfiltered (_("No breakpoint number %d.\n"), i);
13932         }
13933     }
13934 }
13935
13936 /* Call FUNCTION on each of the breakpoints whose numbers are given in
13937    ARGS.  */
13938
13939 static void
13940 map_breakpoint_numbers (const char *args,
13941                         gdb::function_view<void (breakpoint *)> function)
13942 {
13943   if (args == NULL || *args == '\0')
13944     error_no_arg (_("one or more breakpoint numbers"));
13945
13946   number_or_range_parser parser (args);
13947
13948   while (!parser.finished ())
13949     {
13950       int num = parser.get_number ();
13951       map_breakpoint_number_range (std::make_pair (num, num), function);
13952     }
13953 }
13954
13955 /* Return the breakpoint location structure corresponding to the
13956    BP_NUM and LOC_NUM values.  */
13957
13958 static struct bp_location *
13959 find_location_by_number (int bp_num, int loc_num)
13960 {
13961   struct breakpoint *b;
13962
13963   ALL_BREAKPOINTS (b)
13964     if (b->number == bp_num)
13965       {
13966         break;
13967       }
13968
13969   if (!b || b->number != bp_num)
13970     error (_("Bad breakpoint number '%d'"), bp_num);
13971   
13972   if (loc_num == 0)
13973     error (_("Bad breakpoint location number '%d'"), loc_num);
13974
13975   int n = 0;
13976   for (bp_location *loc = b->loc; loc != NULL; loc = loc->next)
13977     if (++n == loc_num)
13978       return loc;
13979
13980   error (_("Bad breakpoint location number '%d'"), loc_num);
13981 }
13982
13983 /* Modes of operation for extract_bp_num.  */
13984 enum class extract_bp_kind
13985 {
13986   /* Extracting a breakpoint number.  */
13987   bp,
13988
13989   /* Extracting a location number.  */
13990   loc,
13991 };
13992
13993 /* Extract a breakpoint or location number (as determined by KIND)
13994    from the string starting at START.  TRAILER is a character which
13995    can be found after the number.  If you don't want a trailer, use
13996    '\0'.  If END_OUT is not NULL, it is set to point after the parsed
13997    string.  This always returns a positive integer.  */
13998
13999 static int
14000 extract_bp_num (extract_bp_kind kind, const char *start,
14001                 int trailer, const char **end_out = NULL)
14002 {
14003   const char *end = start;
14004   int num = get_number_trailer (&end, trailer);
14005   if (num < 0)
14006     error (kind == extract_bp_kind::bp
14007            ? _("Negative breakpoint number '%.*s'")
14008            : _("Negative breakpoint location number '%.*s'"),
14009            int (end - start), start);
14010   if (num == 0)
14011     error (kind == extract_bp_kind::bp
14012            ? _("Bad breakpoint number '%.*s'")
14013            : _("Bad breakpoint location number '%.*s'"),
14014            int (end - start), start);
14015
14016   if (end_out != NULL)
14017     *end_out = end;
14018   return num;
14019 }
14020
14021 /* Extract a breakpoint or location range (as determined by KIND) in
14022    the form NUM1-NUM2 stored at &ARG[arg_offset].  Returns a std::pair
14023    representing the (inclusive) range.  The returned pair's elements
14024    are always positive integers.  */
14025
14026 static std::pair<int, int>
14027 extract_bp_or_bp_range (extract_bp_kind kind,
14028                         const std::string &arg,
14029                         std::string::size_type arg_offset)
14030 {
14031   std::pair<int, int> range;
14032   const char *bp_loc = &arg[arg_offset];
14033   std::string::size_type dash = arg.find ('-', arg_offset);
14034   if (dash != std::string::npos)
14035     {
14036       /* bp_loc is a range (x-z).  */
14037       if (arg.length () == dash + 1)
14038         error (kind == extract_bp_kind::bp
14039                ? _("Bad breakpoint number at or near: '%s'")
14040                : _("Bad breakpoint location number at or near: '%s'"),
14041                bp_loc);
14042
14043       const char *end;
14044       const char *start_first = bp_loc;
14045       const char *start_second = &arg[dash + 1];
14046       range.first = extract_bp_num (kind, start_first, '-');
14047       range.second = extract_bp_num (kind, start_second, '\0', &end);
14048
14049       if (range.first > range.second)
14050         error (kind == extract_bp_kind::bp
14051                ? _("Inverted breakpoint range at '%.*s'")
14052                : _("Inverted breakpoint location range at '%.*s'"),
14053                int (end - start_first), start_first);
14054     }
14055   else
14056     {
14057       /* bp_loc is a single value.  */
14058       range.first = extract_bp_num (kind, bp_loc, '\0');
14059       range.second = range.first;
14060     }
14061   return range;
14062 }
14063
14064 /* Extract the breakpoint/location range specified by ARG.  Returns
14065    the breakpoint range in BP_NUM_RANGE, and the location range in
14066    BP_LOC_RANGE.
14067
14068    ARG may be in any of the following forms:
14069
14070    x     where 'x' is a breakpoint number.
14071    x-y   where 'x' and 'y' specify a breakpoint numbers range.
14072    x.y   where 'x' is a breakpoint number and 'y' a location number.
14073    x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
14074          location number range.
14075 */
14076
14077 static void
14078 extract_bp_number_and_location (const std::string &arg,
14079                                 std::pair<int, int> &bp_num_range,
14080                                 std::pair<int, int> &bp_loc_range)
14081 {
14082   std::string::size_type dot = arg.find ('.');
14083
14084   if (dot != std::string::npos)
14085     {
14086       /* Handle 'x.y' and 'x.y-z' cases.  */
14087
14088       if (arg.length () == dot + 1 || dot == 0)
14089         error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
14090
14091       bp_num_range.first
14092         = extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
14093       bp_num_range.second = bp_num_range.first;
14094
14095       bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
14096                                              arg, dot + 1);
14097     }
14098   else
14099     {
14100       /* Handle x and x-y cases.  */
14101
14102       bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
14103       bp_loc_range.first = 0;
14104       bp_loc_range.second = 0;
14105     }
14106 }
14107
14108 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM.  ENABLE
14109    specifies whether to enable or disable.  */
14110
14111 static void
14112 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
14113 {
14114   struct bp_location *loc = find_location_by_number (bp_num, loc_num);
14115   if (loc != NULL)
14116     {
14117       if (loc->enabled != enable)
14118         {
14119           loc->enabled = enable;
14120           mark_breakpoint_location_modified (loc);
14121         }
14122       if (target_supports_enable_disable_tracepoint ()
14123           && current_trace_status ()->running && loc->owner
14124           && is_tracepoint (loc->owner))
14125         target_disable_tracepoint (loc);
14126     }
14127   update_global_location_list (UGLL_DONT_INSERT);
14128
14129   gdb::observers::breakpoint_modified.notify (loc->owner);
14130 }
14131
14132 /* Enable or disable a range of breakpoint locations.  BP_NUM is the
14133    number of the breakpoint, and BP_LOC_RANGE specifies the
14134    (inclusive) range of location numbers of that breakpoint to
14135    enable/disable.  ENABLE specifies whether to enable or disable the
14136    location.  */
14137
14138 static void
14139 enable_disable_breakpoint_location_range (int bp_num,
14140                                           std::pair<int, int> &bp_loc_range,
14141                                           bool enable)
14142 {
14143   for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
14144     enable_disable_bp_num_loc (bp_num, i, enable);
14145 }
14146
14147 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14148    If from_tty is nonzero, it prints a message to that effect,
14149    which ends with a period (no newline).  */
14150
14151 void
14152 disable_breakpoint (struct breakpoint *bpt)
14153 {
14154   /* Never disable a watchpoint scope breakpoint; we want to
14155      hit them when we leave scope so we can delete both the
14156      watchpoint and its scope breakpoint at that time.  */
14157   if (bpt->type == bp_watchpoint_scope)
14158     return;
14159
14160   bpt->enable_state = bp_disabled;
14161
14162   /* Mark breakpoint locations modified.  */
14163   mark_breakpoint_modified (bpt);
14164
14165   if (target_supports_enable_disable_tracepoint ()
14166       && current_trace_status ()->running && is_tracepoint (bpt))
14167     {
14168       struct bp_location *location;
14169      
14170       for (location = bpt->loc; location; location = location->next)
14171         target_disable_tracepoint (location);
14172     }
14173
14174   update_global_location_list (UGLL_DONT_INSERT);
14175
14176   gdb::observers::breakpoint_modified.notify (bpt);
14177 }
14178
14179 /* Enable or disable the breakpoint(s) or breakpoint location(s)
14180    specified in ARGS.  ARGS may be in any of the formats handled by
14181    extract_bp_number_and_location.  ENABLE specifies whether to enable
14182    or disable the breakpoints/locations.  */
14183
14184 static void
14185 enable_disable_command (const char *args, int from_tty, bool enable)
14186 {
14187   if (args == 0)
14188     {
14189       struct breakpoint *bpt;
14190
14191       ALL_BREAKPOINTS (bpt)
14192         if (user_breakpoint_p (bpt))
14193           {
14194             if (enable)
14195               enable_breakpoint (bpt);
14196             else
14197               disable_breakpoint (bpt);
14198           }
14199     }
14200   else
14201     {
14202       std::string num = extract_arg (&args);
14203
14204       while (!num.empty ())
14205         {
14206           std::pair<int, int> bp_num_range, bp_loc_range;
14207
14208           extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
14209
14210           if (bp_loc_range.first == bp_loc_range.second
14211               && bp_loc_range.first == 0)
14212             {
14213               /* Handle breakpoint ids with formats 'x' or 'x-z'.  */
14214               map_breakpoint_number_range (bp_num_range,
14215                                            enable
14216                                            ? enable_breakpoint
14217                                            : disable_breakpoint);
14218             }
14219           else
14220             {
14221               /* Handle breakpoint ids with formats 'x.y' or
14222                  'x.y-z'.  */
14223               enable_disable_breakpoint_location_range
14224                 (bp_num_range.first, bp_loc_range, enable);
14225             }
14226           num = extract_arg (&args);
14227         }
14228     }
14229 }
14230
14231 /* The disable command disables the specified breakpoints/locations
14232    (or all defined breakpoints) so they're no longer effective in
14233    stopping the inferior.  ARGS may be in any of the forms defined in
14234    extract_bp_number_and_location.  */
14235
14236 static void
14237 disable_command (const char *args, int from_tty)
14238 {
14239   enable_disable_command (args, from_tty, false);
14240 }
14241
14242 static void
14243 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14244                         int count)
14245 {
14246   int target_resources_ok;
14247
14248   if (bpt->type == bp_hardware_breakpoint)
14249     {
14250       int i;
14251       i = hw_breakpoint_used_count ();
14252       target_resources_ok = 
14253         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14254                                             i + 1, 0);
14255       if (target_resources_ok == 0)
14256         error (_("No hardware breakpoint support in the target."));
14257       else if (target_resources_ok < 0)
14258         error (_("Hardware breakpoints used exceeds limit."));
14259     }
14260
14261   if (is_watchpoint (bpt))
14262     {
14263       /* Initialize it just to avoid a GCC false warning.  */
14264       enum enable_state orig_enable_state = bp_disabled;
14265
14266       try
14267         {
14268           struct watchpoint *w = (struct watchpoint *) bpt;
14269
14270           orig_enable_state = bpt->enable_state;
14271           bpt->enable_state = bp_enabled;
14272           update_watchpoint (w, 1 /* reparse */);
14273         }
14274       catch (const gdb_exception &e)
14275         {
14276           bpt->enable_state = orig_enable_state;
14277           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14278                              bpt->number);
14279           return;
14280         }
14281     }
14282
14283   bpt->enable_state = bp_enabled;
14284
14285   /* Mark breakpoint locations modified.  */
14286   mark_breakpoint_modified (bpt);
14287
14288   if (target_supports_enable_disable_tracepoint ()
14289       && current_trace_status ()->running && is_tracepoint (bpt))
14290     {
14291       struct bp_location *location;
14292
14293       for (location = bpt->loc; location; location = location->next)
14294         target_enable_tracepoint (location);
14295     }
14296
14297   bpt->disposition = disposition;
14298   bpt->enable_count = count;
14299   update_global_location_list (UGLL_MAY_INSERT);
14300
14301   gdb::observers::breakpoint_modified.notify (bpt);
14302 }
14303
14304
14305 void
14306 enable_breakpoint (struct breakpoint *bpt)
14307 {
14308   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14309 }
14310
14311 /* The enable command enables the specified breakpoints/locations (or
14312    all defined breakpoints) so they once again become (or continue to
14313    be) effective in stopping the inferior.  ARGS may be in any of the
14314    forms defined in extract_bp_number_and_location.  */
14315
14316 static void
14317 enable_command (const char *args, int from_tty)
14318 {
14319   enable_disable_command (args, from_tty, true);
14320 }
14321
14322 static void
14323 enable_once_command (const char *args, int from_tty)
14324 {
14325   map_breakpoint_numbers
14326     (args, [&] (breakpoint *b)
14327      {
14328        iterate_over_related_breakpoints
14329          (b, [&] (breakpoint *bpt)
14330           {
14331             enable_breakpoint_disp (bpt, disp_disable, 1);
14332           });
14333      });
14334 }
14335
14336 static void
14337 enable_count_command (const char *args, int from_tty)
14338 {
14339   int count;
14340
14341   if (args == NULL)
14342     error_no_arg (_("hit count"));
14343
14344   count = get_number (&args);
14345
14346   map_breakpoint_numbers
14347     (args, [&] (breakpoint *b)
14348      {
14349        iterate_over_related_breakpoints
14350          (b, [&] (breakpoint *bpt)
14351           {
14352             enable_breakpoint_disp (bpt, disp_disable, count);
14353           });
14354      });
14355 }
14356
14357 static void
14358 enable_delete_command (const char *args, int from_tty)
14359 {
14360   map_breakpoint_numbers
14361     (args, [&] (breakpoint *b)
14362      {
14363        iterate_over_related_breakpoints
14364          (b, [&] (breakpoint *bpt)
14365           {
14366             enable_breakpoint_disp (bpt, disp_del, 1);
14367           });
14368      });
14369 }
14370 \f
14371 static void
14372 set_breakpoint_cmd (const char *args, int from_tty)
14373 {
14374 }
14375
14376 static void
14377 show_breakpoint_cmd (const char *args, int from_tty)
14378 {
14379 }
14380
14381 /* Invalidate last known value of any hardware watchpoint if
14382    the memory which that value represents has been written to by
14383    GDB itself.  */
14384
14385 static void
14386 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14387                                       CORE_ADDR addr, ssize_t len,
14388                                       const bfd_byte *data)
14389 {
14390   struct breakpoint *bp;
14391
14392   ALL_BREAKPOINTS (bp)
14393     if (bp->enable_state == bp_enabled
14394         && bp->type == bp_hardware_watchpoint)
14395       {
14396         struct watchpoint *wp = (struct watchpoint *) bp;
14397
14398         if (wp->val_valid && wp->val != nullptr)
14399           {
14400             struct bp_location *loc;
14401
14402             for (loc = bp->loc; loc != NULL; loc = loc->next)
14403               if (loc->loc_type == bp_loc_hardware_watchpoint
14404                   && loc->address + loc->length > addr
14405                   && addr + len > loc->address)
14406                 {
14407                   wp->val = NULL;
14408                   wp->val_valid = 0;
14409                 }
14410           }
14411       }
14412 }
14413
14414 /* Create and insert a breakpoint for software single step.  */
14415
14416 void
14417 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14418                                const address_space *aspace,
14419                                CORE_ADDR next_pc)
14420 {
14421   struct thread_info *tp = inferior_thread ();
14422   struct symtab_and_line sal;
14423   CORE_ADDR pc = next_pc;
14424
14425   if (tp->control.single_step_breakpoints == NULL)
14426     {
14427       tp->control.single_step_breakpoints
14428         = new_single_step_breakpoint (tp->global_num, gdbarch);
14429     }
14430
14431   sal = find_pc_line (pc, 0);
14432   sal.pc = pc;
14433   sal.section = find_pc_overlay (pc);
14434   sal.explicit_pc = 1;
14435   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14436
14437   update_global_location_list (UGLL_INSERT);
14438 }
14439
14440 /* Insert single step breakpoints according to the current state.  */
14441
14442 int
14443 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14444 {
14445   struct regcache *regcache = get_current_regcache ();
14446   std::vector<CORE_ADDR> next_pcs;
14447
14448   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14449
14450   if (!next_pcs.empty ())
14451     {
14452       struct frame_info *frame = get_current_frame ();
14453       const address_space *aspace = get_frame_address_space (frame);
14454
14455       for (CORE_ADDR pc : next_pcs)
14456         insert_single_step_breakpoint (gdbarch, aspace, pc);
14457
14458       return 1;
14459     }
14460   else
14461     return 0;
14462 }
14463
14464 /* See breakpoint.h.  */
14465
14466 int
14467 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14468                                        const address_space *aspace,
14469                                        CORE_ADDR pc)
14470 {
14471   struct bp_location *loc;
14472
14473   for (loc = bp->loc; loc != NULL; loc = loc->next)
14474     if (loc->inserted
14475         && breakpoint_location_address_match (loc, aspace, pc))
14476       return 1;
14477
14478   return 0;
14479 }
14480
14481 /* Check whether a software single-step breakpoint is inserted at
14482    PC.  */
14483
14484 int
14485 single_step_breakpoint_inserted_here_p (const address_space *aspace,
14486                                         CORE_ADDR pc)
14487 {
14488   struct breakpoint *bpt;
14489
14490   ALL_BREAKPOINTS (bpt)
14491     {
14492       if (bpt->type == bp_single_step
14493           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
14494         return 1;
14495     }
14496   return 0;
14497 }
14498
14499 /* Tracepoint-specific operations.  */
14500
14501 /* Set tracepoint count to NUM.  */
14502 static void
14503 set_tracepoint_count (int num)
14504 {
14505   tracepoint_count = num;
14506   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14507 }
14508
14509 static void
14510 trace_command (const char *arg, int from_tty)
14511 {
14512   struct breakpoint_ops *ops;
14513
14514   event_location_up location = string_to_event_location (&arg,
14515                                                          current_language);
14516   if (location != NULL
14517       && event_location_type (location.get ()) == PROBE_LOCATION)
14518     ops = &tracepoint_probe_breakpoint_ops;
14519   else
14520     ops = &tracepoint_breakpoint_ops;
14521
14522   create_breakpoint (get_current_arch (),
14523                      location.get (),
14524                      NULL, 0, arg, 1 /* parse arg */,
14525                      0 /* tempflag */,
14526                      bp_tracepoint /* type_wanted */,
14527                      0 /* Ignore count */,
14528                      pending_break_support,
14529                      ops,
14530                      from_tty,
14531                      1 /* enabled */,
14532                      0 /* internal */, 0);
14533 }
14534
14535 static void
14536 ftrace_command (const char *arg, int from_tty)
14537 {
14538   event_location_up location = string_to_event_location (&arg,
14539                                                          current_language);
14540   create_breakpoint (get_current_arch (),
14541                      location.get (),
14542                      NULL, 0, arg, 1 /* parse arg */,
14543                      0 /* tempflag */,
14544                      bp_fast_tracepoint /* type_wanted */,
14545                      0 /* Ignore count */,
14546                      pending_break_support,
14547                      &tracepoint_breakpoint_ops,
14548                      from_tty,
14549                      1 /* enabled */,
14550                      0 /* internal */, 0);
14551 }
14552
14553 /* strace command implementation.  Creates a static tracepoint.  */
14554
14555 static void
14556 strace_command (const char *arg, int from_tty)
14557 {
14558   struct breakpoint_ops *ops;
14559   event_location_up location;
14560
14561   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14562      or with a normal static tracepoint.  */
14563   if (arg && startswith (arg, "-m") && isspace (arg[2]))
14564     {
14565       ops = &strace_marker_breakpoint_ops;
14566       location = new_linespec_location (&arg, symbol_name_match_type::FULL);
14567     }
14568   else
14569     {
14570       ops = &tracepoint_breakpoint_ops;
14571       location = string_to_event_location (&arg, current_language);
14572     }
14573
14574   create_breakpoint (get_current_arch (),
14575                      location.get (),
14576                      NULL, 0, arg, 1 /* parse arg */,
14577                      0 /* tempflag */,
14578                      bp_static_tracepoint /* type_wanted */,
14579                      0 /* Ignore count */,
14580                      pending_break_support,
14581                      ops,
14582                      from_tty,
14583                      1 /* enabled */,
14584                      0 /* internal */, 0);
14585 }
14586
14587 /* Set up a fake reader function that gets command lines from a linked
14588    list that was acquired during tracepoint uploading.  */
14589
14590 static struct uploaded_tp *this_utp;
14591 static int next_cmd;
14592
14593 static char *
14594 read_uploaded_action (void)
14595 {
14596   char *rslt = nullptr;
14597
14598   if (next_cmd < this_utp->cmd_strings.size ())
14599     {
14600       rslt = this_utp->cmd_strings[next_cmd].get ();
14601       next_cmd++;
14602     }
14603
14604   return rslt;
14605 }
14606
14607 /* Given information about a tracepoint as recorded on a target (which
14608    can be either a live system or a trace file), attempt to create an
14609    equivalent GDB tracepoint.  This is not a reliable process, since
14610    the target does not necessarily have all the information used when
14611    the tracepoint was originally defined.  */
14612   
14613 struct tracepoint *
14614 create_tracepoint_from_upload (struct uploaded_tp *utp)
14615 {
14616   const char *addr_str;
14617   char small_buf[100];
14618   struct tracepoint *tp;
14619
14620   if (utp->at_string)
14621     addr_str = utp->at_string.get ();
14622   else
14623     {
14624       /* In the absence of a source location, fall back to raw
14625          address.  Since there is no way to confirm that the address
14626          means the same thing as when the trace was started, warn the
14627          user.  */
14628       warning (_("Uploaded tracepoint %d has no "
14629                  "source location, using raw address"),
14630                utp->number);
14631       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14632       addr_str = small_buf;
14633     }
14634
14635   /* There's not much we can do with a sequence of bytecodes.  */
14636   if (utp->cond && !utp->cond_string)
14637     warning (_("Uploaded tracepoint %d condition "
14638                "has no source form, ignoring it"),
14639              utp->number);
14640
14641   event_location_up location = string_to_event_location (&addr_str,
14642                                                          current_language);
14643   if (!create_breakpoint (get_current_arch (),
14644                           location.get (),
14645                           utp->cond_string.get (), -1, addr_str,
14646                           0 /* parse cond/thread */,
14647                           0 /* tempflag */,
14648                           utp->type /* type_wanted */,
14649                           0 /* Ignore count */,
14650                           pending_break_support,
14651                           &tracepoint_breakpoint_ops,
14652                           0 /* from_tty */,
14653                           utp->enabled /* enabled */,
14654                           0 /* internal */,
14655                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14656     return NULL;
14657
14658   /* Get the tracepoint we just created.  */
14659   tp = get_tracepoint (tracepoint_count);
14660   gdb_assert (tp != NULL);
14661
14662   if (utp->pass > 0)
14663     {
14664       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14665                  tp->number);
14666
14667       trace_pass_command (small_buf, 0);
14668     }
14669
14670   /* If we have uploaded versions of the original commands, set up a
14671      special-purpose "reader" function and call the usual command line
14672      reader, then pass the result to the breakpoint command-setting
14673      function.  */
14674   if (!utp->cmd_strings.empty ())
14675     {
14676       counted_command_line cmd_list;
14677
14678       this_utp = utp;
14679       next_cmd = 0;
14680
14681       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL);
14682
14683       breakpoint_set_commands (tp, std::move (cmd_list));
14684     }
14685   else if (!utp->actions.empty ()
14686            || !utp->step_actions.empty ())
14687     warning (_("Uploaded tracepoint %d actions "
14688                "have no source form, ignoring them"),
14689              utp->number);
14690
14691   /* Copy any status information that might be available.  */
14692   tp->hit_count = utp->hit_count;
14693   tp->traceframe_usage = utp->traceframe_usage;
14694
14695   return tp;
14696 }
14697   
14698 /* Print information on tracepoint number TPNUM_EXP, or all if
14699    omitted.  */
14700
14701 static void
14702 info_tracepoints_command (const char *args, int from_tty)
14703 {
14704   struct ui_out *uiout = current_uiout;
14705   int num_printed;
14706
14707   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14708
14709   if (num_printed == 0)
14710     {
14711       if (args == NULL || *args == '\0')
14712         uiout->message ("No tracepoints.\n");
14713       else
14714         uiout->message ("No tracepoint matching '%s'.\n", args);
14715     }
14716
14717   default_collect_info ();
14718 }
14719
14720 /* The 'enable trace' command enables tracepoints.
14721    Not supported by all targets.  */
14722 static void
14723 enable_trace_command (const char *args, int from_tty)
14724 {
14725   enable_command (args, from_tty);
14726 }
14727
14728 /* The 'disable trace' command disables tracepoints.
14729    Not supported by all targets.  */
14730 static void
14731 disable_trace_command (const char *args, int from_tty)
14732 {
14733   disable_command (args, from_tty);
14734 }
14735
14736 /* Remove a tracepoint (or all if no argument).  */
14737 static void
14738 delete_trace_command (const char *arg, int from_tty)
14739 {
14740   struct breakpoint *b, *b_tmp;
14741
14742   dont_repeat ();
14743
14744   if (arg == 0)
14745     {
14746       int breaks_to_delete = 0;
14747
14748       /* Delete all breakpoints if no argument.
14749          Do not delete internal or call-dummy breakpoints, these
14750          have to be deleted with an explicit breakpoint number 
14751          argument.  */
14752       ALL_TRACEPOINTS (b)
14753         if (is_tracepoint (b) && user_breakpoint_p (b))
14754           {
14755             breaks_to_delete = 1;
14756             break;
14757           }
14758
14759       /* Ask user only if there are some breakpoints to delete.  */
14760       if (!from_tty
14761           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14762         {
14763           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14764             if (is_tracepoint (b) && user_breakpoint_p (b))
14765               delete_breakpoint (b);
14766         }
14767     }
14768   else
14769     map_breakpoint_numbers
14770       (arg, [&] (breakpoint *br)
14771        {
14772          iterate_over_related_breakpoints (br, delete_breakpoint);
14773        });
14774 }
14775
14776 /* Helper function for trace_pass_command.  */
14777
14778 static void
14779 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14780 {
14781   tp->pass_count = count;
14782   gdb::observers::breakpoint_modified.notify (tp);
14783   if (from_tty)
14784     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
14785                      tp->number, count);
14786 }
14787
14788 /* Set passcount for tracepoint.
14789
14790    First command argument is passcount, second is tracepoint number.
14791    If tracepoint number omitted, apply to most recently defined.
14792    Also accepts special argument "all".  */
14793
14794 static void
14795 trace_pass_command (const char *args, int from_tty)
14796 {
14797   struct tracepoint *t1;
14798   ULONGEST count;
14799
14800   if (args == 0 || *args == 0)
14801     error (_("passcount command requires an "
14802              "argument (count + optional TP num)"));
14803
14804   count = strtoulst (args, &args, 10);  /* Count comes first, then TP num.  */
14805
14806   args = skip_spaces (args);
14807   if (*args && strncasecmp (args, "all", 3) == 0)
14808     {
14809       struct breakpoint *b;
14810
14811       args += 3;                        /* Skip special argument "all".  */
14812       if (*args)
14813         error (_("Junk at end of arguments."));
14814
14815       ALL_TRACEPOINTS (b)
14816       {
14817         t1 = (struct tracepoint *) b;
14818         trace_pass_set_count (t1, count, from_tty);
14819       }
14820     }
14821   else if (*args == '\0')
14822     {
14823       t1 = get_tracepoint_by_number (&args, NULL);
14824       if (t1)
14825         trace_pass_set_count (t1, count, from_tty);
14826     }
14827   else
14828     {
14829       number_or_range_parser parser (args);
14830       while (!parser.finished ())
14831         {
14832           t1 = get_tracepoint_by_number (&args, &parser);
14833           if (t1)
14834             trace_pass_set_count (t1, count, from_tty);
14835         }
14836     }
14837 }
14838
14839 struct tracepoint *
14840 get_tracepoint (int num)
14841 {
14842   struct breakpoint *t;
14843
14844   ALL_TRACEPOINTS (t)
14845     if (t->number == num)
14846       return (struct tracepoint *) t;
14847
14848   return NULL;
14849 }
14850
14851 /* Find the tracepoint with the given target-side number (which may be
14852    different from the tracepoint number after disconnecting and
14853    reconnecting).  */
14854
14855 struct tracepoint *
14856 get_tracepoint_by_number_on_target (int num)
14857 {
14858   struct breakpoint *b;
14859
14860   ALL_TRACEPOINTS (b)
14861     {
14862       struct tracepoint *t = (struct tracepoint *) b;
14863
14864       if (t->number_on_target == num)
14865         return t;
14866     }
14867
14868   return NULL;
14869 }
14870
14871 /* Utility: parse a tracepoint number and look it up in the list.
14872    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14873    If the argument is missing, the most recent tracepoint
14874    (tracepoint_count) is returned.  */
14875
14876 struct tracepoint *
14877 get_tracepoint_by_number (const char **arg,
14878                           number_or_range_parser *parser)
14879 {
14880   struct breakpoint *t;
14881   int tpnum;
14882   const char *instring = arg == NULL ? NULL : *arg;
14883
14884   if (parser != NULL)
14885     {
14886       gdb_assert (!parser->finished ());
14887       tpnum = parser->get_number ();
14888     }
14889   else if (arg == NULL || *arg == NULL || ! **arg)
14890     tpnum = tracepoint_count;
14891   else
14892     tpnum = get_number (arg);
14893
14894   if (tpnum <= 0)
14895     {
14896       if (instring && *instring)
14897         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
14898                          instring);
14899       else
14900         printf_filtered (_("No previous tracepoint\n"));
14901       return NULL;
14902     }
14903
14904   ALL_TRACEPOINTS (t)
14905     if (t->number == tpnum)
14906     {
14907       return (struct tracepoint *) t;
14908     }
14909
14910   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
14911   return NULL;
14912 }
14913
14914 void
14915 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
14916 {
14917   if (b->thread != -1)
14918     fprintf_unfiltered (fp, " thread %d", b->thread);
14919
14920   if (b->task != 0)
14921     fprintf_unfiltered (fp, " task %d", b->task);
14922
14923   fprintf_unfiltered (fp, "\n");
14924 }
14925
14926 /* Save information on user settable breakpoints (watchpoints, etc) to
14927    a new script file named FILENAME.  If FILTER is non-NULL, call it
14928    on each breakpoint and only include the ones for which it returns
14929    non-zero.  */
14930
14931 static void
14932 save_breakpoints (const char *filename, int from_tty,
14933                   int (*filter) (const struct breakpoint *))
14934 {
14935   struct breakpoint *tp;
14936   int any = 0;
14937   int extra_trace_bits = 0;
14938
14939   if (filename == 0 || *filename == 0)
14940     error (_("Argument required (file name in which to save)"));
14941
14942   /* See if we have anything to save.  */
14943   ALL_BREAKPOINTS (tp)
14944   {
14945     /* Skip internal and momentary breakpoints.  */
14946     if (!user_breakpoint_p (tp))
14947       continue;
14948
14949     /* If we have a filter, only save the breakpoints it accepts.  */
14950     if (filter && !filter (tp))
14951       continue;
14952
14953     any = 1;
14954
14955     if (is_tracepoint (tp))
14956       {
14957         extra_trace_bits = 1;
14958
14959         /* We can stop searching.  */
14960         break;
14961       }
14962   }
14963
14964   if (!any)
14965     {
14966       warning (_("Nothing to save."));
14967       return;
14968     }
14969
14970   gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
14971
14972   stdio_file fp;
14973
14974   if (!fp.open (expanded_filename.get (), "w"))
14975     error (_("Unable to open file '%s' for saving (%s)"),
14976            expanded_filename.get (), safe_strerror (errno));
14977
14978   if (extra_trace_bits)
14979     save_trace_state_variables (&fp);
14980
14981   ALL_BREAKPOINTS (tp)
14982   {
14983     /* Skip internal and momentary breakpoints.  */
14984     if (!user_breakpoint_p (tp))
14985       continue;
14986
14987     /* If we have a filter, only save the breakpoints it accepts.  */
14988     if (filter && !filter (tp))
14989       continue;
14990
14991     tp->ops->print_recreate (tp, &fp);
14992
14993     /* Note, we can't rely on tp->number for anything, as we can't
14994        assume the recreated breakpoint numbers will match.  Use $bpnum
14995        instead.  */
14996
14997     if (tp->cond_string)
14998       fp.printf ("  condition $bpnum %s\n", tp->cond_string);
14999
15000     if (tp->ignore_count)
15001       fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15002
15003     if (tp->type != bp_dprintf && tp->commands)
15004       {
15005         fp.puts ("  commands\n");
15006         
15007         current_uiout->redirect (&fp);
15008         try
15009           {
15010             print_command_lines (current_uiout, tp->commands.get (), 2);
15011           }
15012         catch (const gdb_exception &ex)
15013           {
15014           current_uiout->redirect (NULL);
15015             throw;
15016           }
15017
15018         current_uiout->redirect (NULL);
15019         fp.puts ("  end\n");
15020       }
15021
15022     if (tp->enable_state == bp_disabled)
15023       fp.puts ("disable $bpnum\n");
15024
15025     /* If this is a multi-location breakpoint, check if the locations
15026        should be individually disabled.  Watchpoint locations are
15027        special, and not user visible.  */
15028     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15029       {
15030         struct bp_location *loc;
15031         int n = 1;
15032
15033         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15034           if (!loc->enabled)
15035             fp.printf ("disable $bpnum.%d\n", n);
15036       }
15037   }
15038
15039   if (extra_trace_bits && *default_collect)
15040     fp.printf ("set default-collect %s\n", default_collect);
15041
15042   if (from_tty)
15043     printf_filtered (_("Saved to file '%s'.\n"), expanded_filename.get ());
15044 }
15045
15046 /* The `save breakpoints' command.  */
15047
15048 static void
15049 save_breakpoints_command (const char *args, int from_tty)
15050 {
15051   save_breakpoints (args, from_tty, NULL);
15052 }
15053
15054 /* The `save tracepoints' command.  */
15055
15056 static void
15057 save_tracepoints_command (const char *args, int from_tty)
15058 {
15059   save_breakpoints (args, from_tty, is_tracepoint);
15060 }
15061
15062 /* Create a vector of all tracepoints.  */
15063
15064 std::vector<breakpoint *>
15065 all_tracepoints (void)
15066 {
15067   std::vector<breakpoint *> tp_vec;
15068   struct breakpoint *tp;
15069
15070   ALL_TRACEPOINTS (tp)
15071   {
15072     tp_vec.push_back (tp);
15073   }
15074
15075   return tp_vec;
15076 }
15077
15078 \f
15079 /* This help string is used to consolidate all the help string for specifying
15080    locations used by several commands.  */
15081
15082 #define LOCATION_HELP_STRING \
15083 "Linespecs are colon-separated lists of location parameters, such as\n\
15084 source filename, function name, label name, and line number.\n\
15085 Example: To specify the start of a label named \"the_top\" in the\n\
15086 function \"fact\" in the file \"factorial.c\", use\n\
15087 \"factorial.c:fact:the_top\".\n\
15088 \n\
15089 Address locations begin with \"*\" and specify an exact address in the\n\
15090 program.  Example: To specify the fourth byte past the start function\n\
15091 \"main\", use \"*main + 4\".\n\
15092 \n\
15093 Explicit locations are similar to linespecs but use an option/argument\n\
15094 syntax to specify location parameters.\n\
15095 Example: To specify the start of the label named \"the_top\" in the\n\
15096 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15097 -function fact -label the_top\".\n\
15098 \n\
15099 By default, a specified function is matched against the program's\n\
15100 functions in all scopes.  For C++, this means in all namespaces and\n\
15101 classes.  For Ada, this means in all packages.  E.g., in C++,\n\
15102 \"func()\" matches \"A::func()\", \"A::B::func()\", etc.  The\n\
15103 \"-qualified\" flag overrides this behavior, making GDB interpret the\n\
15104 specified name as a complete fully-qualified name instead."
15105
15106 /* This help string is used for the break, hbreak, tbreak and thbreak
15107    commands.  It is defined as a macro to prevent duplication.
15108    COMMAND should be a string constant containing the name of the
15109    command.  */
15110
15111 #define BREAK_ARGS_HELP(command) \
15112 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15113 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15114 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15115 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15116 `-probe-dtrace' (for a DTrace probe).\n\
15117 LOCATION may be a linespec, address, or explicit location as described\n\
15118 below.\n\
15119 \n\
15120 With no LOCATION, uses current execution address of the selected\n\
15121 stack frame.  This is useful for breaking on return to a stack frame.\n\
15122 \n\
15123 THREADNUM is the number from \"info threads\".\n\
15124 CONDITION is a boolean expression.\n\
15125 \n" LOCATION_HELP_STRING "\n\n\
15126 Multiple breakpoints at one place are permitted, and useful if their\n\
15127 conditions are different.\n\
15128 \n\
15129 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15130
15131 /* List of subcommands for "catch".  */
15132 static struct cmd_list_element *catch_cmdlist;
15133
15134 /* List of subcommands for "tcatch".  */
15135 static struct cmd_list_element *tcatch_cmdlist;
15136
15137 void
15138 add_catch_command (const char *name, const char *docstring,
15139                    cmd_const_sfunc_ftype *sfunc,
15140                    completer_ftype *completer,
15141                    void *user_data_catch,
15142                    void *user_data_tcatch)
15143 {
15144   struct cmd_list_element *command;
15145
15146   command = add_cmd (name, class_breakpoint, docstring,
15147                      &catch_cmdlist);
15148   set_cmd_sfunc (command, sfunc);
15149   set_cmd_context (command, user_data_catch);
15150   set_cmd_completer (command, completer);
15151
15152   command = add_cmd (name, class_breakpoint, docstring,
15153                      &tcatch_cmdlist);
15154   set_cmd_sfunc (command, sfunc);
15155   set_cmd_context (command, user_data_tcatch);
15156   set_cmd_completer (command, completer);
15157 }
15158
15159 static void
15160 save_command (const char *arg, int from_tty)
15161 {
15162   printf_unfiltered (_("\"save\" must be followed by "
15163                        "the name of a save subcommand.\n"));
15164   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15165 }
15166
15167 struct breakpoint *
15168 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15169                           void *data)
15170 {
15171   struct breakpoint *b, *b_tmp;
15172
15173   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15174     {
15175       if ((*callback) (b, data))
15176         return b;
15177     }
15178
15179   return NULL;
15180 }
15181
15182 /* Zero if any of the breakpoint's locations could be a location where
15183    functions have been inlined, nonzero otherwise.  */
15184
15185 static int
15186 is_non_inline_function (struct breakpoint *b)
15187 {
15188   /* The shared library event breakpoint is set on the address of a
15189      non-inline function.  */
15190   if (b->type == bp_shlib_event)
15191     return 1;
15192
15193   return 0;
15194 }
15195
15196 /* Nonzero if the specified PC cannot be a location where functions
15197    have been inlined.  */
15198
15199 int
15200 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
15201                            const struct target_waitstatus *ws)
15202 {
15203   struct breakpoint *b;
15204   struct bp_location *bl;
15205
15206   ALL_BREAKPOINTS (b)
15207     {
15208       if (!is_non_inline_function (b))
15209         continue;
15210
15211       for (bl = b->loc; bl != NULL; bl = bl->next)
15212         {
15213           if (!bl->shlib_disabled
15214               && bpstat_check_location (bl, aspace, pc, ws))
15215             return 1;
15216         }
15217     }
15218
15219   return 0;
15220 }
15221
15222 /* Remove any references to OBJFILE which is going to be freed.  */
15223
15224 void
15225 breakpoint_free_objfile (struct objfile *objfile)
15226 {
15227   struct bp_location **locp, *loc;
15228
15229   ALL_BP_LOCATIONS (loc, locp)
15230     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15231       loc->symtab = NULL;
15232 }
15233
15234 void
15235 initialize_breakpoint_ops (void)
15236 {
15237   static int initialized = 0;
15238
15239   struct breakpoint_ops *ops;
15240
15241   if (initialized)
15242     return;
15243   initialized = 1;
15244
15245   /* The breakpoint_ops structure to be inherit by all kinds of
15246      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15247      internal and momentary breakpoints, etc.).  */
15248   ops = &bkpt_base_breakpoint_ops;
15249   *ops = base_breakpoint_ops;
15250   ops->re_set = bkpt_re_set;
15251   ops->insert_location = bkpt_insert_location;
15252   ops->remove_location = bkpt_remove_location;
15253   ops->breakpoint_hit = bkpt_breakpoint_hit;
15254   ops->create_sals_from_location = bkpt_create_sals_from_location;
15255   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15256   ops->decode_location = bkpt_decode_location;
15257
15258   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15259   ops = &bkpt_breakpoint_ops;
15260   *ops = bkpt_base_breakpoint_ops;
15261   ops->re_set = bkpt_re_set;
15262   ops->resources_needed = bkpt_resources_needed;
15263   ops->print_it = bkpt_print_it;
15264   ops->print_mention = bkpt_print_mention;
15265   ops->print_recreate = bkpt_print_recreate;
15266
15267   /* Ranged breakpoints.  */
15268   ops = &ranged_breakpoint_ops;
15269   *ops = bkpt_breakpoint_ops;
15270   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15271   ops->resources_needed = resources_needed_ranged_breakpoint;
15272   ops->print_it = print_it_ranged_breakpoint;
15273   ops->print_one = print_one_ranged_breakpoint;
15274   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15275   ops->print_mention = print_mention_ranged_breakpoint;
15276   ops->print_recreate = print_recreate_ranged_breakpoint;
15277
15278   /* Internal breakpoints.  */
15279   ops = &internal_breakpoint_ops;
15280   *ops = bkpt_base_breakpoint_ops;
15281   ops->re_set = internal_bkpt_re_set;
15282   ops->check_status = internal_bkpt_check_status;
15283   ops->print_it = internal_bkpt_print_it;
15284   ops->print_mention = internal_bkpt_print_mention;
15285
15286   /* Momentary breakpoints.  */
15287   ops = &momentary_breakpoint_ops;
15288   *ops = bkpt_base_breakpoint_ops;
15289   ops->re_set = momentary_bkpt_re_set;
15290   ops->check_status = momentary_bkpt_check_status;
15291   ops->print_it = momentary_bkpt_print_it;
15292   ops->print_mention = momentary_bkpt_print_mention;
15293
15294   /* Probe breakpoints.  */
15295   ops = &bkpt_probe_breakpoint_ops;
15296   *ops = bkpt_breakpoint_ops;
15297   ops->insert_location = bkpt_probe_insert_location;
15298   ops->remove_location = bkpt_probe_remove_location;
15299   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15300   ops->decode_location = bkpt_probe_decode_location;
15301
15302   /* Watchpoints.  */
15303   ops = &watchpoint_breakpoint_ops;
15304   *ops = base_breakpoint_ops;
15305   ops->re_set = re_set_watchpoint;
15306   ops->insert_location = insert_watchpoint;
15307   ops->remove_location = remove_watchpoint;
15308   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15309   ops->check_status = check_status_watchpoint;
15310   ops->resources_needed = resources_needed_watchpoint;
15311   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15312   ops->print_it = print_it_watchpoint;
15313   ops->print_mention = print_mention_watchpoint;
15314   ops->print_recreate = print_recreate_watchpoint;
15315   ops->explains_signal = explains_signal_watchpoint;
15316
15317   /* Masked watchpoints.  */
15318   ops = &masked_watchpoint_breakpoint_ops;
15319   *ops = watchpoint_breakpoint_ops;
15320   ops->insert_location = insert_masked_watchpoint;
15321   ops->remove_location = remove_masked_watchpoint;
15322   ops->resources_needed = resources_needed_masked_watchpoint;
15323   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15324   ops->print_it = print_it_masked_watchpoint;
15325   ops->print_one_detail = print_one_detail_masked_watchpoint;
15326   ops->print_mention = print_mention_masked_watchpoint;
15327   ops->print_recreate = print_recreate_masked_watchpoint;
15328
15329   /* Tracepoints.  */
15330   ops = &tracepoint_breakpoint_ops;
15331   *ops = base_breakpoint_ops;
15332   ops->re_set = tracepoint_re_set;
15333   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15334   ops->print_one_detail = tracepoint_print_one_detail;
15335   ops->print_mention = tracepoint_print_mention;
15336   ops->print_recreate = tracepoint_print_recreate;
15337   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15338   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15339   ops->decode_location = tracepoint_decode_location;
15340
15341   /* Probe tracepoints.  */
15342   ops = &tracepoint_probe_breakpoint_ops;
15343   *ops = tracepoint_breakpoint_ops;
15344   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15345   ops->decode_location = tracepoint_probe_decode_location;
15346
15347   /* Static tracepoints with marker (`-m').  */
15348   ops = &strace_marker_breakpoint_ops;
15349   *ops = tracepoint_breakpoint_ops;
15350   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15351   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15352   ops->decode_location = strace_marker_decode_location;
15353
15354   /* Fork catchpoints.  */
15355   ops = &catch_fork_breakpoint_ops;
15356   *ops = base_breakpoint_ops;
15357   ops->insert_location = insert_catch_fork;
15358   ops->remove_location = remove_catch_fork;
15359   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15360   ops->print_it = print_it_catch_fork;
15361   ops->print_one = print_one_catch_fork;
15362   ops->print_mention = print_mention_catch_fork;
15363   ops->print_recreate = print_recreate_catch_fork;
15364
15365   /* Vfork catchpoints.  */
15366   ops = &catch_vfork_breakpoint_ops;
15367   *ops = base_breakpoint_ops;
15368   ops->insert_location = insert_catch_vfork;
15369   ops->remove_location = remove_catch_vfork;
15370   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15371   ops->print_it = print_it_catch_vfork;
15372   ops->print_one = print_one_catch_vfork;
15373   ops->print_mention = print_mention_catch_vfork;
15374   ops->print_recreate = print_recreate_catch_vfork;
15375
15376   /* Exec catchpoints.  */
15377   ops = &catch_exec_breakpoint_ops;
15378   *ops = base_breakpoint_ops;
15379   ops->insert_location = insert_catch_exec;
15380   ops->remove_location = remove_catch_exec;
15381   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15382   ops->print_it = print_it_catch_exec;
15383   ops->print_one = print_one_catch_exec;
15384   ops->print_mention = print_mention_catch_exec;
15385   ops->print_recreate = print_recreate_catch_exec;
15386
15387   /* Solib-related catchpoints.  */
15388   ops = &catch_solib_breakpoint_ops;
15389   *ops = base_breakpoint_ops;
15390   ops->insert_location = insert_catch_solib;
15391   ops->remove_location = remove_catch_solib;
15392   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15393   ops->check_status = check_status_catch_solib;
15394   ops->print_it = print_it_catch_solib;
15395   ops->print_one = print_one_catch_solib;
15396   ops->print_mention = print_mention_catch_solib;
15397   ops->print_recreate = print_recreate_catch_solib;
15398
15399   ops = &dprintf_breakpoint_ops;
15400   *ops = bkpt_base_breakpoint_ops;
15401   ops->re_set = dprintf_re_set;
15402   ops->resources_needed = bkpt_resources_needed;
15403   ops->print_it = bkpt_print_it;
15404   ops->print_mention = bkpt_print_mention;
15405   ops->print_recreate = dprintf_print_recreate;
15406   ops->after_condition_true = dprintf_after_condition_true;
15407   ops->breakpoint_hit = dprintf_breakpoint_hit;
15408 }
15409
15410 /* Chain containing all defined "enable breakpoint" subcommands.  */
15411
15412 static struct cmd_list_element *enablebreaklist = NULL;
15413
15414 /* See breakpoint.h.  */
15415
15416 cmd_list_element *commands_cmd_element = nullptr;
15417
15418 void
15419 _initialize_breakpoint (void)
15420 {
15421   struct cmd_list_element *c;
15422
15423   initialize_breakpoint_ops ();
15424
15425   gdb::observers::solib_unloaded.attach (disable_breakpoints_in_unloaded_shlib);
15426   gdb::observers::free_objfile.attach (disable_breakpoints_in_freed_objfile);
15427   gdb::observers::memory_changed.attach (invalidate_bp_value_on_memory_change);
15428
15429   breakpoint_chain = 0;
15430   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15431      before a breakpoint is set.  */
15432   breakpoint_count = 0;
15433
15434   tracepoint_count = 0;
15435
15436   add_com ("ignore", class_breakpoint, ignore_command, _("\
15437 Set ignore-count of breakpoint number N to COUNT.\n\
15438 Usage is `ignore N COUNT'."));
15439
15440   commands_cmd_element = add_com ("commands", class_breakpoint,
15441                                   commands_command, _("\
15442 Set commands to be executed when the given breakpoints are hit.\n\
15443 Give a space-separated breakpoint list as argument after \"commands\".\n\
15444 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
15445 (e.g. `5-7').\n\
15446 With no argument, the targeted breakpoint is the last one set.\n\
15447 The commands themselves follow starting on the next line.\n\
15448 Type a line containing \"end\" to indicate the end of them.\n\
15449 Give \"silent\" as the first line to make the breakpoint silent;\n\
15450 then no output is printed when it is hit, except what the commands print."));
15451
15452   c = add_com ("condition", class_breakpoint, condition_command, _("\
15453 Specify breakpoint number N to break only if COND is true.\n\
15454 Usage is `condition N COND', where N is an integer and COND is an\n\
15455 expression to be evaluated whenever breakpoint N is reached."));
15456   set_cmd_completer (c, condition_completer);
15457
15458   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15459 Set a temporary breakpoint.\n\
15460 Like \"break\" except the breakpoint is only temporary,\n\
15461 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15462 by using \"enable delete\" on the breakpoint number.\n\
15463 \n"
15464 BREAK_ARGS_HELP ("tbreak")));
15465   set_cmd_completer (c, location_completer);
15466
15467   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15468 Set a hardware assisted breakpoint.\n\
15469 Like \"break\" except the breakpoint requires hardware support,\n\
15470 some target hardware may not have this support.\n\
15471 \n"
15472 BREAK_ARGS_HELP ("hbreak")));
15473   set_cmd_completer (c, location_completer);
15474
15475   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15476 Set a temporary hardware assisted breakpoint.\n\
15477 Like \"hbreak\" except the breakpoint is only temporary,\n\
15478 so it will be deleted when hit.\n\
15479 \n"
15480 BREAK_ARGS_HELP ("thbreak")));
15481   set_cmd_completer (c, location_completer);
15482
15483   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15484 Enable some breakpoints.\n\
15485 Give breakpoint numbers (separated by spaces) as arguments.\n\
15486 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15487 This is used to cancel the effect of the \"disable\" command.\n\
15488 With a subcommand you can enable temporarily."),
15489                   &enablelist, "enable ", 1, &cmdlist);
15490
15491   add_com_alias ("en", "enable", class_breakpoint, 1);
15492
15493   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15494 Enable some breakpoints.\n\
15495 Give breakpoint numbers (separated by spaces) as arguments.\n\
15496 This is used to cancel the effect of the \"disable\" command.\n\
15497 May be abbreviated to simply \"enable\"."),
15498                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15499
15500   add_cmd ("once", no_class, enable_once_command, _("\
15501 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15502 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15503            &enablebreaklist);
15504
15505   add_cmd ("delete", no_class, enable_delete_command, _("\
15506 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15507 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15508            &enablebreaklist);
15509
15510   add_cmd ("count", no_class, enable_count_command, _("\
15511 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15512 If a breakpoint is hit while enabled in this fashion,\n\
15513 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15514            &enablebreaklist);
15515
15516   add_cmd ("delete", no_class, enable_delete_command, _("\
15517 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15518 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15519            &enablelist);
15520
15521   add_cmd ("once", no_class, enable_once_command, _("\
15522 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15523 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15524            &enablelist);
15525
15526   add_cmd ("count", no_class, enable_count_command, _("\
15527 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15528 If a breakpoint is hit while enabled in this fashion,\n\
15529 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15530            &enablelist);
15531
15532   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15533 Disable some breakpoints.\n\
15534 Arguments are breakpoint numbers with spaces in between.\n\
15535 To disable all breakpoints, give no argument.\n\
15536 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15537                   &disablelist, "disable ", 1, &cmdlist);
15538   add_com_alias ("dis", "disable", class_breakpoint, 1);
15539   add_com_alias ("disa", "disable", class_breakpoint, 1);
15540
15541   add_cmd ("breakpoints", class_alias, disable_command, _("\
15542 Disable some breakpoints.\n\
15543 Arguments are breakpoint numbers with spaces in between.\n\
15544 To disable all breakpoints, give no argument.\n\
15545 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15546 This command may be abbreviated \"disable\"."),
15547            &disablelist);
15548
15549   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15550 Delete some breakpoints or auto-display expressions.\n\
15551 Arguments are breakpoint numbers with spaces in between.\n\
15552 To delete all breakpoints, give no argument.\n\
15553 \n\
15554 Also a prefix command for deletion of other GDB objects.\n\
15555 The \"unset\" command is also an alias for \"delete\"."),
15556                   &deletelist, "delete ", 1, &cmdlist);
15557   add_com_alias ("d", "delete", class_breakpoint, 1);
15558   add_com_alias ("del", "delete", class_breakpoint, 1);
15559
15560   add_cmd ("breakpoints", class_alias, delete_command, _("\
15561 Delete some breakpoints or auto-display expressions.\n\
15562 Arguments are breakpoint numbers with spaces in between.\n\
15563 To delete all breakpoints, give no argument.\n\
15564 This command may be abbreviated \"delete\"."),
15565            &deletelist);
15566
15567   add_com ("clear", class_breakpoint, clear_command, _("\
15568 Clear breakpoint at specified location.\n\
15569 Argument may be a linespec, explicit, or address location as described below.\n\
15570 \n\
15571 With no argument, clears all breakpoints in the line that the selected frame\n\
15572 is executing in.\n"
15573 "\n" LOCATION_HELP_STRING "\n\n\
15574 See also the \"delete\" command which clears breakpoints by number."));
15575   add_com_alias ("cl", "clear", class_breakpoint, 1);
15576
15577   c = add_com ("break", class_breakpoint, break_command, _("\
15578 Set breakpoint at specified location.\n"
15579 BREAK_ARGS_HELP ("break")));
15580   set_cmd_completer (c, location_completer);
15581
15582   add_com_alias ("b", "break", class_run, 1);
15583   add_com_alias ("br", "break", class_run, 1);
15584   add_com_alias ("bre", "break", class_run, 1);
15585   add_com_alias ("brea", "break", class_run, 1);
15586
15587   if (dbx_commands)
15588     {
15589       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15590 Break in function/address or break at a line in the current file."),
15591                              &stoplist, "stop ", 1, &cmdlist);
15592       add_cmd ("in", class_breakpoint, stopin_command,
15593                _("Break in function or address."), &stoplist);
15594       add_cmd ("at", class_breakpoint, stopat_command,
15595                _("Break at a line in the current file."), &stoplist);
15596       add_com ("status", class_info, info_breakpoints_command, _("\
15597 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15598 The \"Type\" column indicates one of:\n\
15599 \tbreakpoint     - normal breakpoint\n\
15600 \twatchpoint     - watchpoint\n\
15601 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15602 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15603 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15604 address and file/line number respectively.\n\
15605 \n\
15606 Convenience variable \"$_\" and default examine address for \"x\"\n\
15607 are set to the address of the last breakpoint listed unless the command\n\
15608 is prefixed with \"server \".\n\n\
15609 Convenience variable \"$bpnum\" contains the number of the last\n\
15610 breakpoint set."));
15611     }
15612
15613   add_info ("breakpoints", info_breakpoints_command, _("\
15614 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15615 The \"Type\" column indicates one of:\n\
15616 \tbreakpoint     - normal breakpoint\n\
15617 \twatchpoint     - watchpoint\n\
15618 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15619 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15620 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15621 address and file/line number respectively.\n\
15622 \n\
15623 Convenience variable \"$_\" and default examine address for \"x\"\n\
15624 are set to the address of the last breakpoint listed unless the command\n\
15625 is prefixed with \"server \".\n\n\
15626 Convenience variable \"$bpnum\" contains the number of the last\n\
15627 breakpoint set."));
15628
15629   add_info_alias ("b", "breakpoints", 1);
15630
15631   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15632 Status of all breakpoints, or breakpoint number NUMBER.\n\
15633 The \"Type\" column indicates one of:\n\
15634 \tbreakpoint     - normal breakpoint\n\
15635 \twatchpoint     - watchpoint\n\
15636 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15637 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15638 \tuntil          - internal breakpoint used by the \"until\" command\n\
15639 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15640 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15641 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15642 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15643 address and file/line number respectively.\n\
15644 \n\
15645 Convenience variable \"$_\" and default examine address for \"x\"\n\
15646 are set to the address of the last breakpoint listed unless the command\n\
15647 is prefixed with \"server \".\n\n\
15648 Convenience variable \"$bpnum\" contains the number of the last\n\
15649 breakpoint set."),
15650            &maintenanceinfolist);
15651
15652   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15653 Set catchpoints to catch events."),
15654                   &catch_cmdlist, "catch ",
15655                   0/*allow-unknown*/, &cmdlist);
15656
15657   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15658 Set temporary catchpoints to catch events."),
15659                   &tcatch_cmdlist, "tcatch ",
15660                   0/*allow-unknown*/, &cmdlist);
15661
15662   add_catch_command ("fork", _("Catch calls to fork."),
15663                      catch_fork_command_1,
15664                      NULL,
15665                      (void *) (uintptr_t) catch_fork_permanent,
15666                      (void *) (uintptr_t) catch_fork_temporary);
15667   add_catch_command ("vfork", _("Catch calls to vfork."),
15668                      catch_fork_command_1,
15669                      NULL,
15670                      (void *) (uintptr_t) catch_vfork_permanent,
15671                      (void *) (uintptr_t) catch_vfork_temporary);
15672   add_catch_command ("exec", _("Catch calls to exec."),
15673                      catch_exec_command_1,
15674                      NULL,
15675                      CATCH_PERMANENT,
15676                      CATCH_TEMPORARY);
15677   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15678 Usage: catch load [REGEX]\n\
15679 If REGEX is given, only stop for libraries matching the regular expression."),
15680                      catch_load_command_1,
15681                      NULL,
15682                      CATCH_PERMANENT,
15683                      CATCH_TEMPORARY);
15684   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15685 Usage: catch unload [REGEX]\n\
15686 If REGEX is given, only stop for libraries matching the regular expression."),
15687                      catch_unload_command_1,
15688                      NULL,
15689                      CATCH_PERMANENT,
15690                      CATCH_TEMPORARY);
15691
15692   c = add_com ("watch", class_breakpoint, watch_command, _("\
15693 Set a watchpoint for an expression.\n\
15694 Usage: watch [-l|-location] EXPRESSION\n\
15695 A watchpoint stops execution of your program whenever the value of\n\
15696 an expression changes.\n\
15697 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15698 the memory to which it refers."));
15699   set_cmd_completer (c, expression_completer);
15700
15701   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15702 Set a read watchpoint for an expression.\n\
15703 Usage: rwatch [-l|-location] EXPRESSION\n\
15704 A watchpoint stops execution of your program whenever the value of\n\
15705 an expression is read.\n\
15706 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15707 the memory to which it refers."));
15708   set_cmd_completer (c, expression_completer);
15709
15710   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15711 Set a watchpoint for an expression.\n\
15712 Usage: awatch [-l|-location] EXPRESSION\n\
15713 A watchpoint stops execution of your program whenever the value of\n\
15714 an expression is either read or written.\n\
15715 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15716 the memory to which it refers."));
15717   set_cmd_completer (c, expression_completer);
15718
15719   add_info ("watchpoints", info_watchpoints_command, _("\
15720 Status of specified watchpoints (all watchpoints if no argument)."));
15721
15722   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15723      respond to changes - contrary to the description.  */
15724   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15725                             &can_use_hw_watchpoints, _("\
15726 Set debugger's willingness to use watchpoint hardware."), _("\
15727 Show debugger's willingness to use watchpoint hardware."), _("\
15728 If zero, gdb will not use hardware for new watchpoints, even if\n\
15729 such is available.  (However, any hardware watchpoints that were\n\
15730 created before setting this to nonzero, will continue to use watchpoint\n\
15731 hardware.)"),
15732                             NULL,
15733                             show_can_use_hw_watchpoints,
15734                             &setlist, &showlist);
15735
15736   can_use_hw_watchpoints = 1;
15737
15738   /* Tracepoint manipulation commands.  */
15739
15740   c = add_com ("trace", class_breakpoint, trace_command, _("\
15741 Set a tracepoint at specified location.\n\
15742 \n"
15743 BREAK_ARGS_HELP ("trace") "\n\
15744 Do \"help tracepoints\" for info on other tracepoint commands."));
15745   set_cmd_completer (c, location_completer);
15746
15747   add_com_alias ("tp", "trace", class_alias, 0);
15748   add_com_alias ("tr", "trace", class_alias, 1);
15749   add_com_alias ("tra", "trace", class_alias, 1);
15750   add_com_alias ("trac", "trace", class_alias, 1);
15751
15752   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15753 Set a fast tracepoint at specified location.\n\
15754 \n"
15755 BREAK_ARGS_HELP ("ftrace") "\n\
15756 Do \"help tracepoints\" for info on other tracepoint commands."));
15757   set_cmd_completer (c, location_completer);
15758
15759   c = add_com ("strace", class_breakpoint, strace_command, _("\
15760 Set a static tracepoint at location or marker.\n\
15761 \n\
15762 strace [LOCATION] [if CONDITION]\n\
15763 LOCATION may be a linespec, explicit, or address location (described below) \n\
15764 or -m MARKER_ID.\n\n\
15765 If a marker id is specified, probe the marker with that name.  With\n\
15766 no LOCATION, uses current execution address of the selected stack frame.\n\
15767 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15768 This collects arbitrary user data passed in the probe point call to the\n\
15769 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15770 by printing the $_sdata variable like any other convenience variable.\n\
15771 \n\
15772 CONDITION is a boolean expression.\n\
15773 \n" LOCATION_HELP_STRING "\n\n\
15774 Multiple tracepoints at one place are permitted, and useful if their\n\
15775 conditions are different.\n\
15776 \n\
15777 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15778 Do \"help tracepoints\" for info on other tracepoint commands."));
15779   set_cmd_completer (c, location_completer);
15780
15781   add_info ("tracepoints", info_tracepoints_command, _("\
15782 Status of specified tracepoints (all tracepoints if no argument).\n\
15783 Convenience variable \"$tpnum\" contains the number of the\n\
15784 last tracepoint set."));
15785
15786   add_info_alias ("tp", "tracepoints", 1);
15787
15788   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15789 Delete specified tracepoints.\n\
15790 Arguments are tracepoint numbers, separated by spaces.\n\
15791 No argument means delete all tracepoints."),
15792            &deletelist);
15793   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
15794
15795   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15796 Disable specified tracepoints.\n\
15797 Arguments are tracepoint numbers, separated by spaces.\n\
15798 No argument means disable all tracepoints."),
15799            &disablelist);
15800   deprecate_cmd (c, "disable");
15801
15802   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15803 Enable specified tracepoints.\n\
15804 Arguments are tracepoint numbers, separated by spaces.\n\
15805 No argument means enable all tracepoints."),
15806            &enablelist);
15807   deprecate_cmd (c, "enable");
15808
15809   add_com ("passcount", class_trace, trace_pass_command, _("\
15810 Set the passcount for a tracepoint.\n\
15811 The trace will end when the tracepoint has been passed 'count' times.\n\
15812 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15813 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
15814
15815   add_prefix_cmd ("save", class_breakpoint, save_command,
15816                   _("Save breakpoint definitions as a script."),
15817                   &save_cmdlist, "save ",
15818                   0/*allow-unknown*/, &cmdlist);
15819
15820   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
15821 Save current breakpoint definitions as a script.\n\
15822 This includes all types of breakpoints (breakpoints, watchpoints,\n\
15823 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
15824 session to restore them."),
15825                &save_cmdlist);
15826   set_cmd_completer (c, filename_completer);
15827
15828   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
15829 Save current tracepoint definitions as a script.\n\
15830 Use the 'source' command in another debug session to restore them."),
15831                &save_cmdlist);
15832   set_cmd_completer (c, filename_completer);
15833
15834   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
15835   deprecate_cmd (c, "save tracepoints");
15836
15837   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
15838 Breakpoint specific settings\n\
15839 Configure various breakpoint-specific variables such as\n\
15840 pending breakpoint behavior"),
15841                   &breakpoint_set_cmdlist, "set breakpoint ",
15842                   0/*allow-unknown*/, &setlist);
15843   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
15844 Breakpoint specific settings\n\
15845 Configure various breakpoint-specific variables such as\n\
15846 pending breakpoint behavior"),
15847                   &breakpoint_show_cmdlist, "show breakpoint ",
15848                   0/*allow-unknown*/, &showlist);
15849
15850   add_setshow_auto_boolean_cmd ("pending", no_class,
15851                                 &pending_break_support, _("\
15852 Set debugger's behavior regarding pending breakpoints."), _("\
15853 Show debugger's behavior regarding pending breakpoints."), _("\
15854 If on, an unrecognized breakpoint location will cause gdb to create a\n\
15855 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
15856 an error.  If auto, an unrecognized breakpoint location results in a\n\
15857 user-query to see if a pending breakpoint should be created."),
15858                                 NULL,
15859                                 show_pending_break_support,
15860                                 &breakpoint_set_cmdlist,
15861                                 &breakpoint_show_cmdlist);
15862
15863   pending_break_support = AUTO_BOOLEAN_AUTO;
15864
15865   add_setshow_boolean_cmd ("auto-hw", no_class,
15866                            &automatic_hardware_breakpoints, _("\
15867 Set automatic usage of hardware breakpoints."), _("\
15868 Show automatic usage of hardware breakpoints."), _("\
15869 If set, the debugger will automatically use hardware breakpoints for\n\
15870 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
15871 a warning will be emitted for such breakpoints."),
15872                            NULL,
15873                            show_automatic_hardware_breakpoints,
15874                            &breakpoint_set_cmdlist,
15875                            &breakpoint_show_cmdlist);
15876
15877   add_setshow_boolean_cmd ("always-inserted", class_support,
15878                            &always_inserted_mode, _("\
15879 Set mode for inserting breakpoints."), _("\
15880 Show mode for inserting breakpoints."), _("\
15881 When this mode is on, breakpoints are inserted immediately as soon as\n\
15882 they're created, kept inserted even when execution stops, and removed\n\
15883 only when the user deletes them.  When this mode is off (the default),\n\
15884 breakpoints are inserted only when execution continues, and removed\n\
15885 when execution stops."),
15886                                 NULL,
15887                                 &show_always_inserted_mode,
15888                                 &breakpoint_set_cmdlist,
15889                                 &breakpoint_show_cmdlist);
15890
15891   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
15892                         condition_evaluation_enums,
15893                         &condition_evaluation_mode_1, _("\
15894 Set mode of breakpoint condition evaluation."), _("\
15895 Show mode of breakpoint condition evaluation."), _("\
15896 When this is set to \"host\", breakpoint conditions will be\n\
15897 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
15898 breakpoint conditions will be downloaded to the target (if the target\n\
15899 supports such feature) and conditions will be evaluated on the target's side.\n\
15900 If this is set to \"auto\" (default), this will be automatically set to\n\
15901 \"target\" if it supports condition evaluation, otherwise it will\n\
15902 be set to \"gdb\""),
15903                            &set_condition_evaluation_mode,
15904                            &show_condition_evaluation_mode,
15905                            &breakpoint_set_cmdlist,
15906                            &breakpoint_show_cmdlist);
15907
15908   add_com ("break-range", class_breakpoint, break_range_command, _("\
15909 Set a breakpoint for an address range.\n\
15910 break-range START-LOCATION, END-LOCATION\n\
15911 where START-LOCATION and END-LOCATION can be one of the following:\n\
15912   LINENUM, for that line in the current file,\n\
15913   FILE:LINENUM, for that line in that file,\n\
15914   +OFFSET, for that number of lines after the current line\n\
15915            or the start of the range\n\
15916   FUNCTION, for the first line in that function,\n\
15917   FILE:FUNCTION, to distinguish among like-named static functions.\n\
15918   *ADDRESS, for the instruction at that address.\n\
15919 \n\
15920 The breakpoint will stop execution of the inferior whenever it executes\n\
15921 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
15922 range (including START-LOCATION and END-LOCATION)."));
15923
15924   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
15925 Set a dynamic printf at specified location.\n\
15926 dprintf location,format string,arg1,arg2,...\n\
15927 location may be a linespec, explicit, or address location.\n"
15928 "\n" LOCATION_HELP_STRING));
15929   set_cmd_completer (c, location_completer);
15930
15931   add_setshow_enum_cmd ("dprintf-style", class_support,
15932                         dprintf_style_enums, &dprintf_style, _("\
15933 Set the style of usage for dynamic printf."), _("\
15934 Show the style of usage for dynamic printf."), _("\
15935 This setting chooses how GDB will do a dynamic printf.\n\
15936 If the value is \"gdb\", then the printing is done by GDB to its own\n\
15937 console, as with the \"printf\" command.\n\
15938 If the value is \"call\", the print is done by calling a function in your\n\
15939 program; by default printf(), but you can choose a different function or\n\
15940 output stream by setting dprintf-function and dprintf-channel."),
15941                         update_dprintf_commands, NULL,
15942                         &setlist, &showlist);
15943
15944   dprintf_function = xstrdup ("printf");
15945   add_setshow_string_cmd ("dprintf-function", class_support,
15946                           &dprintf_function, _("\
15947 Set the function to use for dynamic printf"), _("\
15948 Show the function to use for dynamic printf"), NULL,
15949                           update_dprintf_commands, NULL,
15950                           &setlist, &showlist);
15951
15952   dprintf_channel = xstrdup ("");
15953   add_setshow_string_cmd ("dprintf-channel", class_support,
15954                           &dprintf_channel, _("\
15955 Set the channel to use for dynamic printf"), _("\
15956 Show the channel to use for dynamic printf"), NULL,
15957                           update_dprintf_commands, NULL,
15958                           &setlist, &showlist);
15959
15960   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
15961                            &disconnected_dprintf, _("\
15962 Set whether dprintf continues after GDB disconnects."), _("\
15963 Show whether dprintf continues after GDB disconnects."), _("\
15964 Use this to let dprintf commands continue to hit and produce output\n\
15965 even if GDB disconnects or detaches from the target."),
15966                            NULL,
15967                            NULL,
15968                            &setlist, &showlist);
15969
15970   add_com ("agent-printf", class_vars, agent_printf_command, _("\
15971 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
15972 (target agent only) This is useful for formatted output in user-defined commands."));
15973
15974   automatic_hardware_breakpoints = 1;
15975
15976   gdb::observers::about_to_proceed.attach (breakpoint_about_to_proceed);
15977   gdb::observers::thread_exit.attach (remove_threaded_breakpoints);
15978 }