Remove "struct" keyword in range-based for loops
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2018 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "infrun.h"
36 #include "gdbthread.h"
37 #include "target.h"
38 #include "language.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "ui-out.h"
48 #include "cli/cli-script.h"
49 #include "block.h"
50 #include "solib.h"
51 #include "solist.h"
52 #include "observable.h"
53 #include "memattr.h"
54 #include "ada-lang.h"
55 #include "top.h"
56 #include "valprint.h"
57 #include "jit.h"
58 #include "parser-defs.h"
59 #include "gdb_regex.h"
60 #include "probe.h"
61 #include "cli/cli-utils.h"
62 #include "continuations.h"
63 #include "stack.h"
64 #include "skip.h"
65 #include "ax-gdb.h"
66 #include "dummy-frame.h"
67 #include "interps.h"
68 #include "format.h"
69 #include "thread-fsm.h"
70 #include "tid-parse.h"
71
72 /* readline include files */
73 #include "readline/readline.h"
74 #include "readline/history.h"
75
76 /* readline defines this.  */
77 #undef savestring
78
79 #include "mi/mi-common.h"
80 #include "extension.h"
81 #include <algorithm>
82 #include "progspace-and-thread.h"
83 #include "common/array-view.h"
84 #include "common/gdb_optional.h"
85
86 /* Enums for exception-handling support.  */
87 enum exception_event_kind
88 {
89   EX_EVENT_THROW,
90   EX_EVENT_RETHROW,
91   EX_EVENT_CATCH
92 };
93
94 /* Prototypes for local functions.  */
95
96 static void map_breakpoint_numbers (const char *,
97                                     gdb::function_view<void (breakpoint *)>);
98
99 static void breakpoint_re_set_default (struct breakpoint *);
100
101 static void
102   create_sals_from_location_default (const struct event_location *location,
103                                      struct linespec_result *canonical,
104                                      enum bptype type_wanted);
105
106 static void create_breakpoints_sal_default (struct gdbarch *,
107                                             struct linespec_result *,
108                                             gdb::unique_xmalloc_ptr<char>,
109                                             gdb::unique_xmalloc_ptr<char>,
110                                             enum bptype,
111                                             enum bpdisp, int, int,
112                                             int,
113                                             const struct breakpoint_ops *,
114                                             int, int, int, unsigned);
115
116 static std::vector<symtab_and_line> decode_location_default
117   (struct breakpoint *b, const struct event_location *location,
118    struct program_space *search_pspace);
119
120 static int can_use_hardware_watchpoint
121     (const std::vector<value_ref_ptr> &vals);
122
123 static void mention (struct breakpoint *);
124
125 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
126                                                                enum bptype,
127                                                                const struct breakpoint_ops *);
128 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
129                                                        const struct symtab_and_line *);
130
131 /* This function is used in gdbtk sources and thus can not be made
132    static.  */
133 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
134                                        struct symtab_and_line,
135                                        enum bptype,
136                                        const struct breakpoint_ops *);
137
138 static struct breakpoint *
139   momentary_breakpoint_from_master (struct breakpoint *orig,
140                                     enum bptype type,
141                                     const struct breakpoint_ops *ops,
142                                     int loc_enabled);
143
144 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
145
146 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
147                                             CORE_ADDR bpaddr,
148                                             enum bptype bptype);
149
150 static void describe_other_breakpoints (struct gdbarch *,
151                                         struct program_space *, CORE_ADDR,
152                                         struct obj_section *, int);
153
154 static int watchpoint_locations_match (struct bp_location *loc1,
155                                        struct bp_location *loc2);
156
157 static int breakpoint_location_address_match (struct bp_location *bl,
158                                               const struct address_space *aspace,
159                                               CORE_ADDR addr);
160
161 static int breakpoint_location_address_range_overlap (struct bp_location *,
162                                                       const address_space *,
163                                                       CORE_ADDR, int);
164
165 static int remove_breakpoint (struct bp_location *);
166 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
167
168 static enum print_stop_action print_bp_stop_message (bpstat bs);
169
170 static int hw_breakpoint_used_count (void);
171
172 static int hw_watchpoint_use_count (struct breakpoint *);
173
174 static int hw_watchpoint_used_count_others (struct breakpoint *except,
175                                             enum bptype type,
176                                             int *other_type_used);
177
178 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
179                                     int count);
180
181 static void free_bp_location (struct bp_location *loc);
182 static void incref_bp_location (struct bp_location *loc);
183 static void decref_bp_location (struct bp_location **loc);
184
185 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
186
187 /* update_global_location_list's modes of operation wrt to whether to
188    insert locations now.  */
189 enum ugll_insert_mode
190 {
191   /* Don't insert any breakpoint locations into the inferior, only
192      remove already-inserted locations that no longer should be
193      inserted.  Functions that delete a breakpoint or breakpoints
194      should specify this mode, so that deleting a breakpoint doesn't
195      have the side effect of inserting the locations of other
196      breakpoints that are marked not-inserted, but should_be_inserted
197      returns true on them.
198
199      This behavior is useful is situations close to tear-down -- e.g.,
200      after an exec, while the target still has execution, but
201      breakpoint shadows of the previous executable image should *NOT*
202      be restored to the new image; or before detaching, where the
203      target still has execution and wants to delete breakpoints from
204      GDB's lists, and all breakpoints had already been removed from
205      the inferior.  */
206   UGLL_DONT_INSERT,
207
208   /* May insert breakpoints iff breakpoints_should_be_inserted_now
209      claims breakpoints should be inserted now.  */
210   UGLL_MAY_INSERT,
211
212   /* Insert locations now, irrespective of
213      breakpoints_should_be_inserted_now.  E.g., say all threads are
214      stopped right now, and the user did "continue".  We need to
215      insert breakpoints _before_ resuming the target, but
216      UGLL_MAY_INSERT wouldn't insert them, because
217      breakpoints_should_be_inserted_now returns false at that point,
218      as no thread is running yet.  */
219   UGLL_INSERT
220 };
221
222 static void update_global_location_list (enum ugll_insert_mode);
223
224 static void update_global_location_list_nothrow (enum ugll_insert_mode);
225
226 static int is_hardware_watchpoint (const struct breakpoint *bpt);
227
228 static void insert_breakpoint_locations (void);
229
230 static void trace_pass_command (const char *, int);
231
232 static void set_tracepoint_count (int num);
233
234 static int is_masked_watchpoint (const struct breakpoint *b);
235
236 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
237
238 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
239    otherwise.  */
240
241 static int strace_marker_p (struct breakpoint *b);
242
243 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
244    that are implemented on top of software or hardware breakpoints
245    (user breakpoints, internal and momentary breakpoints, etc.).  */
246 static struct breakpoint_ops bkpt_base_breakpoint_ops;
247
248 /* Internal breakpoints class type.  */
249 static struct breakpoint_ops internal_breakpoint_ops;
250
251 /* Momentary breakpoints class type.  */
252 static struct breakpoint_ops momentary_breakpoint_ops;
253
254 /* The breakpoint_ops structure to be used in regular user created
255    breakpoints.  */
256 struct breakpoint_ops bkpt_breakpoint_ops;
257
258 /* Breakpoints set on probes.  */
259 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
260
261 /* Dynamic printf class type.  */
262 struct breakpoint_ops dprintf_breakpoint_ops;
263
264 /* The style in which to perform a dynamic printf.  This is a user
265    option because different output options have different tradeoffs;
266    if GDB does the printing, there is better error handling if there
267    is a problem with any of the arguments, but using an inferior
268    function lets you have special-purpose printers and sending of
269    output to the same place as compiled-in print functions.  */
270
271 static const char dprintf_style_gdb[] = "gdb";
272 static const char dprintf_style_call[] = "call";
273 static const char dprintf_style_agent[] = "agent";
274 static const char *const dprintf_style_enums[] = {
275   dprintf_style_gdb,
276   dprintf_style_call,
277   dprintf_style_agent,
278   NULL
279 };
280 static const char *dprintf_style = dprintf_style_gdb;
281
282 /* The function to use for dynamic printf if the preferred style is to
283    call into the inferior.  The value is simply a string that is
284    copied into the command, so it can be anything that GDB can
285    evaluate to a callable address, not necessarily a function name.  */
286
287 static char *dprintf_function;
288
289 /* The channel to use for dynamic printf if the preferred style is to
290    call into the inferior; if a nonempty string, it will be passed to
291    the call as the first argument, with the format string as the
292    second.  As with the dprintf function, this can be anything that
293    GDB knows how to evaluate, so in addition to common choices like
294    "stderr", this could be an app-specific expression like
295    "mystreams[curlogger]".  */
296
297 static char *dprintf_channel;
298
299 /* True if dprintf commands should continue to operate even if GDB
300    has disconnected.  */
301 static int disconnected_dprintf = 1;
302
303 struct command_line *
304 breakpoint_commands (struct breakpoint *b)
305 {
306   return b->commands ? b->commands.get () : NULL;
307 }
308
309 /* Flag indicating that a command has proceeded the inferior past the
310    current breakpoint.  */
311
312 static int breakpoint_proceeded;
313
314 const char *
315 bpdisp_text (enum bpdisp disp)
316 {
317   /* NOTE: the following values are a part of MI protocol and
318      represent values of 'disp' field returned when inferior stops at
319      a breakpoint.  */
320   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
321
322   return bpdisps[(int) disp];
323 }
324
325 /* Prototypes for exported functions.  */
326 /* If FALSE, gdb will not use hardware support for watchpoints, even
327    if such is available.  */
328 static int can_use_hw_watchpoints;
329
330 static void
331 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
332                              struct cmd_list_element *c,
333                              const char *value)
334 {
335   fprintf_filtered (file,
336                     _("Debugger's willingness to use "
337                       "watchpoint hardware is %s.\n"),
338                     value);
339 }
340
341 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
342    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
343    for unrecognized breakpoint locations.
344    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
345 static enum auto_boolean pending_break_support;
346 static void
347 show_pending_break_support (struct ui_file *file, int from_tty,
348                             struct cmd_list_element *c,
349                             const char *value)
350 {
351   fprintf_filtered (file,
352                     _("Debugger's behavior regarding "
353                       "pending breakpoints is %s.\n"),
354                     value);
355 }
356
357 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
358    set with "break" but falling in read-only memory.
359    If 0, gdb will warn about such breakpoints, but won't automatically
360    use hardware breakpoints.  */
361 static int automatic_hardware_breakpoints;
362 static void
363 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
364                                      struct cmd_list_element *c,
365                                      const char *value)
366 {
367   fprintf_filtered (file,
368                     _("Automatic usage of hardware breakpoints is %s.\n"),
369                     value);
370 }
371
372 /* If on, GDB keeps breakpoints inserted even if the inferior is
373    stopped, and immediately inserts any new breakpoints as soon as
374    they're created.  If off (default), GDB keeps breakpoints off of
375    the target as long as possible.  That is, it delays inserting
376    breakpoints until the next resume, and removes them again when the
377    target fully stops.  This is a bit safer in case GDB crashes while
378    processing user input.  */
379 static int always_inserted_mode = 0;
380
381 static void
382 show_always_inserted_mode (struct ui_file *file, int from_tty,
383                      struct cmd_list_element *c, const char *value)
384 {
385   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
386                     value);
387 }
388
389 /* See breakpoint.h.  */
390
391 int
392 breakpoints_should_be_inserted_now (void)
393 {
394   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
395     {
396       /* If breakpoints are global, they should be inserted even if no
397          thread under gdb's control is running, or even if there are
398          no threads under GDB's control yet.  */
399       return 1;
400     }
401   else if (target_has_execution)
402     {
403       struct thread_info *tp;
404
405       if (always_inserted_mode)
406         {
407           /* The user wants breakpoints inserted even if all threads
408              are stopped.  */
409           return 1;
410         }
411
412       if (threads_are_executing ())
413         return 1;
414
415       /* Don't remove breakpoints yet if, even though all threads are
416          stopped, we still have events to process.  */
417       ALL_NON_EXITED_THREADS (tp)
418         if (tp->resumed
419             && tp->suspend.waitstatus_pending_p)
420           return 1;
421     }
422   return 0;
423 }
424
425 static const char condition_evaluation_both[] = "host or target";
426
427 /* Modes for breakpoint condition evaluation.  */
428 static const char condition_evaluation_auto[] = "auto";
429 static const char condition_evaluation_host[] = "host";
430 static const char condition_evaluation_target[] = "target";
431 static const char *const condition_evaluation_enums[] = {
432   condition_evaluation_auto,
433   condition_evaluation_host,
434   condition_evaluation_target,
435   NULL
436 };
437
438 /* Global that holds the current mode for breakpoint condition evaluation.  */
439 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
440
441 /* Global that we use to display information to the user (gets its value from
442    condition_evaluation_mode_1.  */
443 static const char *condition_evaluation_mode = condition_evaluation_auto;
444
445 /* Translate a condition evaluation mode MODE into either "host"
446    or "target".  This is used mostly to translate from "auto" to the
447    real setting that is being used.  It returns the translated
448    evaluation mode.  */
449
450 static const char *
451 translate_condition_evaluation_mode (const char *mode)
452 {
453   if (mode == condition_evaluation_auto)
454     {
455       if (target_supports_evaluation_of_breakpoint_conditions ())
456         return condition_evaluation_target;
457       else
458         return condition_evaluation_host;
459     }
460   else
461     return mode;
462 }
463
464 /* Discovers what condition_evaluation_auto translates to.  */
465
466 static const char *
467 breakpoint_condition_evaluation_mode (void)
468 {
469   return translate_condition_evaluation_mode (condition_evaluation_mode);
470 }
471
472 /* Return true if GDB should evaluate breakpoint conditions or false
473    otherwise.  */
474
475 static int
476 gdb_evaluates_breakpoint_condition_p (void)
477 {
478   const char *mode = breakpoint_condition_evaluation_mode ();
479
480   return (mode == condition_evaluation_host);
481 }
482
483 /* Are we executing breakpoint commands?  */
484 static int executing_breakpoint_commands;
485
486 /* Are overlay event breakpoints enabled? */
487 static int overlay_events_enabled;
488
489 /* See description in breakpoint.h. */
490 int target_exact_watchpoints = 0;
491
492 /* Walk the following statement or block through all breakpoints.
493    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
494    current breakpoint.  */
495
496 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
497
498 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
499         for (B = breakpoint_chain;      \
500              B ? (TMP=B->next, 1): 0;   \
501              B = TMP)
502
503 /* Similar iterator for the low-level breakpoints.  SAFE variant is
504    not provided so update_global_location_list must not be called
505    while executing the block of ALL_BP_LOCATIONS.  */
506
507 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
508         for (BP_TMP = bp_locations;                                     \
509              BP_TMP < bp_locations + bp_locations_count && (B = *BP_TMP);\
510              BP_TMP++)
511
512 /* Iterates through locations with address ADDRESS for the currently selected
513    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
514    to where the loop should start from.
515    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
516    appropriate location to start with.  */
517
518 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
519         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
520              BP_LOCP_TMP = BP_LOCP_START;                               \
521              BP_LOCP_START                                              \
522              && (BP_LOCP_TMP < bp_locations + bp_locations_count        \
523              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
524              BP_LOCP_TMP++)
525
526 /* Iterator for tracepoints only.  */
527
528 #define ALL_TRACEPOINTS(B)  \
529   for (B = breakpoint_chain; B; B = B->next)  \
530     if (is_tracepoint (B))
531
532 /* Chains of all breakpoints defined.  */
533
534 struct breakpoint *breakpoint_chain;
535
536 /* Array is sorted by bp_locations_compare - primarily by the ADDRESS.  */
537
538 static struct bp_location **bp_locations;
539
540 /* Number of elements of BP_LOCATIONS.  */
541
542 static unsigned bp_locations_count;
543
544 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
545    ADDRESS for the current elements of BP_LOCATIONS which get a valid
546    result from bp_location_has_shadow.  You can use it for roughly
547    limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
548    an address you need to read.  */
549
550 static CORE_ADDR bp_locations_placed_address_before_address_max;
551
552 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
553    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
554    BP_LOCATIONS which get a valid result from bp_location_has_shadow.
555    You can use it for roughly limiting the subrange of BP_LOCATIONS to
556    scan for shadow bytes for an address you need to read.  */
557
558 static CORE_ADDR bp_locations_shadow_len_after_address_max;
559
560 /* The locations that no longer correspond to any breakpoint, unlinked
561    from the bp_locations array, but for which a hit may still be
562    reported by a target.  */
563 VEC(bp_location_p) *moribund_locations = NULL;
564
565 /* Number of last breakpoint made.  */
566
567 static int breakpoint_count;
568
569 /* The value of `breakpoint_count' before the last command that
570    created breakpoints.  If the last (break-like) command created more
571    than one breakpoint, then the difference between BREAKPOINT_COUNT
572    and PREV_BREAKPOINT_COUNT is more than one.  */
573 static int prev_breakpoint_count;
574
575 /* Number of last tracepoint made.  */
576
577 static int tracepoint_count;
578
579 static struct cmd_list_element *breakpoint_set_cmdlist;
580 static struct cmd_list_element *breakpoint_show_cmdlist;
581 struct cmd_list_element *save_cmdlist;
582
583 /* See declaration at breakpoint.h.  */
584
585 struct breakpoint *
586 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
587                     void *user_data)
588 {
589   struct breakpoint *b = NULL;
590
591   ALL_BREAKPOINTS (b)
592     {
593       if (func (b, user_data) != 0)
594         break;
595     }
596
597   return b;
598 }
599
600 /* Return whether a breakpoint is an active enabled breakpoint.  */
601 static int
602 breakpoint_enabled (struct breakpoint *b)
603 {
604   return (b->enable_state == bp_enabled);
605 }
606
607 /* Set breakpoint count to NUM.  */
608
609 static void
610 set_breakpoint_count (int num)
611 {
612   prev_breakpoint_count = breakpoint_count;
613   breakpoint_count = num;
614   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
615 }
616
617 /* Used by `start_rbreak_breakpoints' below, to record the current
618    breakpoint count before "rbreak" creates any breakpoint.  */
619 static int rbreak_start_breakpoint_count;
620
621 /* Called at the start an "rbreak" command to record the first
622    breakpoint made.  */
623
624 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
625 {
626   rbreak_start_breakpoint_count = breakpoint_count;
627 }
628
629 /* Called at the end of an "rbreak" command to record the last
630    breakpoint made.  */
631
632 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
633 {
634   prev_breakpoint_count = rbreak_start_breakpoint_count;
635 }
636
637 /* Used in run_command to zero the hit count when a new run starts.  */
638
639 void
640 clear_breakpoint_hit_counts (void)
641 {
642   struct breakpoint *b;
643
644   ALL_BREAKPOINTS (b)
645     b->hit_count = 0;
646 }
647
648 \f
649 /* Return the breakpoint with the specified number, or NULL
650    if the number does not refer to an existing breakpoint.  */
651
652 struct breakpoint *
653 get_breakpoint (int num)
654 {
655   struct breakpoint *b;
656
657   ALL_BREAKPOINTS (b)
658     if (b->number == num)
659       return b;
660   
661   return NULL;
662 }
663
664 \f
665
666 /* Mark locations as "conditions have changed" in case the target supports
667    evaluating conditions on its side.  */
668
669 static void
670 mark_breakpoint_modified (struct breakpoint *b)
671 {
672   struct bp_location *loc;
673
674   /* This is only meaningful if the target is
675      evaluating conditions and if the user has
676      opted for condition evaluation on the target's
677      side.  */
678   if (gdb_evaluates_breakpoint_condition_p ()
679       || !target_supports_evaluation_of_breakpoint_conditions ())
680     return;
681
682   if (!is_breakpoint (b))
683     return;
684
685   for (loc = b->loc; loc; loc = loc->next)
686     loc->condition_changed = condition_modified;
687 }
688
689 /* Mark location as "conditions have changed" in case the target supports
690    evaluating conditions on its side.  */
691
692 static void
693 mark_breakpoint_location_modified (struct bp_location *loc)
694 {
695   /* This is only meaningful if the target is
696      evaluating conditions and if the user has
697      opted for condition evaluation on the target's
698      side.  */
699   if (gdb_evaluates_breakpoint_condition_p ()
700       || !target_supports_evaluation_of_breakpoint_conditions ())
701
702     return;
703
704   if (!is_breakpoint (loc->owner))
705     return;
706
707   loc->condition_changed = condition_modified;
708 }
709
710 /* Sets the condition-evaluation mode using the static global
711    condition_evaluation_mode.  */
712
713 static void
714 set_condition_evaluation_mode (const char *args, int from_tty,
715                                struct cmd_list_element *c)
716 {
717   const char *old_mode, *new_mode;
718
719   if ((condition_evaluation_mode_1 == condition_evaluation_target)
720       && !target_supports_evaluation_of_breakpoint_conditions ())
721     {
722       condition_evaluation_mode_1 = condition_evaluation_mode;
723       warning (_("Target does not support breakpoint condition evaluation.\n"
724                  "Using host evaluation mode instead."));
725       return;
726     }
727
728   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
729   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
730
731   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
732      settings was "auto".  */
733   condition_evaluation_mode = condition_evaluation_mode_1;
734
735   /* Only update the mode if the user picked a different one.  */
736   if (new_mode != old_mode)
737     {
738       struct bp_location *loc, **loc_tmp;
739       /* If the user switched to a different evaluation mode, we
740          need to synch the changes with the target as follows:
741
742          "host" -> "target": Send all (valid) conditions to the target.
743          "target" -> "host": Remove all the conditions from the target.
744       */
745
746       if (new_mode == condition_evaluation_target)
747         {
748           /* Mark everything modified and synch conditions with the
749              target.  */
750           ALL_BP_LOCATIONS (loc, loc_tmp)
751             mark_breakpoint_location_modified (loc);
752         }
753       else
754         {
755           /* Manually mark non-duplicate locations to synch conditions
756              with the target.  We do this to remove all the conditions the
757              target knows about.  */
758           ALL_BP_LOCATIONS (loc, loc_tmp)
759             if (is_breakpoint (loc->owner) && loc->inserted)
760               loc->needs_update = 1;
761         }
762
763       /* Do the update.  */
764       update_global_location_list (UGLL_MAY_INSERT);
765     }
766
767   return;
768 }
769
770 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
771    what "auto" is translating to.  */
772
773 static void
774 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
775                                 struct cmd_list_element *c, const char *value)
776 {
777   if (condition_evaluation_mode == condition_evaluation_auto)
778     fprintf_filtered (file,
779                       _("Breakpoint condition evaluation "
780                         "mode is %s (currently %s).\n"),
781                       value,
782                       breakpoint_condition_evaluation_mode ());
783   else
784     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
785                       value);
786 }
787
788 /* A comparison function for bp_location AP and BP that is used by
789    bsearch.  This comparison function only cares about addresses, unlike
790    the more general bp_locations_compare function.  */
791
792 static int
793 bp_locations_compare_addrs (const void *ap, const void *bp)
794 {
795   const struct bp_location *a = *(const struct bp_location **) ap;
796   const struct bp_location *b = *(const struct bp_location **) bp;
797
798   if (a->address == b->address)
799     return 0;
800   else
801     return ((a->address > b->address) - (a->address < b->address));
802 }
803
804 /* Helper function to skip all bp_locations with addresses
805    less than ADDRESS.  It returns the first bp_location that
806    is greater than or equal to ADDRESS.  If none is found, just
807    return NULL.  */
808
809 static struct bp_location **
810 get_first_locp_gte_addr (CORE_ADDR address)
811 {
812   struct bp_location dummy_loc;
813   struct bp_location *dummy_locp = &dummy_loc;
814   struct bp_location **locp_found = NULL;
815
816   /* Initialize the dummy location's address field.  */
817   dummy_loc.address = address;
818
819   /* Find a close match to the first location at ADDRESS.  */
820   locp_found = ((struct bp_location **)
821                 bsearch (&dummy_locp, bp_locations, bp_locations_count,
822                          sizeof (struct bp_location **),
823                          bp_locations_compare_addrs));
824
825   /* Nothing was found, nothing left to do.  */
826   if (locp_found == NULL)
827     return NULL;
828
829   /* We may have found a location that is at ADDRESS but is not the first in the
830      location's list.  Go backwards (if possible) and locate the first one.  */
831   while ((locp_found - 1) >= bp_locations
832          && (*(locp_found - 1))->address == address)
833     locp_found--;
834
835   return locp_found;
836 }
837
838 void
839 set_breakpoint_condition (struct breakpoint *b, const char *exp,
840                           int from_tty)
841 {
842   xfree (b->cond_string);
843   b->cond_string = NULL;
844
845   if (is_watchpoint (b))
846     {
847       struct watchpoint *w = (struct watchpoint *) b;
848
849       w->cond_exp.reset ();
850     }
851   else
852     {
853       struct bp_location *loc;
854
855       for (loc = b->loc; loc; loc = loc->next)
856         {
857           loc->cond.reset ();
858
859           /* No need to free the condition agent expression
860              bytecode (if we have one).  We will handle this
861              when we go through update_global_location_list.  */
862         }
863     }
864
865   if (*exp == 0)
866     {
867       if (from_tty)
868         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
869     }
870   else
871     {
872       const char *arg = exp;
873
874       /* I don't know if it matters whether this is the string the user
875          typed in or the decompiled expression.  */
876       b->cond_string = xstrdup (arg);
877       b->condition_not_parsed = 0;
878
879       if (is_watchpoint (b))
880         {
881           struct watchpoint *w = (struct watchpoint *) b;
882
883           innermost_block.reset ();
884           arg = exp;
885           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
886           if (*arg)
887             error (_("Junk at end of expression"));
888           w->cond_exp_valid_block = innermost_block.block ();
889         }
890       else
891         {
892           struct bp_location *loc;
893
894           for (loc = b->loc; loc; loc = loc->next)
895             {
896               arg = exp;
897               loc->cond =
898                 parse_exp_1 (&arg, loc->address,
899                              block_for_pc (loc->address), 0);
900               if (*arg)
901                 error (_("Junk at end of expression"));
902             }
903         }
904     }
905   mark_breakpoint_modified (b);
906
907   gdb::observers::breakpoint_modified.notify (b);
908 }
909
910 /* Completion for the "condition" command.  */
911
912 static void
913 condition_completer (struct cmd_list_element *cmd,
914                      completion_tracker &tracker,
915                      const char *text, const char *word)
916 {
917   const char *space;
918
919   text = skip_spaces (text);
920   space = skip_to_space (text);
921   if (*space == '\0')
922     {
923       int len;
924       struct breakpoint *b;
925
926       if (text[0] == '$')
927         {
928           /* We don't support completion of history indices.  */
929           if (!isdigit (text[1]))
930             complete_internalvar (tracker, &text[1]);
931           return;
932         }
933
934       /* We're completing the breakpoint number.  */
935       len = strlen (text);
936
937       ALL_BREAKPOINTS (b)
938         {
939           char number[50];
940
941           xsnprintf (number, sizeof (number), "%d", b->number);
942
943           if (strncmp (number, text, len) == 0)
944             {
945               gdb::unique_xmalloc_ptr<char> copy (xstrdup (number));
946               tracker.add_completion (std::move (copy));
947             }
948         }
949
950       return;
951     }
952
953   /* We're completing the expression part.  */
954   text = skip_spaces (space);
955   expression_completer (cmd, tracker, text, word);
956 }
957
958 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
959
960 static void
961 condition_command (const char *arg, int from_tty)
962 {
963   struct breakpoint *b;
964   const char *p;
965   int bnum;
966
967   if (arg == 0)
968     error_no_arg (_("breakpoint number"));
969
970   p = arg;
971   bnum = get_number (&p);
972   if (bnum == 0)
973     error (_("Bad breakpoint argument: '%s'"), arg);
974
975   ALL_BREAKPOINTS (b)
976     if (b->number == bnum)
977       {
978         /* Check if this breakpoint has a "stop" method implemented in an
979            extension language.  This method and conditions entered into GDB
980            from the CLI are mutually exclusive.  */
981         const struct extension_language_defn *extlang
982           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
983
984         if (extlang != NULL)
985           {
986             error (_("Only one stop condition allowed.  There is currently"
987                      " a %s stop condition defined for this breakpoint."),
988                    ext_lang_capitalized_name (extlang));
989           }
990         set_breakpoint_condition (b, p, from_tty);
991
992         if (is_breakpoint (b))
993           update_global_location_list (UGLL_MAY_INSERT);
994
995         return;
996       }
997
998   error (_("No breakpoint number %d."), bnum);
999 }
1000
1001 /* Check that COMMAND do not contain commands that are suitable
1002    only for tracepoints and not suitable for ordinary breakpoints.
1003    Throw if any such commands is found.  */
1004
1005 static void
1006 check_no_tracepoint_commands (struct command_line *commands)
1007 {
1008   struct command_line *c;
1009
1010   for (c = commands; c; c = c->next)
1011     {
1012       int i;
1013
1014       if (c->control_type == while_stepping_control)
1015         error (_("The 'while-stepping' command can "
1016                  "only be used for tracepoints"));
1017
1018       check_no_tracepoint_commands (c->body_list_0.get ());
1019       check_no_tracepoint_commands (c->body_list_1.get ());
1020
1021       /* Not that command parsing removes leading whitespace and comment
1022          lines and also empty lines.  So, we only need to check for
1023          command directly.  */
1024       if (strstr (c->line, "collect ") == c->line)
1025         error (_("The 'collect' command can only be used for tracepoints"));
1026
1027       if (strstr (c->line, "teval ") == c->line)
1028         error (_("The 'teval' command can only be used for tracepoints"));
1029     }
1030 }
1031
1032 struct longjmp_breakpoint : public breakpoint
1033 {
1034   ~longjmp_breakpoint () override;
1035 };
1036
1037 /* Encapsulate tests for different types of tracepoints.  */
1038
1039 static bool
1040 is_tracepoint_type (bptype type)
1041 {
1042   return (type == bp_tracepoint
1043           || type == bp_fast_tracepoint
1044           || type == bp_static_tracepoint);
1045 }
1046
1047 static bool
1048 is_longjmp_type (bptype type)
1049 {
1050   return type == bp_longjmp || type == bp_exception;
1051 }
1052
1053 int
1054 is_tracepoint (const struct breakpoint *b)
1055 {
1056   return is_tracepoint_type (b->type);
1057 }
1058
1059 /* Factory function to create an appropriate instance of breakpoint given
1060    TYPE.  */
1061
1062 static std::unique_ptr<breakpoint>
1063 new_breakpoint_from_type (bptype type)
1064 {
1065   breakpoint *b;
1066
1067   if (is_tracepoint_type (type))
1068     b = new tracepoint ();
1069   else if (is_longjmp_type (type))
1070     b = new longjmp_breakpoint ();
1071   else
1072     b = new breakpoint ();
1073
1074   return std::unique_ptr<breakpoint> (b);
1075 }
1076
1077 /* A helper function that validates that COMMANDS are valid for a
1078    breakpoint.  This function will throw an exception if a problem is
1079    found.  */
1080
1081 static void
1082 validate_commands_for_breakpoint (struct breakpoint *b,
1083                                   struct command_line *commands)
1084 {
1085   if (is_tracepoint (b))
1086     {
1087       struct tracepoint *t = (struct tracepoint *) b;
1088       struct command_line *c;
1089       struct command_line *while_stepping = 0;
1090
1091       /* Reset the while-stepping step count.  The previous commands
1092          might have included a while-stepping action, while the new
1093          ones might not.  */
1094       t->step_count = 0;
1095
1096       /* We need to verify that each top-level element of commands is
1097          valid for tracepoints, that there's at most one
1098          while-stepping element, and that the while-stepping's body
1099          has valid tracing commands excluding nested while-stepping.
1100          We also need to validate the tracepoint action line in the
1101          context of the tracepoint --- validate_actionline actually
1102          has side effects, like setting the tracepoint's
1103          while-stepping STEP_COUNT, in addition to checking if the
1104          collect/teval actions parse and make sense in the
1105          tracepoint's context.  */
1106       for (c = commands; c; c = c->next)
1107         {
1108           if (c->control_type == while_stepping_control)
1109             {
1110               if (b->type == bp_fast_tracepoint)
1111                 error (_("The 'while-stepping' command "
1112                          "cannot be used for fast tracepoint"));
1113               else if (b->type == bp_static_tracepoint)
1114                 error (_("The 'while-stepping' command "
1115                          "cannot be used for static tracepoint"));
1116
1117               if (while_stepping)
1118                 error (_("The 'while-stepping' command "
1119                          "can be used only once"));
1120               else
1121                 while_stepping = c;
1122             }
1123
1124           validate_actionline (c->line, b);
1125         }
1126       if (while_stepping)
1127         {
1128           struct command_line *c2;
1129
1130           gdb_assert (while_stepping->body_list_1 == nullptr);
1131           c2 = while_stepping->body_list_0.get ();
1132           for (; c2; c2 = c2->next)
1133             {
1134               if (c2->control_type == while_stepping_control)
1135                 error (_("The 'while-stepping' command cannot be nested"));
1136             }
1137         }
1138     }
1139   else
1140     {
1141       check_no_tracepoint_commands (commands);
1142     }
1143 }
1144
1145 /* Return a vector of all the static tracepoints set at ADDR.  The
1146    caller is responsible for releasing the vector.  */
1147
1148 VEC(breakpoint_p) *
1149 static_tracepoints_here (CORE_ADDR addr)
1150 {
1151   struct breakpoint *b;
1152   VEC(breakpoint_p) *found = 0;
1153   struct bp_location *loc;
1154
1155   ALL_BREAKPOINTS (b)
1156     if (b->type == bp_static_tracepoint)
1157       {
1158         for (loc = b->loc; loc; loc = loc->next)
1159           if (loc->address == addr)
1160             VEC_safe_push(breakpoint_p, found, b);
1161       }
1162
1163   return found;
1164 }
1165
1166 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1167    validate that only allowed commands are included.  */
1168
1169 void
1170 breakpoint_set_commands (struct breakpoint *b, 
1171                          counted_command_line &&commands)
1172 {
1173   validate_commands_for_breakpoint (b, commands.get ());
1174
1175   b->commands = std::move (commands);
1176   gdb::observers::breakpoint_modified.notify (b);
1177 }
1178
1179 /* Set the internal `silent' flag on the breakpoint.  Note that this
1180    is not the same as the "silent" that may appear in the breakpoint's
1181    commands.  */
1182
1183 void
1184 breakpoint_set_silent (struct breakpoint *b, int silent)
1185 {
1186   int old_silent = b->silent;
1187
1188   b->silent = silent;
1189   if (old_silent != silent)
1190     gdb::observers::breakpoint_modified.notify (b);
1191 }
1192
1193 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1194    breakpoint work for any thread.  */
1195
1196 void
1197 breakpoint_set_thread (struct breakpoint *b, int thread)
1198 {
1199   int old_thread = b->thread;
1200
1201   b->thread = thread;
1202   if (old_thread != thread)
1203     gdb::observers::breakpoint_modified.notify (b);
1204 }
1205
1206 /* Set the task for this breakpoint.  If TASK is 0, make the
1207    breakpoint work for any task.  */
1208
1209 void
1210 breakpoint_set_task (struct breakpoint *b, int task)
1211 {
1212   int old_task = b->task;
1213
1214   b->task = task;
1215   if (old_task != task)
1216     gdb::observers::breakpoint_modified.notify (b);
1217 }
1218
1219 static void
1220 commands_command_1 (const char *arg, int from_tty,
1221                     struct command_line *control)
1222 {
1223   counted_command_line cmd;
1224
1225   std::string new_arg;
1226
1227   if (arg == NULL || !*arg)
1228     {
1229       if (breakpoint_count - prev_breakpoint_count > 1)
1230         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1231                                  breakpoint_count);
1232       else if (breakpoint_count > 0)
1233         new_arg = string_printf ("%d", breakpoint_count);
1234       arg = new_arg.c_str ();
1235     }
1236
1237   map_breakpoint_numbers
1238     (arg, [&] (breakpoint *b)
1239      {
1240        if (cmd == NULL)
1241          {
1242            if (control != NULL)
1243              cmd = control->body_list_0;
1244            else
1245              {
1246                std::string str
1247                  = string_printf (_("Type commands for breakpoint(s) "
1248                                     "%s, one per line."),
1249                                   arg);
1250
1251                auto do_validate = [=] (const char *line)
1252                                   {
1253                                     validate_actionline (line, b);
1254                                   };
1255                gdb::function_view<void (const char *)> validator;
1256                if (is_tracepoint (b))
1257                  validator = do_validate;
1258
1259                cmd = read_command_lines (str.c_str (), from_tty, 1, validator);
1260              }
1261          }
1262
1263        /* If a breakpoint was on the list more than once, we don't need to
1264           do anything.  */
1265        if (b->commands != cmd)
1266          {
1267            validate_commands_for_breakpoint (b, cmd.get ());
1268            b->commands = cmd;
1269            gdb::observers::breakpoint_modified.notify (b);
1270          }
1271      });
1272 }
1273
1274 static void
1275 commands_command (const char *arg, int from_tty)
1276 {
1277   commands_command_1 (arg, from_tty, NULL);
1278 }
1279
1280 /* Like commands_command, but instead of reading the commands from
1281    input stream, takes them from an already parsed command structure.
1282
1283    This is used by cli-script.c to DTRT with breakpoint commands
1284    that are part of if and while bodies.  */
1285 enum command_control_type
1286 commands_from_control_command (const char *arg, struct command_line *cmd)
1287 {
1288   commands_command_1 (arg, 0, cmd);
1289   return simple_control;
1290 }
1291
1292 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1293
1294 static int
1295 bp_location_has_shadow (struct bp_location *bl)
1296 {
1297   if (bl->loc_type != bp_loc_software_breakpoint)
1298     return 0;
1299   if (!bl->inserted)
1300     return 0;
1301   if (bl->target_info.shadow_len == 0)
1302     /* BL isn't valid, or doesn't shadow memory.  */
1303     return 0;
1304   return 1;
1305 }
1306
1307 /* Update BUF, which is LEN bytes read from the target address
1308    MEMADDR, by replacing a memory breakpoint with its shadowed
1309    contents.
1310
1311    If READBUF is not NULL, this buffer must not overlap with the of
1312    the breakpoint location's shadow_contents buffer.  Otherwise, a
1313    failed assertion internal error will be raised.  */
1314
1315 static void
1316 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1317                             const gdb_byte *writebuf_org,
1318                             ULONGEST memaddr, LONGEST len,
1319                             struct bp_target_info *target_info,
1320                             struct gdbarch *gdbarch)
1321 {
1322   /* Now do full processing of the found relevant range of elements.  */
1323   CORE_ADDR bp_addr = 0;
1324   int bp_size = 0;
1325   int bptoffset = 0;
1326
1327   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1328                                  current_program_space->aspace, 0))
1329     {
1330       /* The breakpoint is inserted in a different address space.  */
1331       return;
1332     }
1333
1334   /* Addresses and length of the part of the breakpoint that
1335      we need to copy.  */
1336   bp_addr = target_info->placed_address;
1337   bp_size = target_info->shadow_len;
1338
1339   if (bp_addr + bp_size <= memaddr)
1340     {
1341       /* The breakpoint is entirely before the chunk of memory we are
1342          reading.  */
1343       return;
1344     }
1345
1346   if (bp_addr >= memaddr + len)
1347     {
1348       /* The breakpoint is entirely after the chunk of memory we are
1349          reading.  */
1350       return;
1351     }
1352
1353   /* Offset within shadow_contents.  */
1354   if (bp_addr < memaddr)
1355     {
1356       /* Only copy the second part of the breakpoint.  */
1357       bp_size -= memaddr - bp_addr;
1358       bptoffset = memaddr - bp_addr;
1359       bp_addr = memaddr;
1360     }
1361
1362   if (bp_addr + bp_size > memaddr + len)
1363     {
1364       /* Only copy the first part of the breakpoint.  */
1365       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1366     }
1367
1368   if (readbuf != NULL)
1369     {
1370       /* Verify that the readbuf buffer does not overlap with the
1371          shadow_contents buffer.  */
1372       gdb_assert (target_info->shadow_contents >= readbuf + len
1373                   || readbuf >= (target_info->shadow_contents
1374                                  + target_info->shadow_len));
1375
1376       /* Update the read buffer with this inserted breakpoint's
1377          shadow.  */
1378       memcpy (readbuf + bp_addr - memaddr,
1379               target_info->shadow_contents + bptoffset, bp_size);
1380     }
1381   else
1382     {
1383       const unsigned char *bp;
1384       CORE_ADDR addr = target_info->reqstd_address;
1385       int placed_size;
1386
1387       /* Update the shadow with what we want to write to memory.  */
1388       memcpy (target_info->shadow_contents + bptoffset,
1389               writebuf_org + bp_addr - memaddr, bp_size);
1390
1391       /* Determine appropriate breakpoint contents and size for this
1392          address.  */
1393       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1394
1395       /* Update the final write buffer with this inserted
1396          breakpoint's INSN.  */
1397       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1398     }
1399 }
1400
1401 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1402    by replacing any memory breakpoints with their shadowed contents.
1403
1404    If READBUF is not NULL, this buffer must not overlap with any of
1405    the breakpoint location's shadow_contents buffers.  Otherwise,
1406    a failed assertion internal error will be raised.
1407
1408    The range of shadowed area by each bp_location is:
1409      bl->address - bp_locations_placed_address_before_address_max
1410      up to bl->address + bp_locations_shadow_len_after_address_max
1411    The range we were requested to resolve shadows for is:
1412      memaddr ... memaddr + len
1413    Thus the safe cutoff boundaries for performance optimization are
1414      memaddr + len <= (bl->address
1415                        - bp_locations_placed_address_before_address_max)
1416    and:
1417      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1418
1419 void
1420 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1421                         const gdb_byte *writebuf_org,
1422                         ULONGEST memaddr, LONGEST len)
1423 {
1424   /* Left boundary, right boundary and median element of our binary
1425      search.  */
1426   unsigned bc_l, bc_r, bc;
1427
1428   /* Find BC_L which is a leftmost element which may affect BUF
1429      content.  It is safe to report lower value but a failure to
1430      report higher one.  */
1431
1432   bc_l = 0;
1433   bc_r = bp_locations_count;
1434   while (bc_l + 1 < bc_r)
1435     {
1436       struct bp_location *bl;
1437
1438       bc = (bc_l + bc_r) / 2;
1439       bl = bp_locations[bc];
1440
1441       /* Check first BL->ADDRESS will not overflow due to the added
1442          constant.  Then advance the left boundary only if we are sure
1443          the BC element can in no way affect the BUF content (MEMADDR
1444          to MEMADDR + LEN range).
1445
1446          Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1447          offset so that we cannot miss a breakpoint with its shadow
1448          range tail still reaching MEMADDR.  */
1449
1450       if ((bl->address + bp_locations_shadow_len_after_address_max
1451            >= bl->address)
1452           && (bl->address + bp_locations_shadow_len_after_address_max
1453               <= memaddr))
1454         bc_l = bc;
1455       else
1456         bc_r = bc;
1457     }
1458
1459   /* Due to the binary search above, we need to make sure we pick the
1460      first location that's at BC_L's address.  E.g., if there are
1461      multiple locations at the same address, BC_L may end up pointing
1462      at a duplicate location, and miss the "master"/"inserted"
1463      location.  Say, given locations L1, L2 and L3 at addresses A and
1464      B:
1465
1466       L1@A, L2@A, L3@B, ...
1467
1468      BC_L could end up pointing at location L2, while the "master"
1469      location could be L1.  Since the `loc->inserted' flag is only set
1470      on "master" locations, we'd forget to restore the shadow of L1
1471      and L2.  */
1472   while (bc_l > 0
1473          && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1474     bc_l--;
1475
1476   /* Now do full processing of the found relevant range of elements.  */
1477
1478   for (bc = bc_l; bc < bp_locations_count; bc++)
1479   {
1480     struct bp_location *bl = bp_locations[bc];
1481
1482     /* bp_location array has BL->OWNER always non-NULL.  */
1483     if (bl->owner->type == bp_none)
1484       warning (_("reading through apparently deleted breakpoint #%d?"),
1485                bl->owner->number);
1486
1487     /* Performance optimization: any further element can no longer affect BUF
1488        content.  */
1489
1490     if (bl->address >= bp_locations_placed_address_before_address_max
1491         && memaddr + len <= (bl->address
1492                              - bp_locations_placed_address_before_address_max))
1493       break;
1494
1495     if (!bp_location_has_shadow (bl))
1496       continue;
1497
1498     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1499                                 memaddr, len, &bl->target_info, bl->gdbarch);
1500   }
1501 }
1502
1503 \f
1504
1505 /* Return true if BPT is either a software breakpoint or a hardware
1506    breakpoint.  */
1507
1508 int
1509 is_breakpoint (const struct breakpoint *bpt)
1510 {
1511   return (bpt->type == bp_breakpoint
1512           || bpt->type == bp_hardware_breakpoint
1513           || bpt->type == bp_dprintf);
1514 }
1515
1516 /* Return true if BPT is of any hardware watchpoint kind.  */
1517
1518 static int
1519 is_hardware_watchpoint (const struct breakpoint *bpt)
1520 {
1521   return (bpt->type == bp_hardware_watchpoint
1522           || bpt->type == bp_read_watchpoint
1523           || bpt->type == bp_access_watchpoint);
1524 }
1525
1526 /* Return true if BPT is of any watchpoint kind, hardware or
1527    software.  */
1528
1529 int
1530 is_watchpoint (const struct breakpoint *bpt)
1531 {
1532   return (is_hardware_watchpoint (bpt)
1533           || bpt->type == bp_watchpoint);
1534 }
1535
1536 /* Returns true if the current thread and its running state are safe
1537    to evaluate or update watchpoint B.  Watchpoints on local
1538    expressions need to be evaluated in the context of the thread that
1539    was current when the watchpoint was created, and, that thread needs
1540    to be stopped to be able to select the correct frame context.
1541    Watchpoints on global expressions can be evaluated on any thread,
1542    and in any state.  It is presently left to the target allowing
1543    memory accesses when threads are running.  */
1544
1545 static int
1546 watchpoint_in_thread_scope (struct watchpoint *b)
1547 {
1548   return (b->pspace == current_program_space
1549           && (ptid_equal (b->watchpoint_thread, null_ptid)
1550               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1551                   && !is_executing (inferior_ptid))));
1552 }
1553
1554 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1555    associated bp_watchpoint_scope breakpoint.  */
1556
1557 static void
1558 watchpoint_del_at_next_stop (struct watchpoint *w)
1559 {
1560   if (w->related_breakpoint != w)
1561     {
1562       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1563       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1564       w->related_breakpoint->disposition = disp_del_at_next_stop;
1565       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1566       w->related_breakpoint = w;
1567     }
1568   w->disposition = disp_del_at_next_stop;
1569 }
1570
1571 /* Extract a bitfield value from value VAL using the bit parameters contained in
1572    watchpoint W.  */
1573
1574 static struct value *
1575 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1576 {
1577   struct value *bit_val;
1578
1579   if (val == NULL)
1580     return NULL;
1581
1582   bit_val = allocate_value (value_type (val));
1583
1584   unpack_value_bitfield (bit_val,
1585                          w->val_bitpos,
1586                          w->val_bitsize,
1587                          value_contents_for_printing (val),
1588                          value_offset (val),
1589                          val);
1590
1591   return bit_val;
1592 }
1593
1594 /* Allocate a dummy location and add it to B, which must be a software
1595    watchpoint.  This is required because even if a software watchpoint
1596    is not watching any memory, bpstat_stop_status requires a location
1597    to be able to report stops.  */
1598
1599 static void
1600 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1601                                             struct program_space *pspace)
1602 {
1603   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1604
1605   b->loc = allocate_bp_location (b);
1606   b->loc->pspace = pspace;
1607   b->loc->address = -1;
1608   b->loc->length = -1;
1609 }
1610
1611 /* Returns true if B is a software watchpoint that is not watching any
1612    memory (e.g., "watch $pc").  */
1613
1614 static int
1615 is_no_memory_software_watchpoint (struct breakpoint *b)
1616 {
1617   return (b->type == bp_watchpoint
1618           && b->loc != NULL
1619           && b->loc->next == NULL
1620           && b->loc->address == -1
1621           && b->loc->length == -1);
1622 }
1623
1624 /* Assuming that B is a watchpoint:
1625    - Reparse watchpoint expression, if REPARSE is non-zero
1626    - Evaluate expression and store the result in B->val
1627    - Evaluate the condition if there is one, and store the result
1628      in b->loc->cond.
1629    - Update the list of values that must be watched in B->loc.
1630
1631    If the watchpoint disposition is disp_del_at_next_stop, then do
1632    nothing.  If this is local watchpoint that is out of scope, delete
1633    it.
1634
1635    Even with `set breakpoint always-inserted on' the watchpoints are
1636    removed + inserted on each stop here.  Normal breakpoints must
1637    never be removed because they might be missed by a running thread
1638    when debugging in non-stop mode.  On the other hand, hardware
1639    watchpoints (is_hardware_watchpoint; processed here) are specific
1640    to each LWP since they are stored in each LWP's hardware debug
1641    registers.  Therefore, such LWP must be stopped first in order to
1642    be able to modify its hardware watchpoints.
1643
1644    Hardware watchpoints must be reset exactly once after being
1645    presented to the user.  It cannot be done sooner, because it would
1646    reset the data used to present the watchpoint hit to the user.  And
1647    it must not be done later because it could display the same single
1648    watchpoint hit during multiple GDB stops.  Note that the latter is
1649    relevant only to the hardware watchpoint types bp_read_watchpoint
1650    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1651    not user-visible - its hit is suppressed if the memory content has
1652    not changed.
1653
1654    The following constraints influence the location where we can reset
1655    hardware watchpoints:
1656
1657    * target_stopped_by_watchpoint and target_stopped_data_address are
1658      called several times when GDB stops.
1659
1660    [linux] 
1661    * Multiple hardware watchpoints can be hit at the same time,
1662      causing GDB to stop.  GDB only presents one hardware watchpoint
1663      hit at a time as the reason for stopping, and all the other hits
1664      are presented later, one after the other, each time the user
1665      requests the execution to be resumed.  Execution is not resumed
1666      for the threads still having pending hit event stored in
1667      LWP_INFO->STATUS.  While the watchpoint is already removed from
1668      the inferior on the first stop the thread hit event is kept being
1669      reported from its cached value by linux_nat_stopped_data_address
1670      until the real thread resume happens after the watchpoint gets
1671      presented and thus its LWP_INFO->STATUS gets reset.
1672
1673    Therefore the hardware watchpoint hit can get safely reset on the
1674    watchpoint removal from inferior.  */
1675
1676 static void
1677 update_watchpoint (struct watchpoint *b, int reparse)
1678 {
1679   int within_current_scope;
1680   struct frame_id saved_frame_id;
1681   int frame_saved;
1682
1683   /* If this is a local watchpoint, we only want to check if the
1684      watchpoint frame is in scope if the current thread is the thread
1685      that was used to create the watchpoint.  */
1686   if (!watchpoint_in_thread_scope (b))
1687     return;
1688
1689   if (b->disposition == disp_del_at_next_stop)
1690     return;
1691  
1692   frame_saved = 0;
1693
1694   /* Determine if the watchpoint is within scope.  */
1695   if (b->exp_valid_block == NULL)
1696     within_current_scope = 1;
1697   else
1698     {
1699       struct frame_info *fi = get_current_frame ();
1700       struct gdbarch *frame_arch = get_frame_arch (fi);
1701       CORE_ADDR frame_pc = get_frame_pc (fi);
1702
1703       /* If we're at a point where the stack has been destroyed
1704          (e.g. in a function epilogue), unwinding may not work
1705          properly. Do not attempt to recreate locations at this
1706          point.  See similar comments in watchpoint_check.  */
1707       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1708         return;
1709
1710       /* Save the current frame's ID so we can restore it after
1711          evaluating the watchpoint expression on its own frame.  */
1712       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1713          took a frame parameter, so that we didn't have to change the
1714          selected frame.  */
1715       frame_saved = 1;
1716       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1717
1718       fi = frame_find_by_id (b->watchpoint_frame);
1719       within_current_scope = (fi != NULL);
1720       if (within_current_scope)
1721         select_frame (fi);
1722     }
1723
1724   /* We don't free locations.  They are stored in the bp_location array
1725      and update_global_location_list will eventually delete them and
1726      remove breakpoints if needed.  */
1727   b->loc = NULL;
1728
1729   if (within_current_scope && reparse)
1730     {
1731       const char *s;
1732
1733       b->exp.reset ();
1734       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1735       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1736       /* If the meaning of expression itself changed, the old value is
1737          no longer relevant.  We don't want to report a watchpoint hit
1738          to the user when the old value and the new value may actually
1739          be completely different objects.  */
1740       b->val = NULL;
1741       b->val_valid = 0;
1742
1743       /* Note that unlike with breakpoints, the watchpoint's condition
1744          expression is stored in the breakpoint object, not in the
1745          locations (re)created below.  */
1746       if (b->cond_string != NULL)
1747         {
1748           b->cond_exp.reset ();
1749
1750           s = b->cond_string;
1751           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1752         }
1753     }
1754
1755   /* If we failed to parse the expression, for example because
1756      it refers to a global variable in a not-yet-loaded shared library,
1757      don't try to insert watchpoint.  We don't automatically delete
1758      such watchpoint, though, since failure to parse expression
1759      is different from out-of-scope watchpoint.  */
1760   if (!target_has_execution)
1761     {
1762       /* Without execution, memory can't change.  No use to try and
1763          set watchpoint locations.  The watchpoint will be reset when
1764          the target gains execution, through breakpoint_re_set.  */
1765       if (!can_use_hw_watchpoints)
1766         {
1767           if (b->ops->works_in_software_mode (b))
1768             b->type = bp_watchpoint;
1769           else
1770             error (_("Can't set read/access watchpoint when "
1771                      "hardware watchpoints are disabled."));
1772         }
1773     }
1774   else if (within_current_scope && b->exp)
1775     {
1776       int pc = 0;
1777       std::vector<value_ref_ptr> val_chain;
1778       struct value *v, *result, *next;
1779       struct program_space *frame_pspace;
1780
1781       fetch_subexp_value (b->exp.get (), &pc, &v, &result, &val_chain, 0);
1782
1783       /* Avoid setting b->val if it's already set.  The meaning of
1784          b->val is 'the last value' user saw, and we should update
1785          it only if we reported that last value to user.  As it
1786          happens, the code that reports it updates b->val directly.
1787          We don't keep track of the memory value for masked
1788          watchpoints.  */
1789       if (!b->val_valid && !is_masked_watchpoint (b))
1790         {
1791           if (b->val_bitsize != 0)
1792             v = extract_bitfield_from_watchpoint_value (b, v);
1793           b->val = release_value (v);
1794           b->val_valid = 1;
1795         }
1796
1797       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1798
1799       /* Look at each value on the value chain.  */
1800       gdb_assert (!val_chain.empty ());
1801       for (const value_ref_ptr &iter : val_chain)
1802         {
1803           v = iter.get ();
1804
1805           /* If it's a memory location, and GDB actually needed
1806              its contents to evaluate the expression, then we
1807              must watch it.  If the first value returned is
1808              still lazy, that means an error occurred reading it;
1809              watch it anyway in case it becomes readable.  */
1810           if (VALUE_LVAL (v) == lval_memory
1811               && (v == val_chain[0] || ! value_lazy (v)))
1812             {
1813               struct type *vtype = check_typedef (value_type (v));
1814
1815               /* We only watch structs and arrays if user asked
1816                  for it explicitly, never if they just happen to
1817                  appear in the middle of some value chain.  */
1818               if (v == result
1819                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1820                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1821                 {
1822                   CORE_ADDR addr;
1823                   enum target_hw_bp_type type;
1824                   struct bp_location *loc, **tmp;
1825                   int bitpos = 0, bitsize = 0;
1826
1827                   if (value_bitsize (v) != 0)
1828                     {
1829                       /* Extract the bit parameters out from the bitfield
1830                          sub-expression.  */
1831                       bitpos = value_bitpos (v);
1832                       bitsize = value_bitsize (v);
1833                     }
1834                   else if (v == result && b->val_bitsize != 0)
1835                     {
1836                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1837                         lvalue whose bit parameters are saved in the fields
1838                         VAL_BITPOS and VAL_BITSIZE.  */
1839                       bitpos = b->val_bitpos;
1840                       bitsize = b->val_bitsize;
1841                     }
1842
1843                   addr = value_address (v);
1844                   if (bitsize != 0)
1845                     {
1846                       /* Skip the bytes that don't contain the bitfield.  */
1847                       addr += bitpos / 8;
1848                     }
1849
1850                   type = hw_write;
1851                   if (b->type == bp_read_watchpoint)
1852                     type = hw_read;
1853                   else if (b->type == bp_access_watchpoint)
1854                     type = hw_access;
1855
1856                   loc = allocate_bp_location (b);
1857                   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
1858                     ;
1859                   *tmp = loc;
1860                   loc->gdbarch = get_type_arch (value_type (v));
1861
1862                   loc->pspace = frame_pspace;
1863                   loc->address = address_significant (loc->gdbarch, addr);
1864
1865                   if (bitsize != 0)
1866                     {
1867                       /* Just cover the bytes that make up the bitfield.  */
1868                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
1869                     }
1870                   else
1871                     loc->length = TYPE_LENGTH (value_type (v));
1872
1873                   loc->watchpoint_type = type;
1874                 }
1875             }
1876         }
1877
1878       /* Change the type of breakpoint between hardware assisted or
1879          an ordinary watchpoint depending on the hardware support
1880          and free hardware slots.  REPARSE is set when the inferior
1881          is started.  */
1882       if (reparse)
1883         {
1884           int reg_cnt;
1885           enum bp_loc_type loc_type;
1886           struct bp_location *bl;
1887
1888           reg_cnt = can_use_hardware_watchpoint (val_chain);
1889
1890           if (reg_cnt)
1891             {
1892               int i, target_resources_ok, other_type_used;
1893               enum bptype type;
1894
1895               /* Use an exact watchpoint when there's only one memory region to be
1896                  watched, and only one debug register is needed to watch it.  */
1897               b->exact = target_exact_watchpoints && reg_cnt == 1;
1898
1899               /* We need to determine how many resources are already
1900                  used for all other hardware watchpoints plus this one
1901                  to see if we still have enough resources to also fit
1902                  this watchpoint in as well.  */
1903
1904               /* If this is a software watchpoint, we try to turn it
1905                  to a hardware one -- count resources as if B was of
1906                  hardware watchpoint type.  */
1907               type = b->type;
1908               if (type == bp_watchpoint)
1909                 type = bp_hardware_watchpoint;
1910
1911               /* This watchpoint may or may not have been placed on
1912                  the list yet at this point (it won't be in the list
1913                  if we're trying to create it for the first time,
1914                  through watch_command), so always account for it
1915                  manually.  */
1916
1917               /* Count resources used by all watchpoints except B.  */
1918               i = hw_watchpoint_used_count_others (b, type, &other_type_used);
1919
1920               /* Add in the resources needed for B.  */
1921               i += hw_watchpoint_use_count (b);
1922
1923               target_resources_ok
1924                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1925               if (target_resources_ok <= 0)
1926                 {
1927                   int sw_mode = b->ops->works_in_software_mode (b);
1928
1929                   if (target_resources_ok == 0 && !sw_mode)
1930                     error (_("Target does not support this type of "
1931                              "hardware watchpoint."));
1932                   else if (target_resources_ok < 0 && !sw_mode)
1933                     error (_("There are not enough available hardware "
1934                              "resources for this watchpoint."));
1935
1936                   /* Downgrade to software watchpoint.  */
1937                   b->type = bp_watchpoint;
1938                 }
1939               else
1940                 {
1941                   /* If this was a software watchpoint, we've just
1942                      found we have enough resources to turn it to a
1943                      hardware watchpoint.  Otherwise, this is a
1944                      nop.  */
1945                   b->type = type;
1946                 }
1947             }
1948           else if (!b->ops->works_in_software_mode (b))
1949             {
1950               if (!can_use_hw_watchpoints)
1951                 error (_("Can't set read/access watchpoint when "
1952                          "hardware watchpoints are disabled."));
1953               else
1954                 error (_("Expression cannot be implemented with "
1955                          "read/access watchpoint."));
1956             }
1957           else
1958             b->type = bp_watchpoint;
1959
1960           loc_type = (b->type == bp_watchpoint? bp_loc_other
1961                       : bp_loc_hardware_watchpoint);
1962           for (bl = b->loc; bl; bl = bl->next)
1963             bl->loc_type = loc_type;
1964         }
1965
1966       /* If a software watchpoint is not watching any memory, then the
1967          above left it without any location set up.  But,
1968          bpstat_stop_status requires a location to be able to report
1969          stops, so make sure there's at least a dummy one.  */
1970       if (b->type == bp_watchpoint && b->loc == NULL)
1971         software_watchpoint_add_no_memory_location (b, frame_pspace);
1972     }
1973   else if (!within_current_scope)
1974     {
1975       printf_filtered (_("\
1976 Watchpoint %d deleted because the program has left the block\n\
1977 in which its expression is valid.\n"),
1978                        b->number);
1979       watchpoint_del_at_next_stop (b);
1980     }
1981
1982   /* Restore the selected frame.  */
1983   if (frame_saved)
1984     select_frame (frame_find_by_id (saved_frame_id));
1985 }
1986
1987
1988 /* Returns 1 iff breakpoint location should be
1989    inserted in the inferior.  We don't differentiate the type of BL's owner
1990    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1991    breakpoint_ops is not defined, because in insert_bp_location,
1992    tracepoint's insert_location will not be called.  */
1993 static int
1994 should_be_inserted (struct bp_location *bl)
1995 {
1996   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
1997     return 0;
1998
1999   if (bl->owner->disposition == disp_del_at_next_stop)
2000     return 0;
2001
2002   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2003     return 0;
2004
2005   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2006     return 0;
2007
2008   /* This is set for example, when we're attached to the parent of a
2009      vfork, and have detached from the child.  The child is running
2010      free, and we expect it to do an exec or exit, at which point the
2011      OS makes the parent schedulable again (and the target reports
2012      that the vfork is done).  Until the child is done with the shared
2013      memory region, do not insert breakpoints in the parent, otherwise
2014      the child could still trip on the parent's breakpoints.  Since
2015      the parent is blocked anyway, it won't miss any breakpoint.  */
2016   if (bl->pspace->breakpoints_not_allowed)
2017     return 0;
2018
2019   /* Don't insert a breakpoint if we're trying to step past its
2020      location, except if the breakpoint is a single-step breakpoint,
2021      and the breakpoint's thread is the thread which is stepping past
2022      a breakpoint.  */
2023   if ((bl->loc_type == bp_loc_software_breakpoint
2024        || bl->loc_type == bp_loc_hardware_breakpoint)
2025       && stepping_past_instruction_at (bl->pspace->aspace,
2026                                        bl->address)
2027       /* The single-step breakpoint may be inserted at the location
2028          we're trying to step if the instruction branches to itself.
2029          However, the instruction won't be executed at all and it may
2030          break the semantics of the instruction, for example, the
2031          instruction is a conditional branch or updates some flags.
2032          We can't fix it unless GDB is able to emulate the instruction
2033          or switch to displaced stepping.  */
2034       && !(bl->owner->type == bp_single_step
2035            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2036     {
2037       if (debug_infrun)
2038         {
2039           fprintf_unfiltered (gdb_stdlog,
2040                               "infrun: skipping breakpoint: "
2041                               "stepping past insn at: %s\n",
2042                               paddress (bl->gdbarch, bl->address));
2043         }
2044       return 0;
2045     }
2046
2047   /* Don't insert watchpoints if we're trying to step past the
2048      instruction that triggered one.  */
2049   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2050       && stepping_past_nonsteppable_watchpoint ())
2051     {
2052       if (debug_infrun)
2053         {
2054           fprintf_unfiltered (gdb_stdlog,
2055                               "infrun: stepping past non-steppable watchpoint. "
2056                               "skipping watchpoint at %s:%d\n",
2057                               paddress (bl->gdbarch, bl->address),
2058                               bl->length);
2059         }
2060       return 0;
2061     }
2062
2063   return 1;
2064 }
2065
2066 /* Same as should_be_inserted but does the check assuming
2067    that the location is not duplicated.  */
2068
2069 static int
2070 unduplicated_should_be_inserted (struct bp_location *bl)
2071 {
2072   int result;
2073   const int save_duplicate = bl->duplicate;
2074
2075   bl->duplicate = 0;
2076   result = should_be_inserted (bl);
2077   bl->duplicate = save_duplicate;
2078   return result;
2079 }
2080
2081 /* Parses a conditional described by an expression COND into an
2082    agent expression bytecode suitable for evaluation
2083    by the bytecode interpreter.  Return NULL if there was
2084    any error during parsing.  */
2085
2086 static agent_expr_up
2087 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2088 {
2089   if (cond == NULL)
2090     return NULL;
2091
2092   agent_expr_up aexpr;
2093
2094   /* We don't want to stop processing, so catch any errors
2095      that may show up.  */
2096   TRY
2097     {
2098       aexpr = gen_eval_for_expr (scope, cond);
2099     }
2100
2101   CATCH (ex, RETURN_MASK_ERROR)
2102     {
2103       /* If we got here, it means the condition could not be parsed to a valid
2104          bytecode expression and thus can't be evaluated on the target's side.
2105          It's no use iterating through the conditions.  */
2106     }
2107   END_CATCH
2108
2109   /* We have a valid agent expression.  */
2110   return aexpr;
2111 }
2112
2113 /* Based on location BL, create a list of breakpoint conditions to be
2114    passed on to the target.  If we have duplicated locations with different
2115    conditions, we will add such conditions to the list.  The idea is that the
2116    target will evaluate the list of conditions and will only notify GDB when
2117    one of them is true.  */
2118
2119 static void
2120 build_target_condition_list (struct bp_location *bl)
2121 {
2122   struct bp_location **locp = NULL, **loc2p;
2123   int null_condition_or_parse_error = 0;
2124   int modified = bl->needs_update;
2125   struct bp_location *loc;
2126
2127   /* Release conditions left over from a previous insert.  */
2128   bl->target_info.conditions.clear ();
2129
2130   /* This is only meaningful if the target is
2131      evaluating conditions and if the user has
2132      opted for condition evaluation on the target's
2133      side.  */
2134   if (gdb_evaluates_breakpoint_condition_p ()
2135       || !target_supports_evaluation_of_breakpoint_conditions ())
2136     return;
2137
2138   /* Do a first pass to check for locations with no assigned
2139      conditions or conditions that fail to parse to a valid agent expression
2140      bytecode.  If any of these happen, then it's no use to send conditions
2141      to the target since this location will always trigger and generate a
2142      response back to GDB.  */
2143   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2144     {
2145       loc = (*loc2p);
2146       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2147         {
2148           if (modified)
2149             {
2150               /* Re-parse the conditions since something changed.  In that
2151                  case we already freed the condition bytecodes (see
2152                  force_breakpoint_reinsertion).  We just
2153                  need to parse the condition to bytecodes again.  */
2154               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2155                                                         loc->cond.get ());
2156             }
2157
2158           /* If we have a NULL bytecode expression, it means something
2159              went wrong or we have a null condition expression.  */
2160           if (!loc->cond_bytecode)
2161             {
2162               null_condition_or_parse_error = 1;
2163               break;
2164             }
2165         }
2166     }
2167
2168   /* If any of these happened, it means we will have to evaluate the conditions
2169      for the location's address on gdb's side.  It is no use keeping bytecodes
2170      for all the other duplicate locations, thus we free all of them here.
2171
2172      This is so we have a finer control over which locations' conditions are
2173      being evaluated by GDB or the remote stub.  */
2174   if (null_condition_or_parse_error)
2175     {
2176       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2177         {
2178           loc = (*loc2p);
2179           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2180             {
2181               /* Only go as far as the first NULL bytecode is
2182                  located.  */
2183               if (!loc->cond_bytecode)
2184                 return;
2185
2186               loc->cond_bytecode.reset ();
2187             }
2188         }
2189     }
2190
2191   /* No NULL conditions or failed bytecode generation.  Build a condition list
2192      for this location's address.  */
2193   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2194     {
2195       loc = (*loc2p);
2196       if (loc->cond
2197           && is_breakpoint (loc->owner)
2198           && loc->pspace->num == bl->pspace->num
2199           && loc->owner->enable_state == bp_enabled
2200           && loc->enabled)
2201         {
2202           /* Add the condition to the vector.  This will be used later
2203              to send the conditions to the target.  */
2204           bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2205         }
2206     }
2207
2208   return;
2209 }
2210
2211 /* Parses a command described by string CMD into an agent expression
2212    bytecode suitable for evaluation by the bytecode interpreter.
2213    Return NULL if there was any error during parsing.  */
2214
2215 static agent_expr_up
2216 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2217 {
2218   const char *cmdrest;
2219   const char *format_start, *format_end;
2220   struct gdbarch *gdbarch = get_current_arch ();
2221
2222   if (cmd == NULL)
2223     return NULL;
2224
2225   cmdrest = cmd;
2226
2227   if (*cmdrest == ',')
2228     ++cmdrest;
2229   cmdrest = skip_spaces (cmdrest);
2230
2231   if (*cmdrest++ != '"')
2232     error (_("No format string following the location"));
2233
2234   format_start = cmdrest;
2235
2236   format_pieces fpieces (&cmdrest);
2237
2238   format_end = cmdrest;
2239
2240   if (*cmdrest++ != '"')
2241     error (_("Bad format string, non-terminated '\"'."));
2242   
2243   cmdrest = skip_spaces (cmdrest);
2244
2245   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2246     error (_("Invalid argument syntax"));
2247
2248   if (*cmdrest == ',')
2249     cmdrest++;
2250   cmdrest = skip_spaces (cmdrest);
2251
2252   /* For each argument, make an expression.  */
2253
2254   std::vector<struct expression *> argvec;
2255   while (*cmdrest != '\0')
2256     {
2257       const char *cmd1;
2258
2259       cmd1 = cmdrest;
2260       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2261       argvec.push_back (expr.release ());
2262       cmdrest = cmd1;
2263       if (*cmdrest == ',')
2264         ++cmdrest;
2265     }
2266
2267   agent_expr_up aexpr;
2268
2269   /* We don't want to stop processing, so catch any errors
2270      that may show up.  */
2271   TRY
2272     {
2273       aexpr = gen_printf (scope, gdbarch, 0, 0,
2274                           format_start, format_end - format_start,
2275                           argvec.size (), argvec.data ());
2276     }
2277   CATCH (ex, RETURN_MASK_ERROR)
2278     {
2279       /* If we got here, it means the command could not be parsed to a valid
2280          bytecode expression and thus can't be evaluated on the target's side.
2281          It's no use iterating through the other commands.  */
2282     }
2283   END_CATCH
2284
2285   /* We have a valid agent expression, return it.  */
2286   return aexpr;
2287 }
2288
2289 /* Based on location BL, create a list of breakpoint commands to be
2290    passed on to the target.  If we have duplicated locations with
2291    different commands, we will add any such to the list.  */
2292
2293 static void
2294 build_target_command_list (struct bp_location *bl)
2295 {
2296   struct bp_location **locp = NULL, **loc2p;
2297   int null_command_or_parse_error = 0;
2298   int modified = bl->needs_update;
2299   struct bp_location *loc;
2300
2301   /* Clear commands left over from a previous insert.  */
2302   bl->target_info.tcommands.clear ();
2303
2304   if (!target_can_run_breakpoint_commands ())
2305     return;
2306
2307   /* For now, limit to agent-style dprintf breakpoints.  */
2308   if (dprintf_style != dprintf_style_agent)
2309     return;
2310
2311   /* For now, if we have any duplicate location that isn't a dprintf,
2312      don't install the target-side commands, as that would make the
2313      breakpoint not be reported to the core, and we'd lose
2314      control.  */
2315   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2316     {
2317       loc = (*loc2p);
2318       if (is_breakpoint (loc->owner)
2319           && loc->pspace->num == bl->pspace->num
2320           && loc->owner->type != bp_dprintf)
2321         return;
2322     }
2323
2324   /* Do a first pass to check for locations with no assigned
2325      conditions or conditions that fail to parse to a valid agent expression
2326      bytecode.  If any of these happen, then it's no use to send conditions
2327      to the target since this location will always trigger and generate a
2328      response back to GDB.  */
2329   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2330     {
2331       loc = (*loc2p);
2332       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2333         {
2334           if (modified)
2335             {
2336               /* Re-parse the commands since something changed.  In that
2337                  case we already freed the command bytecodes (see
2338                  force_breakpoint_reinsertion).  We just
2339                  need to parse the command to bytecodes again.  */
2340               loc->cmd_bytecode
2341                 = parse_cmd_to_aexpr (bl->address,
2342                                       loc->owner->extra_string);
2343             }
2344
2345           /* If we have a NULL bytecode expression, it means something
2346              went wrong or we have a null command expression.  */
2347           if (!loc->cmd_bytecode)
2348             {
2349               null_command_or_parse_error = 1;
2350               break;
2351             }
2352         }
2353     }
2354
2355   /* If anything failed, then we're not doing target-side commands,
2356      and so clean up.  */
2357   if (null_command_or_parse_error)
2358     {
2359       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2360         {
2361           loc = (*loc2p);
2362           if (is_breakpoint (loc->owner)
2363               && loc->pspace->num == bl->pspace->num)
2364             {
2365               /* Only go as far as the first NULL bytecode is
2366                  located.  */
2367               if (loc->cmd_bytecode == NULL)
2368                 return;
2369
2370               loc->cmd_bytecode.reset ();
2371             }
2372         }
2373     }
2374
2375   /* No NULL commands or failed bytecode generation.  Build a command list
2376      for this location's address.  */
2377   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2378     {
2379       loc = (*loc2p);
2380       if (loc->owner->extra_string
2381           && is_breakpoint (loc->owner)
2382           && loc->pspace->num == bl->pspace->num
2383           && loc->owner->enable_state == bp_enabled
2384           && loc->enabled)
2385         {
2386           /* Add the command to the vector.  This will be used later
2387              to send the commands to the target.  */
2388           bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2389         }
2390     }
2391
2392   bl->target_info.persist = 0;
2393   /* Maybe flag this location as persistent.  */
2394   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2395     bl->target_info.persist = 1;
2396 }
2397
2398 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2399    of breakpoint according to ADDR except single-step breakpoint.
2400    Get the kind of single-step breakpoint according to the current
2401    registers state.  */
2402
2403 static int
2404 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2405 {
2406   if (bl->owner->type == bp_single_step)
2407     {
2408       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2409       struct regcache *regcache;
2410
2411       regcache = get_thread_regcache (thr->ptid);
2412
2413       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2414                                                          regcache, addr);
2415     }
2416   else
2417     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2418 }
2419
2420 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2421    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2422    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2423    Returns 0 for success, 1 if the bp_location type is not supported or
2424    -1 for failure.
2425
2426    NOTE drow/2003-09-09: This routine could be broken down to an
2427    object-style method for each breakpoint or catchpoint type.  */
2428 static int
2429 insert_bp_location (struct bp_location *bl,
2430                     struct ui_file *tmp_error_stream,
2431                     int *disabled_breaks,
2432                     int *hw_breakpoint_error,
2433                     int *hw_bp_error_explained_already)
2434 {
2435   gdb_exception bp_excpt = exception_none;
2436
2437   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2438     return 0;
2439
2440   /* Note we don't initialize bl->target_info, as that wipes out
2441      the breakpoint location's shadow_contents if the breakpoint
2442      is still inserted at that location.  This in turn breaks
2443      target_read_memory which depends on these buffers when
2444      a memory read is requested at the breakpoint location:
2445      Once the target_info has been wiped, we fail to see that
2446      we have a breakpoint inserted at that address and thus
2447      read the breakpoint instead of returning the data saved in
2448      the breakpoint location's shadow contents.  */
2449   bl->target_info.reqstd_address = bl->address;
2450   bl->target_info.placed_address_space = bl->pspace->aspace;
2451   bl->target_info.length = bl->length;
2452
2453   /* When working with target-side conditions, we must pass all the conditions
2454      for the same breakpoint address down to the target since GDB will not
2455      insert those locations.  With a list of breakpoint conditions, the target
2456      can decide when to stop and notify GDB.  */
2457
2458   if (is_breakpoint (bl->owner))
2459     {
2460       build_target_condition_list (bl);
2461       build_target_command_list (bl);
2462       /* Reset the modification marker.  */
2463       bl->needs_update = 0;
2464     }
2465
2466   if (bl->loc_type == bp_loc_software_breakpoint
2467       || bl->loc_type == bp_loc_hardware_breakpoint)
2468     {
2469       if (bl->owner->type != bp_hardware_breakpoint)
2470         {
2471           /* If the explicitly specified breakpoint type
2472              is not hardware breakpoint, check the memory map to see
2473              if the breakpoint address is in read only memory or not.
2474
2475              Two important cases are:
2476              - location type is not hardware breakpoint, memory
2477              is readonly.  We change the type of the location to
2478              hardware breakpoint.
2479              - location type is hardware breakpoint, memory is
2480              read-write.  This means we've previously made the
2481              location hardware one, but then the memory map changed,
2482              so we undo.
2483              
2484              When breakpoints are removed, remove_breakpoints will use
2485              location types we've just set here, the only possible
2486              problem is that memory map has changed during running
2487              program, but it's not going to work anyway with current
2488              gdb.  */
2489           struct mem_region *mr 
2490             = lookup_mem_region (bl->target_info.reqstd_address);
2491           
2492           if (mr)
2493             {
2494               if (automatic_hardware_breakpoints)
2495                 {
2496                   enum bp_loc_type new_type;
2497                   
2498                   if (mr->attrib.mode != MEM_RW)
2499                     new_type = bp_loc_hardware_breakpoint;
2500                   else 
2501                     new_type = bp_loc_software_breakpoint;
2502                   
2503                   if (new_type != bl->loc_type)
2504                     {
2505                       static int said = 0;
2506
2507                       bl->loc_type = new_type;
2508                       if (!said)
2509                         {
2510                           fprintf_filtered (gdb_stdout,
2511                                             _("Note: automatically using "
2512                                               "hardware breakpoints for "
2513                                               "read-only addresses.\n"));
2514                           said = 1;
2515                         }
2516                     }
2517                 }
2518               else if (bl->loc_type == bp_loc_software_breakpoint
2519                        && mr->attrib.mode != MEM_RW)
2520                 {
2521                   fprintf_unfiltered (tmp_error_stream,
2522                                       _("Cannot insert breakpoint %d.\n"
2523                                         "Cannot set software breakpoint "
2524                                         "at read-only address %s\n"),
2525                                       bl->owner->number,
2526                                       paddress (bl->gdbarch, bl->address));
2527                   return 1;
2528                 }
2529             }
2530         }
2531         
2532       /* First check to see if we have to handle an overlay.  */
2533       if (overlay_debugging == ovly_off
2534           || bl->section == NULL
2535           || !(section_is_overlay (bl->section)))
2536         {
2537           /* No overlay handling: just set the breakpoint.  */
2538           TRY
2539             {
2540               int val;
2541
2542               val = bl->owner->ops->insert_location (bl);
2543               if (val)
2544                 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2545             }
2546           CATCH (e, RETURN_MASK_ALL)
2547             {
2548               bp_excpt = e;
2549             }
2550           END_CATCH
2551         }
2552       else
2553         {
2554           /* This breakpoint is in an overlay section.
2555              Shall we set a breakpoint at the LMA?  */
2556           if (!overlay_events_enabled)
2557             {
2558               /* Yes -- overlay event support is not active, 
2559                  so we must try to set a breakpoint at the LMA.
2560                  This will not work for a hardware breakpoint.  */
2561               if (bl->loc_type == bp_loc_hardware_breakpoint)
2562                 warning (_("hardware breakpoint %d not supported in overlay!"),
2563                          bl->owner->number);
2564               else
2565                 {
2566                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2567                                                              bl->section);
2568                   /* Set a software (trap) breakpoint at the LMA.  */
2569                   bl->overlay_target_info = bl->target_info;
2570                   bl->overlay_target_info.reqstd_address = addr;
2571
2572                   /* No overlay handling: just set the breakpoint.  */
2573                   TRY
2574                     {
2575                       int val;
2576
2577                       bl->overlay_target_info.kind
2578                         = breakpoint_kind (bl, &addr);
2579                       bl->overlay_target_info.placed_address = addr;
2580                       val = target_insert_breakpoint (bl->gdbarch,
2581                                                       &bl->overlay_target_info);
2582                       if (val)
2583                         bp_excpt
2584                           = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2585                     }
2586                   CATCH (e, RETURN_MASK_ALL)
2587                     {
2588                       bp_excpt = e;
2589                     }
2590                   END_CATCH
2591
2592                   if (bp_excpt.reason != 0)
2593                     fprintf_unfiltered (tmp_error_stream,
2594                                         "Overlay breakpoint %d "
2595                                         "failed: in ROM?\n",
2596                                         bl->owner->number);
2597                 }
2598             }
2599           /* Shall we set a breakpoint at the VMA? */
2600           if (section_is_mapped (bl->section))
2601             {
2602               /* Yes.  This overlay section is mapped into memory.  */
2603               TRY
2604                 {
2605                   int val;
2606
2607                   val = bl->owner->ops->insert_location (bl);
2608                   if (val)
2609                     bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2610                 }
2611               CATCH (e, RETURN_MASK_ALL)
2612                 {
2613                   bp_excpt = e;
2614                 }
2615               END_CATCH
2616             }
2617           else
2618             {
2619               /* No.  This breakpoint will not be inserted.  
2620                  No error, but do not mark the bp as 'inserted'.  */
2621               return 0;
2622             }
2623         }
2624
2625       if (bp_excpt.reason != 0)
2626         {
2627           /* Can't set the breakpoint.  */
2628
2629           /* In some cases, we might not be able to insert a
2630              breakpoint in a shared library that has already been
2631              removed, but we have not yet processed the shlib unload
2632              event.  Unfortunately, some targets that implement
2633              breakpoint insertion themselves can't tell why the
2634              breakpoint insertion failed (e.g., the remote target
2635              doesn't define error codes), so we must treat generic
2636              errors as memory errors.  */
2637           if (bp_excpt.reason == RETURN_ERROR
2638               && (bp_excpt.error == GENERIC_ERROR
2639                   || bp_excpt.error == MEMORY_ERROR)
2640               && bl->loc_type == bp_loc_software_breakpoint
2641               && (solib_name_from_address (bl->pspace, bl->address)
2642                   || shared_objfile_contains_address_p (bl->pspace,
2643                                                         bl->address)))
2644             {
2645               /* See also: disable_breakpoints_in_shlibs.  */
2646               bl->shlib_disabled = 1;
2647               gdb::observers::breakpoint_modified.notify (bl->owner);
2648               if (!*disabled_breaks)
2649                 {
2650                   fprintf_unfiltered (tmp_error_stream, 
2651                                       "Cannot insert breakpoint %d.\n", 
2652                                       bl->owner->number);
2653                   fprintf_unfiltered (tmp_error_stream, 
2654                                       "Temporarily disabling shared "
2655                                       "library breakpoints:\n");
2656                 }
2657               *disabled_breaks = 1;
2658               fprintf_unfiltered (tmp_error_stream,
2659                                   "breakpoint #%d\n", bl->owner->number);
2660               return 0;
2661             }
2662           else
2663             {
2664               if (bl->loc_type == bp_loc_hardware_breakpoint)
2665                 {
2666                   *hw_breakpoint_error = 1;
2667                   *hw_bp_error_explained_already = bp_excpt.message != NULL;
2668                   fprintf_unfiltered (tmp_error_stream,
2669                                       "Cannot insert hardware breakpoint %d%s",
2670                                       bl->owner->number,
2671                                       bp_excpt.message ? ":" : ".\n");
2672                   if (bp_excpt.message != NULL)
2673                     fprintf_unfiltered (tmp_error_stream, "%s.\n",
2674                                         bp_excpt.message);
2675                 }
2676               else
2677                 {
2678                   if (bp_excpt.message == NULL)
2679                     {
2680                       std::string message
2681                         = memory_error_message (TARGET_XFER_E_IO,
2682                                                 bl->gdbarch, bl->address);
2683
2684                       fprintf_unfiltered (tmp_error_stream,
2685                                           "Cannot insert breakpoint %d.\n"
2686                                           "%s\n",
2687                                           bl->owner->number, message.c_str ());
2688                     }
2689                   else
2690                     {
2691                       fprintf_unfiltered (tmp_error_stream,
2692                                           "Cannot insert breakpoint %d: %s\n",
2693                                           bl->owner->number,
2694                                           bp_excpt.message);
2695                     }
2696                 }
2697               return 1;
2698
2699             }
2700         }
2701       else
2702         bl->inserted = 1;
2703
2704       return 0;
2705     }
2706
2707   else if (bl->loc_type == bp_loc_hardware_watchpoint
2708            /* NOTE drow/2003-09-08: This state only exists for removing
2709               watchpoints.  It's not clear that it's necessary...  */
2710            && bl->owner->disposition != disp_del_at_next_stop)
2711     {
2712       int val;
2713
2714       gdb_assert (bl->owner->ops != NULL
2715                   && bl->owner->ops->insert_location != NULL);
2716
2717       val = bl->owner->ops->insert_location (bl);
2718
2719       /* If trying to set a read-watchpoint, and it turns out it's not
2720          supported, try emulating one with an access watchpoint.  */
2721       if (val == 1 && bl->watchpoint_type == hw_read)
2722         {
2723           struct bp_location *loc, **loc_temp;
2724
2725           /* But don't try to insert it, if there's already another
2726              hw_access location that would be considered a duplicate
2727              of this one.  */
2728           ALL_BP_LOCATIONS (loc, loc_temp)
2729             if (loc != bl
2730                 && loc->watchpoint_type == hw_access
2731                 && watchpoint_locations_match (bl, loc))
2732               {
2733                 bl->duplicate = 1;
2734                 bl->inserted = 1;
2735                 bl->target_info = loc->target_info;
2736                 bl->watchpoint_type = hw_access;
2737                 val = 0;
2738                 break;
2739               }
2740
2741           if (val == 1)
2742             {
2743               bl->watchpoint_type = hw_access;
2744               val = bl->owner->ops->insert_location (bl);
2745
2746               if (val)
2747                 /* Back to the original value.  */
2748                 bl->watchpoint_type = hw_read;
2749             }
2750         }
2751
2752       bl->inserted = (val == 0);
2753     }
2754
2755   else if (bl->owner->type == bp_catchpoint)
2756     {
2757       int val;
2758
2759       gdb_assert (bl->owner->ops != NULL
2760                   && bl->owner->ops->insert_location != NULL);
2761
2762       val = bl->owner->ops->insert_location (bl);
2763       if (val)
2764         {
2765           bl->owner->enable_state = bp_disabled;
2766
2767           if (val == 1)
2768             warning (_("\
2769 Error inserting catchpoint %d: Your system does not support this type\n\
2770 of catchpoint."), bl->owner->number);
2771           else
2772             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2773         }
2774
2775       bl->inserted = (val == 0);
2776
2777       /* We've already printed an error message if there was a problem
2778          inserting this catchpoint, and we've disabled the catchpoint,
2779          so just return success.  */
2780       return 0;
2781     }
2782
2783   return 0;
2784 }
2785
2786 /* This function is called when program space PSPACE is about to be
2787    deleted.  It takes care of updating breakpoints to not reference
2788    PSPACE anymore.  */
2789
2790 void
2791 breakpoint_program_space_exit (struct program_space *pspace)
2792 {
2793   struct breakpoint *b, *b_temp;
2794   struct bp_location *loc, **loc_temp;
2795
2796   /* Remove any breakpoint that was set through this program space.  */
2797   ALL_BREAKPOINTS_SAFE (b, b_temp)
2798     {
2799       if (b->pspace == pspace)
2800         delete_breakpoint (b);
2801     }
2802
2803   /* Breakpoints set through other program spaces could have locations
2804      bound to PSPACE as well.  Remove those.  */
2805   ALL_BP_LOCATIONS (loc, loc_temp)
2806     {
2807       struct bp_location *tmp;
2808
2809       if (loc->pspace == pspace)
2810         {
2811           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2812           if (loc->owner->loc == loc)
2813             loc->owner->loc = loc->next;
2814           else
2815             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2816               if (tmp->next == loc)
2817                 {
2818                   tmp->next = loc->next;
2819                   break;
2820                 }
2821         }
2822     }
2823
2824   /* Now update the global location list to permanently delete the
2825      removed locations above.  */
2826   update_global_location_list (UGLL_DONT_INSERT);
2827 }
2828
2829 /* Make sure all breakpoints are inserted in inferior.
2830    Throws exception on any error.
2831    A breakpoint that is already inserted won't be inserted
2832    again, so calling this function twice is safe.  */
2833 void
2834 insert_breakpoints (void)
2835 {
2836   struct breakpoint *bpt;
2837
2838   ALL_BREAKPOINTS (bpt)
2839     if (is_hardware_watchpoint (bpt))
2840       {
2841         struct watchpoint *w = (struct watchpoint *) bpt;
2842
2843         update_watchpoint (w, 0 /* don't reparse.  */);
2844       }
2845
2846   /* Updating watchpoints creates new locations, so update the global
2847      location list.  Explicitly tell ugll to insert locations and
2848      ignore breakpoints_always_inserted_mode.  */
2849   update_global_location_list (UGLL_INSERT);
2850 }
2851
2852 /* Invoke CALLBACK for each of bp_location.  */
2853
2854 void
2855 iterate_over_bp_locations (walk_bp_location_callback callback)
2856 {
2857   struct bp_location *loc, **loc_tmp;
2858
2859   ALL_BP_LOCATIONS (loc, loc_tmp)
2860     {
2861       callback (loc, NULL);
2862     }
2863 }
2864
2865 /* This is used when we need to synch breakpoint conditions between GDB and the
2866    target.  It is the case with deleting and disabling of breakpoints when using
2867    always-inserted mode.  */
2868
2869 static void
2870 update_inserted_breakpoint_locations (void)
2871 {
2872   struct bp_location *bl, **blp_tmp;
2873   int error_flag = 0;
2874   int val = 0;
2875   int disabled_breaks = 0;
2876   int hw_breakpoint_error = 0;
2877   int hw_bp_details_reported = 0;
2878
2879   string_file tmp_error_stream;
2880
2881   /* Explicitly mark the warning -- this will only be printed if
2882      there was an error.  */
2883   tmp_error_stream.puts ("Warning:\n");
2884
2885   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2886
2887   ALL_BP_LOCATIONS (bl, blp_tmp)
2888     {
2889       /* We only want to update software breakpoints and hardware
2890          breakpoints.  */
2891       if (!is_breakpoint (bl->owner))
2892         continue;
2893
2894       /* We only want to update locations that are already inserted
2895          and need updating.  This is to avoid unwanted insertion during
2896          deletion of breakpoints.  */
2897       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2898         continue;
2899
2900       switch_to_program_space_and_thread (bl->pspace);
2901
2902       /* For targets that support global breakpoints, there's no need
2903          to select an inferior to insert breakpoint to.  In fact, even
2904          if we aren't attached to any process yet, we should still
2905          insert breakpoints.  */
2906       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2907           && ptid_equal (inferior_ptid, null_ptid))
2908         continue;
2909
2910       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2911                                     &hw_breakpoint_error, &hw_bp_details_reported);
2912       if (val)
2913         error_flag = val;
2914     }
2915
2916   if (error_flag)
2917     {
2918       target_terminal::ours_for_output ();
2919       error_stream (tmp_error_stream);
2920     }
2921 }
2922
2923 /* Used when starting or continuing the program.  */
2924
2925 static void
2926 insert_breakpoint_locations (void)
2927 {
2928   struct breakpoint *bpt;
2929   struct bp_location *bl, **blp_tmp;
2930   int error_flag = 0;
2931   int val = 0;
2932   int disabled_breaks = 0;
2933   int hw_breakpoint_error = 0;
2934   int hw_bp_error_explained_already = 0;
2935
2936   string_file tmp_error_stream;
2937
2938   /* Explicitly mark the warning -- this will only be printed if
2939      there was an error.  */
2940   tmp_error_stream.puts ("Warning:\n");
2941
2942   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2943
2944   ALL_BP_LOCATIONS (bl, blp_tmp)
2945     {
2946       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2947         continue;
2948
2949       /* There is no point inserting thread-specific breakpoints if
2950          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2951          has BL->OWNER always non-NULL.  */
2952       if (bl->owner->thread != -1
2953           && !valid_global_thread_id (bl->owner->thread))
2954         continue;
2955
2956       switch_to_program_space_and_thread (bl->pspace);
2957
2958       /* For targets that support global breakpoints, there's no need
2959          to select an inferior to insert breakpoint to.  In fact, even
2960          if we aren't attached to any process yet, we should still
2961          insert breakpoints.  */
2962       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2963           && ptid_equal (inferior_ptid, null_ptid))
2964         continue;
2965
2966       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2967                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
2968       if (val)
2969         error_flag = val;
2970     }
2971
2972   /* If we failed to insert all locations of a watchpoint, remove
2973      them, as half-inserted watchpoint is of limited use.  */
2974   ALL_BREAKPOINTS (bpt)  
2975     {
2976       int some_failed = 0;
2977       struct bp_location *loc;
2978
2979       if (!is_hardware_watchpoint (bpt))
2980         continue;
2981
2982       if (!breakpoint_enabled (bpt))
2983         continue;
2984
2985       if (bpt->disposition == disp_del_at_next_stop)
2986         continue;
2987       
2988       for (loc = bpt->loc; loc; loc = loc->next)
2989         if (!loc->inserted && should_be_inserted (loc))
2990           {
2991             some_failed = 1;
2992             break;
2993           }
2994       if (some_failed)
2995         {
2996           for (loc = bpt->loc; loc; loc = loc->next)
2997             if (loc->inserted)
2998               remove_breakpoint (loc);
2999
3000           hw_breakpoint_error = 1;
3001           tmp_error_stream.printf ("Could not insert "
3002                                    "hardware watchpoint %d.\n",
3003                                    bpt->number);
3004           error_flag = -1;
3005         }
3006     }
3007
3008   if (error_flag)
3009     {
3010       /* If a hardware breakpoint or watchpoint was inserted, add a
3011          message about possibly exhausted resources.  */
3012       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3013         {
3014           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3015 You may have requested too many hardware breakpoints/watchpoints.\n");
3016         }
3017       target_terminal::ours_for_output ();
3018       error_stream (tmp_error_stream);
3019     }
3020 }
3021
3022 /* Used when the program stops.
3023    Returns zero if successful, or non-zero if there was a problem
3024    removing a breakpoint location.  */
3025
3026 int
3027 remove_breakpoints (void)
3028 {
3029   struct bp_location *bl, **blp_tmp;
3030   int val = 0;
3031
3032   ALL_BP_LOCATIONS (bl, blp_tmp)
3033   {
3034     if (bl->inserted && !is_tracepoint (bl->owner))
3035       val |= remove_breakpoint (bl);
3036   }
3037   return val;
3038 }
3039
3040 /* When a thread exits, remove breakpoints that are related to
3041    that thread.  */
3042
3043 static void
3044 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3045 {
3046   struct breakpoint *b, *b_tmp;
3047
3048   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3049     {
3050       if (b->thread == tp->global_num && user_breakpoint_p (b))
3051         {
3052           b->disposition = disp_del_at_next_stop;
3053
3054           printf_filtered (_("\
3055 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3056                            b->number, print_thread_id (tp));
3057
3058           /* Hide it from the user.  */
3059           b->number = 0;
3060        }
3061     }
3062 }
3063
3064 /* Remove breakpoints of process PID.  */
3065
3066 int
3067 remove_breakpoints_pid (int pid)
3068 {
3069   struct bp_location *bl, **blp_tmp;
3070   int val;
3071   struct inferior *inf = find_inferior_pid (pid);
3072
3073   ALL_BP_LOCATIONS (bl, blp_tmp)
3074   {
3075     if (bl->pspace != inf->pspace)
3076       continue;
3077
3078     if (bl->inserted && !bl->target_info.persist)
3079       {
3080         val = remove_breakpoint (bl);
3081         if (val != 0)
3082           return val;
3083       }
3084   }
3085   return 0;
3086 }
3087
3088 static int internal_breakpoint_number = -1;
3089
3090 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3091    If INTERNAL is non-zero, the breakpoint number will be populated
3092    from internal_breakpoint_number and that variable decremented.
3093    Otherwise the breakpoint number will be populated from
3094    breakpoint_count and that value incremented.  Internal breakpoints
3095    do not set the internal var bpnum.  */
3096 static void
3097 set_breakpoint_number (int internal, struct breakpoint *b)
3098 {
3099   if (internal)
3100     b->number = internal_breakpoint_number--;
3101   else
3102     {
3103       set_breakpoint_count (breakpoint_count + 1);
3104       b->number = breakpoint_count;
3105     }
3106 }
3107
3108 static struct breakpoint *
3109 create_internal_breakpoint (struct gdbarch *gdbarch,
3110                             CORE_ADDR address, enum bptype type,
3111                             const struct breakpoint_ops *ops)
3112 {
3113   symtab_and_line sal;
3114   sal.pc = address;
3115   sal.section = find_pc_overlay (sal.pc);
3116   sal.pspace = current_program_space;
3117
3118   breakpoint *b = set_raw_breakpoint (gdbarch, sal, type, ops);
3119   b->number = internal_breakpoint_number--;
3120   b->disposition = disp_donttouch;
3121
3122   return b;
3123 }
3124
3125 static const char *const longjmp_names[] =
3126   {
3127     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3128   };
3129 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3130
3131 /* Per-objfile data private to breakpoint.c.  */
3132 struct breakpoint_objfile_data
3133 {
3134   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3135   struct bound_minimal_symbol overlay_msym {};
3136
3137   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3138   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES] {};
3139
3140   /* True if we have looked for longjmp probes.  */
3141   int longjmp_searched = 0;
3142
3143   /* SystemTap probe points for longjmp (if any).  These are non-owning
3144      references.  */
3145   std::vector<probe *> longjmp_probes;
3146
3147   /* Minimal symbol for "std::terminate()" (if any).  */
3148   struct bound_minimal_symbol terminate_msym {};
3149
3150   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3151   struct bound_minimal_symbol exception_msym {};
3152
3153   /* True if we have looked for exception probes.  */
3154   int exception_searched = 0;
3155
3156   /* SystemTap probe points for unwinding (if any).  These are non-owning
3157      references.  */
3158   std::vector<probe *> exception_probes;
3159 };
3160
3161 static const struct objfile_data *breakpoint_objfile_key;
3162
3163 /* Minimal symbol not found sentinel.  */
3164 static struct minimal_symbol msym_not_found;
3165
3166 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3167
3168 static int
3169 msym_not_found_p (const struct minimal_symbol *msym)
3170 {
3171   return msym == &msym_not_found;
3172 }
3173
3174 /* Return per-objfile data needed by breakpoint.c.
3175    Allocate the data if necessary.  */
3176
3177 static struct breakpoint_objfile_data *
3178 get_breakpoint_objfile_data (struct objfile *objfile)
3179 {
3180   struct breakpoint_objfile_data *bp_objfile_data;
3181
3182   bp_objfile_data = ((struct breakpoint_objfile_data *)
3183                      objfile_data (objfile, breakpoint_objfile_key));
3184   if (bp_objfile_data == NULL)
3185     {
3186       bp_objfile_data = new breakpoint_objfile_data ();
3187       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3188     }
3189   return bp_objfile_data;
3190 }
3191
3192 static void
3193 free_breakpoint_objfile_data (struct objfile *obj, void *data)
3194 {
3195   struct breakpoint_objfile_data *bp_objfile_data
3196     = (struct breakpoint_objfile_data *) data;
3197
3198   delete bp_objfile_data;
3199 }
3200
3201 static void
3202 create_overlay_event_breakpoint (void)
3203 {
3204   struct objfile *objfile;
3205   const char *const func_name = "_ovly_debug_event";
3206
3207   ALL_OBJFILES (objfile)
3208     {
3209       struct breakpoint *b;
3210       struct breakpoint_objfile_data *bp_objfile_data;
3211       CORE_ADDR addr;
3212       struct explicit_location explicit_loc;
3213
3214       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3215
3216       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3217         continue;
3218
3219       if (bp_objfile_data->overlay_msym.minsym == NULL)
3220         {
3221           struct bound_minimal_symbol m;
3222
3223           m = lookup_minimal_symbol_text (func_name, objfile);
3224           if (m.minsym == NULL)
3225             {
3226               /* Avoid future lookups in this objfile.  */
3227               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3228               continue;
3229             }
3230           bp_objfile_data->overlay_msym = m;
3231         }
3232
3233       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3234       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3235                                       bp_overlay_event,
3236                                       &internal_breakpoint_ops);
3237       initialize_explicit_location (&explicit_loc);
3238       explicit_loc.function_name = ASTRDUP (func_name);
3239       b->location = new_explicit_location (&explicit_loc);
3240
3241       if (overlay_debugging == ovly_auto)
3242         {
3243           b->enable_state = bp_enabled;
3244           overlay_events_enabled = 1;
3245         }
3246       else
3247        {
3248          b->enable_state = bp_disabled;
3249          overlay_events_enabled = 0;
3250        }
3251     }
3252 }
3253
3254 static void
3255 create_longjmp_master_breakpoint (void)
3256 {
3257   struct program_space *pspace;
3258
3259   scoped_restore_current_program_space restore_pspace;
3260
3261   ALL_PSPACES (pspace)
3262   {
3263     struct objfile *objfile;
3264
3265     set_current_program_space (pspace);
3266
3267     ALL_OBJFILES (objfile)
3268     {
3269       int i;
3270       struct gdbarch *gdbarch;
3271       struct breakpoint_objfile_data *bp_objfile_data;
3272
3273       gdbarch = get_objfile_arch (objfile);
3274
3275       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3276
3277       if (!bp_objfile_data->longjmp_searched)
3278         {
3279           std::vector<probe *> ret
3280             = find_probes_in_objfile (objfile, "libc", "longjmp");
3281
3282           if (!ret.empty ())
3283             {
3284               /* We are only interested in checking one element.  */
3285               probe *p = ret[0];
3286
3287               if (!p->can_evaluate_arguments ())
3288                 {
3289                   /* We cannot use the probe interface here, because it does
3290                      not know how to evaluate arguments.  */
3291                   ret.clear ();
3292                 }
3293             }
3294           bp_objfile_data->longjmp_probes = ret;
3295           bp_objfile_data->longjmp_searched = 1;
3296         }
3297
3298       if (!bp_objfile_data->longjmp_probes.empty ())
3299         {
3300           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3301
3302           for (probe *p : bp_objfile_data->longjmp_probes)
3303             {
3304               struct breakpoint *b;
3305
3306               b = create_internal_breakpoint (gdbarch,
3307                                               p->get_relocated_address (objfile),
3308                                               bp_longjmp_master,
3309                                               &internal_breakpoint_ops);
3310               b->location = new_probe_location ("-probe-stap libc:longjmp");
3311               b->enable_state = bp_disabled;
3312             }
3313
3314           continue;
3315         }
3316
3317       if (!gdbarch_get_longjmp_target_p (gdbarch))
3318         continue;
3319
3320       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3321         {
3322           struct breakpoint *b;
3323           const char *func_name;
3324           CORE_ADDR addr;
3325           struct explicit_location explicit_loc;
3326
3327           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3328             continue;
3329
3330           func_name = longjmp_names[i];
3331           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3332             {
3333               struct bound_minimal_symbol m;
3334
3335               m = lookup_minimal_symbol_text (func_name, objfile);
3336               if (m.minsym == NULL)
3337                 {
3338                   /* Prevent future lookups in this objfile.  */
3339                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3340                   continue;
3341                 }
3342               bp_objfile_data->longjmp_msym[i] = m;
3343             }
3344
3345           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3346           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3347                                           &internal_breakpoint_ops);
3348           initialize_explicit_location (&explicit_loc);
3349           explicit_loc.function_name = ASTRDUP (func_name);
3350           b->location = new_explicit_location (&explicit_loc);
3351           b->enable_state = bp_disabled;
3352         }
3353     }
3354   }
3355 }
3356
3357 /* Create a master std::terminate breakpoint.  */
3358 static void
3359 create_std_terminate_master_breakpoint (void)
3360 {
3361   struct program_space *pspace;
3362   const char *const func_name = "std::terminate()";
3363
3364   scoped_restore_current_program_space restore_pspace;
3365
3366   ALL_PSPACES (pspace)
3367   {
3368     struct objfile *objfile;
3369     CORE_ADDR addr;
3370
3371     set_current_program_space (pspace);
3372
3373     ALL_OBJFILES (objfile)
3374     {
3375       struct breakpoint *b;
3376       struct breakpoint_objfile_data *bp_objfile_data;
3377       struct explicit_location explicit_loc;
3378
3379       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3380
3381       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3382         continue;
3383
3384       if (bp_objfile_data->terminate_msym.minsym == NULL)
3385         {
3386           struct bound_minimal_symbol m;
3387
3388           m = lookup_minimal_symbol (func_name, NULL, objfile);
3389           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3390                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3391             {
3392               /* Prevent future lookups in this objfile.  */
3393               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3394               continue;
3395             }
3396           bp_objfile_data->terminate_msym = m;
3397         }
3398
3399       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3400       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3401                                       bp_std_terminate_master,
3402                                       &internal_breakpoint_ops);
3403       initialize_explicit_location (&explicit_loc);
3404       explicit_loc.function_name = ASTRDUP (func_name);
3405       b->location = new_explicit_location (&explicit_loc);
3406       b->enable_state = bp_disabled;
3407     }
3408   }
3409 }
3410
3411 /* Install a master breakpoint on the unwinder's debug hook.  */
3412
3413 static void
3414 create_exception_master_breakpoint (void)
3415 {
3416   struct objfile *objfile;
3417   const char *const func_name = "_Unwind_DebugHook";
3418
3419   ALL_OBJFILES (objfile)
3420     {
3421       struct breakpoint *b;
3422       struct gdbarch *gdbarch;
3423       struct breakpoint_objfile_data *bp_objfile_data;
3424       CORE_ADDR addr;
3425       struct explicit_location explicit_loc;
3426
3427       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3428
3429       /* We prefer the SystemTap probe point if it exists.  */
3430       if (!bp_objfile_data->exception_searched)
3431         {
3432           std::vector<probe *> ret
3433             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3434
3435           if (!ret.empty ())
3436             {
3437               /* We are only interested in checking one element.  */
3438               probe *p = ret[0];
3439
3440               if (!p->can_evaluate_arguments ())
3441                 {
3442                   /* We cannot use the probe interface here, because it does
3443                      not know how to evaluate arguments.  */
3444                   ret.clear ();
3445                 }
3446             }
3447           bp_objfile_data->exception_probes = ret;
3448           bp_objfile_data->exception_searched = 1;
3449         }
3450
3451       if (!bp_objfile_data->exception_probes.empty ())
3452         {
3453           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3454
3455           for (probe *p : bp_objfile_data->exception_probes)
3456             {
3457               struct breakpoint *b;
3458
3459               b = create_internal_breakpoint (gdbarch,
3460                                               p->get_relocated_address (objfile),
3461                                               bp_exception_master,
3462                                               &internal_breakpoint_ops);
3463               b->location = new_probe_location ("-probe-stap libgcc:unwind");
3464               b->enable_state = bp_disabled;
3465             }
3466
3467           continue;
3468         }
3469
3470       /* Otherwise, try the hook function.  */
3471
3472       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3473         continue;
3474
3475       gdbarch = get_objfile_arch (objfile);
3476
3477       if (bp_objfile_data->exception_msym.minsym == NULL)
3478         {
3479           struct bound_minimal_symbol debug_hook;
3480
3481           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3482           if (debug_hook.minsym == NULL)
3483             {
3484               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3485               continue;
3486             }
3487
3488           bp_objfile_data->exception_msym = debug_hook;
3489         }
3490
3491       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3492       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr, target_stack);
3493       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3494                                       &internal_breakpoint_ops);
3495       initialize_explicit_location (&explicit_loc);
3496       explicit_loc.function_name = ASTRDUP (func_name);
3497       b->location = new_explicit_location (&explicit_loc);
3498       b->enable_state = bp_disabled;
3499     }
3500 }
3501
3502 /* Does B have a location spec?  */
3503
3504 static int
3505 breakpoint_event_location_empty_p (const struct breakpoint *b)
3506 {
3507   return b->location != NULL && event_location_empty_p (b->location.get ());
3508 }
3509
3510 void
3511 update_breakpoints_after_exec (void)
3512 {
3513   struct breakpoint *b, *b_tmp;
3514   struct bp_location *bploc, **bplocp_tmp;
3515
3516   /* We're about to delete breakpoints from GDB's lists.  If the
3517      INSERTED flag is true, GDB will try to lift the breakpoints by
3518      writing the breakpoints' "shadow contents" back into memory.  The
3519      "shadow contents" are NOT valid after an exec, so GDB should not
3520      do that.  Instead, the target is responsible from marking
3521      breakpoints out as soon as it detects an exec.  We don't do that
3522      here instead, because there may be other attempts to delete
3523      breakpoints after detecting an exec and before reaching here.  */
3524   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3525     if (bploc->pspace == current_program_space)
3526       gdb_assert (!bploc->inserted);
3527
3528   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3529   {
3530     if (b->pspace != current_program_space)
3531       continue;
3532
3533     /* Solib breakpoints must be explicitly reset after an exec().  */
3534     if (b->type == bp_shlib_event)
3535       {
3536         delete_breakpoint (b);
3537         continue;
3538       }
3539
3540     /* JIT breakpoints must be explicitly reset after an exec().  */
3541     if (b->type == bp_jit_event)
3542       {
3543         delete_breakpoint (b);
3544         continue;
3545       }
3546
3547     /* Thread event breakpoints must be set anew after an exec(),
3548        as must overlay event and longjmp master breakpoints.  */
3549     if (b->type == bp_thread_event || b->type == bp_overlay_event
3550         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3551         || b->type == bp_exception_master)
3552       {
3553         delete_breakpoint (b);
3554         continue;
3555       }
3556
3557     /* Step-resume breakpoints are meaningless after an exec().  */
3558     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3559       {
3560         delete_breakpoint (b);
3561         continue;
3562       }
3563
3564     /* Just like single-step breakpoints.  */
3565     if (b->type == bp_single_step)
3566       {
3567         delete_breakpoint (b);
3568         continue;
3569       }
3570
3571     /* Longjmp and longjmp-resume breakpoints are also meaningless
3572        after an exec.  */
3573     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3574         || b->type == bp_longjmp_call_dummy
3575         || b->type == bp_exception || b->type == bp_exception_resume)
3576       {
3577         delete_breakpoint (b);
3578         continue;
3579       }
3580
3581     if (b->type == bp_catchpoint)
3582       {
3583         /* For now, none of the bp_catchpoint breakpoints need to
3584            do anything at this point.  In the future, if some of
3585            the catchpoints need to something, we will need to add
3586            a new method, and call this method from here.  */
3587         continue;
3588       }
3589
3590     /* bp_finish is a special case.  The only way we ought to be able
3591        to see one of these when an exec() has happened, is if the user
3592        caught a vfork, and then said "finish".  Ordinarily a finish just
3593        carries them to the call-site of the current callee, by setting
3594        a temporary bp there and resuming.  But in this case, the finish
3595        will carry them entirely through the vfork & exec.
3596
3597        We don't want to allow a bp_finish to remain inserted now.  But
3598        we can't safely delete it, 'cause finish_command has a handle to
3599        the bp on a bpstat, and will later want to delete it.  There's a
3600        chance (and I've seen it happen) that if we delete the bp_finish
3601        here, that its storage will get reused by the time finish_command
3602        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3603        We really must allow finish_command to delete a bp_finish.
3604
3605        In the absence of a general solution for the "how do we know
3606        it's safe to delete something others may have handles to?"
3607        problem, what we'll do here is just uninsert the bp_finish, and
3608        let finish_command delete it.
3609
3610        (We know the bp_finish is "doomed" in the sense that it's
3611        momentary, and will be deleted as soon as finish_command sees
3612        the inferior stopped.  So it doesn't matter that the bp's
3613        address is probably bogus in the new a.out, unlike e.g., the
3614        solib breakpoints.)  */
3615
3616     if (b->type == bp_finish)
3617       {
3618         continue;
3619       }
3620
3621     /* Without a symbolic address, we have little hope of the
3622        pre-exec() address meaning the same thing in the post-exec()
3623        a.out.  */
3624     if (breakpoint_event_location_empty_p (b))
3625       {
3626         delete_breakpoint (b);
3627         continue;
3628       }
3629   }
3630 }
3631
3632 int
3633 detach_breakpoints (ptid_t ptid)
3634 {
3635   struct bp_location *bl, **blp_tmp;
3636   int val = 0;
3637   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3638   struct inferior *inf = current_inferior ();
3639
3640   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3641     error (_("Cannot detach breakpoints of inferior_ptid"));
3642
3643   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3644   inferior_ptid = ptid;
3645   ALL_BP_LOCATIONS (bl, blp_tmp)
3646   {
3647     if (bl->pspace != inf->pspace)
3648       continue;
3649
3650     /* This function must physically remove breakpoints locations
3651        from the specified ptid, without modifying the breakpoint
3652        package's state.  Locations of type bp_loc_other are only
3653        maintained at GDB side.  So, there is no need to remove
3654        these bp_loc_other locations.  Moreover, removing these
3655        would modify the breakpoint package's state.  */
3656     if (bl->loc_type == bp_loc_other)
3657       continue;
3658
3659     if (bl->inserted)
3660       val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3661   }
3662
3663   return val;
3664 }
3665
3666 /* Remove the breakpoint location BL from the current address space.
3667    Note that this is used to detach breakpoints from a child fork.
3668    When we get here, the child isn't in the inferior list, and neither
3669    do we have objects to represent its address space --- we should
3670    *not* look at bl->pspace->aspace here.  */
3671
3672 static int
3673 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3674 {
3675   int val;
3676
3677   /* BL is never in moribund_locations by our callers.  */
3678   gdb_assert (bl->owner != NULL);
3679
3680   /* The type of none suggests that owner is actually deleted.
3681      This should not ever happen.  */
3682   gdb_assert (bl->owner->type != bp_none);
3683
3684   if (bl->loc_type == bp_loc_software_breakpoint
3685       || bl->loc_type == bp_loc_hardware_breakpoint)
3686     {
3687       /* "Normal" instruction breakpoint: either the standard
3688          trap-instruction bp (bp_breakpoint), or a
3689          bp_hardware_breakpoint.  */
3690
3691       /* First check to see if we have to handle an overlay.  */
3692       if (overlay_debugging == ovly_off
3693           || bl->section == NULL
3694           || !(section_is_overlay (bl->section)))
3695         {
3696           /* No overlay handling: just remove the breakpoint.  */
3697
3698           /* If we're trying to uninsert a memory breakpoint that we
3699              know is set in a dynamic object that is marked
3700              shlib_disabled, then either the dynamic object was
3701              removed with "remove-symbol-file" or with
3702              "nosharedlibrary".  In the former case, we don't know
3703              whether another dynamic object might have loaded over the
3704              breakpoint's address -- the user might well let us know
3705              about it next with add-symbol-file (the whole point of
3706              add-symbol-file is letting the user manually maintain a
3707              list of dynamically loaded objects).  If we have the
3708              breakpoint's shadow memory, that is, this is a software
3709              breakpoint managed by GDB, check whether the breakpoint
3710              is still inserted in memory, to avoid overwriting wrong
3711              code with stale saved shadow contents.  Note that HW
3712              breakpoints don't have shadow memory, as they're
3713              implemented using a mechanism that is not dependent on
3714              being able to modify the target's memory, and as such
3715              they should always be removed.  */
3716           if (bl->shlib_disabled
3717               && bl->target_info.shadow_len != 0
3718               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3719             val = 0;
3720           else
3721             val = bl->owner->ops->remove_location (bl, reason);
3722         }
3723       else
3724         {
3725           /* This breakpoint is in an overlay section.
3726              Did we set a breakpoint at the LMA?  */
3727           if (!overlay_events_enabled)
3728               {
3729                 /* Yes -- overlay event support is not active, so we
3730                    should have set a breakpoint at the LMA.  Remove it.  
3731                 */
3732                 /* Ignore any failures: if the LMA is in ROM, we will
3733                    have already warned when we failed to insert it.  */
3734                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3735                   target_remove_hw_breakpoint (bl->gdbarch,
3736                                                &bl->overlay_target_info);
3737                 else
3738                   target_remove_breakpoint (bl->gdbarch,
3739                                             &bl->overlay_target_info,
3740                                             reason);
3741               }
3742           /* Did we set a breakpoint at the VMA? 
3743              If so, we will have marked the breakpoint 'inserted'.  */
3744           if (bl->inserted)
3745             {
3746               /* Yes -- remove it.  Previously we did not bother to
3747                  remove the breakpoint if the section had been
3748                  unmapped, but let's not rely on that being safe.  We
3749                  don't know what the overlay manager might do.  */
3750
3751               /* However, we should remove *software* breakpoints only
3752                  if the section is still mapped, or else we overwrite
3753                  wrong code with the saved shadow contents.  */
3754               if (bl->loc_type == bp_loc_hardware_breakpoint
3755                   || section_is_mapped (bl->section))
3756                 val = bl->owner->ops->remove_location (bl, reason);
3757               else
3758                 val = 0;
3759             }
3760           else
3761             {
3762               /* No -- not inserted, so no need to remove.  No error.  */
3763               val = 0;
3764             }
3765         }
3766
3767       /* In some cases, we might not be able to remove a breakpoint in
3768          a shared library that has already been removed, but we have
3769          not yet processed the shlib unload event.  Similarly for an
3770          unloaded add-symbol-file object - the user might not yet have
3771          had the chance to remove-symbol-file it.  shlib_disabled will
3772          be set if the library/object has already been removed, but
3773          the breakpoint hasn't been uninserted yet, e.g., after
3774          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3775          always-inserted mode.  */
3776       if (val
3777           && (bl->loc_type == bp_loc_software_breakpoint
3778               && (bl->shlib_disabled
3779                   || solib_name_from_address (bl->pspace, bl->address)
3780                   || shared_objfile_contains_address_p (bl->pspace,
3781                                                         bl->address))))
3782         val = 0;
3783
3784       if (val)
3785         return val;
3786       bl->inserted = (reason == DETACH_BREAKPOINT);
3787     }
3788   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3789     {
3790       gdb_assert (bl->owner->ops != NULL
3791                   && bl->owner->ops->remove_location != NULL);
3792
3793       bl->inserted = (reason == DETACH_BREAKPOINT);
3794       bl->owner->ops->remove_location (bl, reason);
3795
3796       /* Failure to remove any of the hardware watchpoints comes here.  */
3797       if (reason == REMOVE_BREAKPOINT && bl->inserted)
3798         warning (_("Could not remove hardware watchpoint %d."),
3799                  bl->owner->number);
3800     }
3801   else if (bl->owner->type == bp_catchpoint
3802            && breakpoint_enabled (bl->owner)
3803            && !bl->duplicate)
3804     {
3805       gdb_assert (bl->owner->ops != NULL
3806                   && bl->owner->ops->remove_location != NULL);
3807
3808       val = bl->owner->ops->remove_location (bl, reason);
3809       if (val)
3810         return val;
3811
3812       bl->inserted = (reason == DETACH_BREAKPOINT);
3813     }
3814
3815   return 0;
3816 }
3817
3818 static int
3819 remove_breakpoint (struct bp_location *bl)
3820 {
3821   /* BL is never in moribund_locations by our callers.  */
3822   gdb_assert (bl->owner != NULL);
3823
3824   /* The type of none suggests that owner is actually deleted.
3825      This should not ever happen.  */
3826   gdb_assert (bl->owner->type != bp_none);
3827
3828   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3829
3830   switch_to_program_space_and_thread (bl->pspace);
3831
3832   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
3833 }
3834
3835 /* Clear the "inserted" flag in all breakpoints.  */
3836
3837 void
3838 mark_breakpoints_out (void)
3839 {
3840   struct bp_location *bl, **blp_tmp;
3841
3842   ALL_BP_LOCATIONS (bl, blp_tmp)
3843     if (bl->pspace == current_program_space)
3844       bl->inserted = 0;
3845 }
3846
3847 /* Clear the "inserted" flag in all breakpoints and delete any
3848    breakpoints which should go away between runs of the program.
3849
3850    Plus other such housekeeping that has to be done for breakpoints
3851    between runs.
3852
3853    Note: this function gets called at the end of a run (by
3854    generic_mourn_inferior) and when a run begins (by
3855    init_wait_for_inferior).  */
3856
3857
3858
3859 void
3860 breakpoint_init_inferior (enum inf_context context)
3861 {
3862   struct breakpoint *b, *b_tmp;
3863   struct bp_location *bl;
3864   int ix;
3865   struct program_space *pspace = current_program_space;
3866
3867   /* If breakpoint locations are shared across processes, then there's
3868      nothing to do.  */
3869   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3870     return;
3871
3872   mark_breakpoints_out ();
3873
3874   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3875   {
3876     if (b->loc && b->loc->pspace != pspace)
3877       continue;
3878
3879     switch (b->type)
3880       {
3881       case bp_call_dummy:
3882       case bp_longjmp_call_dummy:
3883
3884         /* If the call dummy breakpoint is at the entry point it will
3885            cause problems when the inferior is rerun, so we better get
3886            rid of it.  */
3887
3888       case bp_watchpoint_scope:
3889
3890         /* Also get rid of scope breakpoints.  */
3891
3892       case bp_shlib_event:
3893
3894         /* Also remove solib event breakpoints.  Their addresses may
3895            have changed since the last time we ran the program.
3896            Actually we may now be debugging against different target;
3897            and so the solib backend that installed this breakpoint may
3898            not be used in by the target.  E.g.,
3899
3900            (gdb) file prog-linux
3901            (gdb) run               # native linux target
3902            ...
3903            (gdb) kill
3904            (gdb) file prog-win.exe
3905            (gdb) tar rem :9999     # remote Windows gdbserver.
3906         */
3907
3908       case bp_step_resume:
3909
3910         /* Also remove step-resume breakpoints.  */
3911
3912       case bp_single_step:
3913
3914         /* Also remove single-step breakpoints.  */
3915
3916         delete_breakpoint (b);
3917         break;
3918
3919       case bp_watchpoint:
3920       case bp_hardware_watchpoint:
3921       case bp_read_watchpoint:
3922       case bp_access_watchpoint:
3923         {
3924           struct watchpoint *w = (struct watchpoint *) b;
3925
3926           /* Likewise for watchpoints on local expressions.  */
3927           if (w->exp_valid_block != NULL)
3928             delete_breakpoint (b);
3929           else
3930             {
3931               /* Get rid of existing locations, which are no longer
3932                  valid.  New ones will be created in
3933                  update_watchpoint, when the inferior is restarted.
3934                  The next update_global_location_list call will
3935                  garbage collect them.  */
3936               b->loc = NULL;
3937
3938               if (context == inf_starting)
3939                 {
3940                   /* Reset val field to force reread of starting value in
3941                      insert_breakpoints.  */
3942                   w->val.reset (nullptr);
3943                   w->val_valid = 0;
3944                 }
3945             }
3946         }
3947         break;
3948       default:
3949         break;
3950       }
3951   }
3952
3953   /* Get rid of the moribund locations.  */
3954   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3955     decref_bp_location (&bl);
3956   VEC_free (bp_location_p, moribund_locations);
3957 }
3958
3959 /* These functions concern about actual breakpoints inserted in the
3960    target --- to e.g. check if we need to do decr_pc adjustment or if
3961    we need to hop over the bkpt --- so we check for address space
3962    match, not program space.  */
3963
3964 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3965    exists at PC.  It returns ordinary_breakpoint_here if it's an
3966    ordinary breakpoint, or permanent_breakpoint_here if it's a
3967    permanent breakpoint.
3968    - When continuing from a location with an ordinary breakpoint, we
3969      actually single step once before calling insert_breakpoints.
3970    - When continuing from a location with a permanent breakpoint, we
3971      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3972      the target, to advance the PC past the breakpoint.  */
3973
3974 enum breakpoint_here
3975 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
3976 {
3977   struct bp_location *bl, **blp_tmp;
3978   int any_breakpoint_here = 0;
3979
3980   ALL_BP_LOCATIONS (bl, blp_tmp)
3981     {
3982       if (bl->loc_type != bp_loc_software_breakpoint
3983           && bl->loc_type != bp_loc_hardware_breakpoint)
3984         continue;
3985
3986       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3987       if ((breakpoint_enabled (bl->owner)
3988            || bl->permanent)
3989           && breakpoint_location_address_match (bl, aspace, pc))
3990         {
3991           if (overlay_debugging 
3992               && section_is_overlay (bl->section)
3993               && !section_is_mapped (bl->section))
3994             continue;           /* unmapped overlay -- can't be a match */
3995           else if (bl->permanent)
3996             return permanent_breakpoint_here;
3997           else
3998             any_breakpoint_here = 1;
3999         }
4000     }
4001
4002   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4003 }
4004
4005 /* See breakpoint.h.  */
4006
4007 int
4008 breakpoint_in_range_p (const address_space *aspace,
4009                        CORE_ADDR addr, ULONGEST len)
4010 {
4011   struct bp_location *bl, **blp_tmp;
4012
4013   ALL_BP_LOCATIONS (bl, blp_tmp)
4014     {
4015       if (bl->loc_type != bp_loc_software_breakpoint
4016           && bl->loc_type != bp_loc_hardware_breakpoint)
4017         continue;
4018
4019       if ((breakpoint_enabled (bl->owner)
4020            || bl->permanent)
4021           && breakpoint_location_address_range_overlap (bl, aspace,
4022                                                         addr, len))
4023         {
4024           if (overlay_debugging
4025               && section_is_overlay (bl->section)
4026               && !section_is_mapped (bl->section))
4027             {
4028               /* Unmapped overlay -- can't be a match.  */
4029               continue;
4030             }
4031
4032           return 1;
4033         }
4034     }
4035
4036   return 0;
4037 }
4038
4039 /* Return true if there's a moribund breakpoint at PC.  */
4040
4041 int
4042 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4043 {
4044   struct bp_location *loc;
4045   int ix;
4046
4047   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4048     if (breakpoint_location_address_match (loc, aspace, pc))
4049       return 1;
4050
4051   return 0;
4052 }
4053
4054 /* Returns non-zero iff BL is inserted at PC, in address space
4055    ASPACE.  */
4056
4057 static int
4058 bp_location_inserted_here_p (struct bp_location *bl,
4059                              const address_space *aspace, CORE_ADDR pc)
4060 {
4061   if (bl->inserted
4062       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4063                                    aspace, pc))
4064     {
4065       if (overlay_debugging
4066           && section_is_overlay (bl->section)
4067           && !section_is_mapped (bl->section))
4068         return 0;               /* unmapped overlay -- can't be a match */
4069       else
4070         return 1;
4071     }
4072   return 0;
4073 }
4074
4075 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4076
4077 int
4078 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4079 {
4080   struct bp_location **blp, **blp_tmp = NULL;
4081
4082   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4083     {
4084       struct bp_location *bl = *blp;
4085
4086       if (bl->loc_type != bp_loc_software_breakpoint
4087           && bl->loc_type != bp_loc_hardware_breakpoint)
4088         continue;
4089
4090       if (bp_location_inserted_here_p (bl, aspace, pc))
4091         return 1;
4092     }
4093   return 0;
4094 }
4095
4096 /* This function returns non-zero iff there is a software breakpoint
4097    inserted at PC.  */
4098
4099 int
4100 software_breakpoint_inserted_here_p (const address_space *aspace,
4101                                      CORE_ADDR pc)
4102 {
4103   struct bp_location **blp, **blp_tmp = NULL;
4104
4105   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4106     {
4107       struct bp_location *bl = *blp;
4108
4109       if (bl->loc_type != bp_loc_software_breakpoint)
4110         continue;
4111
4112       if (bp_location_inserted_here_p (bl, aspace, pc))
4113         return 1;
4114     }
4115
4116   return 0;
4117 }
4118
4119 /* See breakpoint.h.  */
4120
4121 int
4122 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4123                                      CORE_ADDR pc)
4124 {
4125   struct bp_location **blp, **blp_tmp = NULL;
4126
4127   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4128     {
4129       struct bp_location *bl = *blp;
4130
4131       if (bl->loc_type != bp_loc_hardware_breakpoint)
4132         continue;
4133
4134       if (bp_location_inserted_here_p (bl, aspace, pc))
4135         return 1;
4136     }
4137
4138   return 0;
4139 }
4140
4141 int
4142 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4143                                        CORE_ADDR addr, ULONGEST len)
4144 {
4145   struct breakpoint *bpt;
4146
4147   ALL_BREAKPOINTS (bpt)
4148     {
4149       struct bp_location *loc;
4150
4151       if (bpt->type != bp_hardware_watchpoint
4152           && bpt->type != bp_access_watchpoint)
4153         continue;
4154
4155       if (!breakpoint_enabled (bpt))
4156         continue;
4157
4158       for (loc = bpt->loc; loc; loc = loc->next)
4159         if (loc->pspace->aspace == aspace && loc->inserted)
4160           {
4161             CORE_ADDR l, h;
4162
4163             /* Check for intersection.  */
4164             l = std::max<CORE_ADDR> (loc->address, addr);
4165             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4166             if (l < h)
4167               return 1;
4168           }
4169     }
4170   return 0;
4171 }
4172 \f
4173
4174 /* bpstat stuff.  External routines' interfaces are documented
4175    in breakpoint.h.  */
4176
4177 int
4178 is_catchpoint (struct breakpoint *ep)
4179 {
4180   return (ep->type == bp_catchpoint);
4181 }
4182
4183 /* Frees any storage that is part of a bpstat.  Does not walk the
4184    'next' chain.  */
4185
4186 bpstats::~bpstats ()
4187 {
4188   if (bp_location_at != NULL)
4189     decref_bp_location (&bp_location_at);
4190 }
4191
4192 /* Clear a bpstat so that it says we are not at any breakpoint.
4193    Also free any storage that is part of a bpstat.  */
4194
4195 void
4196 bpstat_clear (bpstat *bsp)
4197 {
4198   bpstat p;
4199   bpstat q;
4200
4201   if (bsp == 0)
4202     return;
4203   p = *bsp;
4204   while (p != NULL)
4205     {
4206       q = p->next;
4207       delete p;
4208       p = q;
4209     }
4210   *bsp = NULL;
4211 }
4212
4213 bpstats::bpstats (const bpstats &other)
4214   : next (NULL),
4215     bp_location_at (other.bp_location_at),
4216     breakpoint_at (other.breakpoint_at),
4217     commands (other.commands),
4218     print (other.print),
4219     stop (other.stop),
4220     print_it (other.print_it)
4221 {
4222   if (other.old_val != NULL)
4223     old_val = release_value (value_copy (other.old_val.get ()));
4224   incref_bp_location (bp_location_at);
4225 }
4226
4227 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4228    is part of the bpstat is copied as well.  */
4229
4230 bpstat
4231 bpstat_copy (bpstat bs)
4232 {
4233   bpstat p = NULL;
4234   bpstat tmp;
4235   bpstat retval = NULL;
4236
4237   if (bs == NULL)
4238     return bs;
4239
4240   for (; bs != NULL; bs = bs->next)
4241     {
4242       tmp = new bpstats (*bs);
4243
4244       if (p == NULL)
4245         /* This is the first thing in the chain.  */
4246         retval = tmp;
4247       else
4248         p->next = tmp;
4249       p = tmp;
4250     }
4251   p->next = NULL;
4252   return retval;
4253 }
4254
4255 /* Find the bpstat associated with this breakpoint.  */
4256
4257 bpstat
4258 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4259 {
4260   if (bsp == NULL)
4261     return NULL;
4262
4263   for (; bsp != NULL; bsp = bsp->next)
4264     {
4265       if (bsp->breakpoint_at == breakpoint)
4266         return bsp;
4267     }
4268   return NULL;
4269 }
4270
4271 /* See breakpoint.h.  */
4272
4273 int
4274 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4275 {
4276   for (; bsp != NULL; bsp = bsp->next)
4277     {
4278       if (bsp->breakpoint_at == NULL)
4279         {
4280           /* A moribund location can never explain a signal other than
4281              GDB_SIGNAL_TRAP.  */
4282           if (sig == GDB_SIGNAL_TRAP)
4283             return 1;
4284         }
4285       else
4286         {
4287           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4288                                                         sig))
4289             return 1;
4290         }
4291     }
4292
4293   return 0;
4294 }
4295
4296 /* Put in *NUM the breakpoint number of the first breakpoint we are
4297    stopped at.  *BSP upon return is a bpstat which points to the
4298    remaining breakpoints stopped at (but which is not guaranteed to be
4299    good for anything but further calls to bpstat_num).
4300
4301    Return 0 if passed a bpstat which does not indicate any breakpoints.
4302    Return -1 if stopped at a breakpoint that has been deleted since
4303    we set it.
4304    Return 1 otherwise.  */
4305
4306 int
4307 bpstat_num (bpstat *bsp, int *num)
4308 {
4309   struct breakpoint *b;
4310
4311   if ((*bsp) == NULL)
4312     return 0;                   /* No more breakpoint values */
4313
4314   /* We assume we'll never have several bpstats that correspond to a
4315      single breakpoint -- otherwise, this function might return the
4316      same number more than once and this will look ugly.  */
4317   b = (*bsp)->breakpoint_at;
4318   *bsp = (*bsp)->next;
4319   if (b == NULL)
4320     return -1;                  /* breakpoint that's been deleted since */
4321
4322   *num = b->number;             /* We have its number */
4323   return 1;
4324 }
4325
4326 /* See breakpoint.h.  */
4327
4328 void
4329 bpstat_clear_actions (void)
4330 {
4331   struct thread_info *tp;
4332   bpstat bs;
4333
4334   if (ptid_equal (inferior_ptid, null_ptid))
4335     return;
4336
4337   tp = find_thread_ptid (inferior_ptid);
4338   if (tp == NULL)
4339     return;
4340
4341   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4342     {
4343       bs->commands = NULL;
4344       bs->old_val.reset (nullptr);
4345     }
4346 }
4347
4348 /* Called when a command is about to proceed the inferior.  */
4349
4350 static void
4351 breakpoint_about_to_proceed (void)
4352 {
4353   if (!ptid_equal (inferior_ptid, null_ptid))
4354     {
4355       struct thread_info *tp = inferior_thread ();
4356
4357       /* Allow inferior function calls in breakpoint commands to not
4358          interrupt the command list.  When the call finishes
4359          successfully, the inferior will be standing at the same
4360          breakpoint as if nothing happened.  */
4361       if (tp->control.in_infcall)
4362         return;
4363     }
4364
4365   breakpoint_proceeded = 1;
4366 }
4367
4368 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4369    or its equivalent.  */
4370
4371 static int
4372 command_line_is_silent (struct command_line *cmd)
4373 {
4374   return cmd && (strcmp ("silent", cmd->line) == 0);
4375 }
4376
4377 /* Execute all the commands associated with all the breakpoints at
4378    this location.  Any of these commands could cause the process to
4379    proceed beyond this point, etc.  We look out for such changes by
4380    checking the global "breakpoint_proceeded" after each command.
4381
4382    Returns true if a breakpoint command resumed the inferior.  In that
4383    case, it is the caller's responsibility to recall it again with the
4384    bpstat of the current thread.  */
4385
4386 static int
4387 bpstat_do_actions_1 (bpstat *bsp)
4388 {
4389   bpstat bs;
4390   int again = 0;
4391
4392   /* Avoid endless recursion if a `source' command is contained
4393      in bs->commands.  */
4394   if (executing_breakpoint_commands)
4395     return 0;
4396
4397   scoped_restore save_executing
4398     = make_scoped_restore (&executing_breakpoint_commands, 1);
4399
4400   scoped_restore preventer = prevent_dont_repeat ();
4401
4402   /* This pointer will iterate over the list of bpstat's.  */
4403   bs = *bsp;
4404
4405   breakpoint_proceeded = 0;
4406   for (; bs != NULL; bs = bs->next)
4407     {
4408       struct command_line *cmd = NULL;
4409
4410       /* Take ownership of the BSP's command tree, if it has one.
4411
4412          The command tree could legitimately contain commands like
4413          'step' and 'next', which call clear_proceed_status, which
4414          frees stop_bpstat's command tree.  To make sure this doesn't
4415          free the tree we're executing out from under us, we need to
4416          take ownership of the tree ourselves.  Since a given bpstat's
4417          commands are only executed once, we don't need to copy it; we
4418          can clear the pointer in the bpstat, and make sure we free
4419          the tree when we're done.  */
4420       counted_command_line ccmd = bs->commands;
4421       bs->commands = NULL;
4422       if (ccmd != NULL)
4423         cmd = ccmd.get ();
4424       if (command_line_is_silent (cmd))
4425         {
4426           /* The action has been already done by bpstat_stop_status.  */
4427           cmd = cmd->next;
4428         }
4429
4430       while (cmd != NULL)
4431         {
4432           execute_control_command (cmd);
4433
4434           if (breakpoint_proceeded)
4435             break;
4436           else
4437             cmd = cmd->next;
4438         }
4439
4440       if (breakpoint_proceeded)
4441         {
4442           if (current_ui->async)
4443             /* If we are in async mode, then the target might be still
4444                running, not stopped at any breakpoint, so nothing for
4445                us to do here -- just return to the event loop.  */
4446             ;
4447           else
4448             /* In sync mode, when execute_control_command returns
4449                we're already standing on the next breakpoint.
4450                Breakpoint commands for that stop were not run, since
4451                execute_command does not run breakpoint commands --
4452                only command_line_handler does, but that one is not
4453                involved in execution of breakpoint commands.  So, we
4454                can now execute breakpoint commands.  It should be
4455                noted that making execute_command do bpstat actions is
4456                not an option -- in this case we'll have recursive
4457                invocation of bpstat for each breakpoint with a
4458                command, and can easily blow up GDB stack.  Instead, we
4459                return true, which will trigger the caller to recall us
4460                with the new stop_bpstat.  */
4461             again = 1;
4462           break;
4463         }
4464     }
4465   return again;
4466 }
4467
4468 void
4469 bpstat_do_actions (void)
4470 {
4471   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4472
4473   /* Do any commands attached to breakpoint we are stopped at.  */
4474   while (!ptid_equal (inferior_ptid, null_ptid)
4475          && target_has_execution
4476          && !is_exited (inferior_ptid)
4477          && !is_executing (inferior_ptid))
4478     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4479        and only return when it is stopped at the next breakpoint, we
4480        keep doing breakpoint actions until it returns false to
4481        indicate the inferior was not resumed.  */
4482     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4483       break;
4484
4485   discard_cleanups (cleanup_if_error);
4486 }
4487
4488 /* Print out the (old or new) value associated with a watchpoint.  */
4489
4490 static void
4491 watchpoint_value_print (struct value *val, struct ui_file *stream)
4492 {
4493   if (val == NULL)
4494     fprintf_unfiltered (stream, _("<unreadable>"));
4495   else
4496     {
4497       struct value_print_options opts;
4498       get_user_print_options (&opts);
4499       value_print (val, stream, &opts);
4500     }
4501 }
4502
4503 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4504    debugging multiple threads.  */
4505
4506 void
4507 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4508 {
4509   if (uiout->is_mi_like_p ())
4510     return;
4511
4512   uiout->text ("\n");
4513
4514   if (show_thread_that_caused_stop ())
4515     {
4516       const char *name;
4517       struct thread_info *thr = inferior_thread ();
4518
4519       uiout->text ("Thread ");
4520       uiout->field_fmt ("thread-id", "%s", print_thread_id (thr));
4521
4522       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4523       if (name != NULL)
4524         {
4525           uiout->text (" \"");
4526           uiout->field_fmt ("name", "%s", name);
4527           uiout->text ("\"");
4528         }
4529
4530       uiout->text (" hit ");
4531     }
4532 }
4533
4534 /* Generic routine for printing messages indicating why we
4535    stopped.  The behavior of this function depends on the value
4536    'print_it' in the bpstat structure.  Under some circumstances we
4537    may decide not to print anything here and delegate the task to
4538    normal_stop().  */
4539
4540 static enum print_stop_action
4541 print_bp_stop_message (bpstat bs)
4542 {
4543   switch (bs->print_it)
4544     {
4545     case print_it_noop:
4546       /* Nothing should be printed for this bpstat entry.  */
4547       return PRINT_UNKNOWN;
4548       break;
4549
4550     case print_it_done:
4551       /* We still want to print the frame, but we already printed the
4552          relevant messages.  */
4553       return PRINT_SRC_AND_LOC;
4554       break;
4555
4556     case print_it_normal:
4557       {
4558         struct breakpoint *b = bs->breakpoint_at;
4559
4560         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4561            which has since been deleted.  */
4562         if (b == NULL)
4563           return PRINT_UNKNOWN;
4564
4565         /* Normal case.  Call the breakpoint's print_it method.  */
4566         return b->ops->print_it (bs);
4567       }
4568       break;
4569
4570     default:
4571       internal_error (__FILE__, __LINE__,
4572                       _("print_bp_stop_message: unrecognized enum value"));
4573       break;
4574     }
4575 }
4576
4577 /* A helper function that prints a shared library stopped event.  */
4578
4579 static void
4580 print_solib_event (int is_catchpoint)
4581 {
4582   bool any_deleted = !current_program_space->deleted_solibs.empty ();
4583   bool any_added = !current_program_space->added_solibs.empty ();
4584
4585   if (!is_catchpoint)
4586     {
4587       if (any_added || any_deleted)
4588         current_uiout->text (_("Stopped due to shared library event:\n"));
4589       else
4590         current_uiout->text (_("Stopped due to shared library event (no "
4591                                "libraries added or removed)\n"));
4592     }
4593
4594   if (current_uiout->is_mi_like_p ())
4595     current_uiout->field_string ("reason",
4596                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4597
4598   if (any_deleted)
4599     {
4600       current_uiout->text (_("  Inferior unloaded "));
4601       ui_out_emit_list list_emitter (current_uiout, "removed");
4602       for (int ix = 0; ix < current_program_space->deleted_solibs.size (); ix++)
4603         {
4604           const std::string &name = current_program_space->deleted_solibs[ix];
4605
4606           if (ix > 0)
4607             current_uiout->text ("    ");
4608           current_uiout->field_string ("library", name);
4609           current_uiout->text ("\n");
4610         }
4611     }
4612
4613   if (any_added)
4614     {
4615       current_uiout->text (_("  Inferior loaded "));
4616       ui_out_emit_list list_emitter (current_uiout, "added");
4617       bool first = true;
4618       for (so_list *iter : current_program_space->added_solibs)
4619         {
4620           if (!first)
4621             current_uiout->text ("    ");
4622           first = false;
4623           current_uiout->field_string ("library", iter->so_name);
4624           current_uiout->text ("\n");
4625         }
4626     }
4627 }
4628
4629 /* Print a message indicating what happened.  This is called from
4630    normal_stop().  The input to this routine is the head of the bpstat
4631    list - a list of the eventpoints that caused this stop.  KIND is
4632    the target_waitkind for the stopping event.  This
4633    routine calls the generic print routine for printing a message
4634    about reasons for stopping.  This will print (for example) the
4635    "Breakpoint n," part of the output.  The return value of this
4636    routine is one of:
4637
4638    PRINT_UNKNOWN: Means we printed nothing.
4639    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4640    code to print the location.  An example is 
4641    "Breakpoint 1, " which should be followed by
4642    the location.
4643    PRINT_SRC_ONLY: Means we printed something, but there is no need
4644    to also print the location part of the message.
4645    An example is the catch/throw messages, which
4646    don't require a location appended to the end.
4647    PRINT_NOTHING: We have done some printing and we don't need any 
4648    further info to be printed.  */
4649
4650 enum print_stop_action
4651 bpstat_print (bpstat bs, int kind)
4652 {
4653   enum print_stop_action val;
4654
4655   /* Maybe another breakpoint in the chain caused us to stop.
4656      (Currently all watchpoints go on the bpstat whether hit or not.
4657      That probably could (should) be changed, provided care is taken
4658      with respect to bpstat_explains_signal).  */
4659   for (; bs; bs = bs->next)
4660     {
4661       val = print_bp_stop_message (bs);
4662       if (val == PRINT_SRC_ONLY 
4663           || val == PRINT_SRC_AND_LOC 
4664           || val == PRINT_NOTHING)
4665         return val;
4666     }
4667
4668   /* If we had hit a shared library event breakpoint,
4669      print_bp_stop_message would print out this message.  If we hit an
4670      OS-level shared library event, do the same thing.  */
4671   if (kind == TARGET_WAITKIND_LOADED)
4672     {
4673       print_solib_event (0);
4674       return PRINT_NOTHING;
4675     }
4676
4677   /* We reached the end of the chain, or we got a null BS to start
4678      with and nothing was printed.  */
4679   return PRINT_UNKNOWN;
4680 }
4681
4682 /* Evaluate the boolean expression EXP and return the result.  */
4683
4684 static bool
4685 breakpoint_cond_eval (expression *exp)
4686 {
4687   struct value *mark = value_mark ();
4688   bool res = value_true (evaluate_expression (exp));
4689
4690   value_free_to_mark (mark);
4691   return res;
4692 }
4693
4694 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4695
4696 bpstats::bpstats (struct bp_location *bl, bpstat **bs_link_pointer)
4697   : next (NULL),
4698     bp_location_at (bl),
4699     breakpoint_at (bl->owner),
4700     commands (NULL),
4701     print (0),
4702     stop (0),
4703     print_it (print_it_normal)
4704 {
4705   incref_bp_location (bl);
4706   **bs_link_pointer = this;
4707   *bs_link_pointer = &next;
4708 }
4709
4710 bpstats::bpstats ()
4711   : next (NULL),
4712     bp_location_at (NULL),
4713     breakpoint_at (NULL),
4714     commands (NULL),
4715     print (0),
4716     stop (0),
4717     print_it (print_it_normal)
4718 {
4719 }
4720 \f
4721 /* The target has stopped with waitstatus WS.  Check if any hardware
4722    watchpoints have triggered, according to the target.  */
4723
4724 int
4725 watchpoints_triggered (struct target_waitstatus *ws)
4726 {
4727   bool stopped_by_watchpoint = target_stopped_by_watchpoint ();
4728   CORE_ADDR addr;
4729   struct breakpoint *b;
4730
4731   if (!stopped_by_watchpoint)
4732     {
4733       /* We were not stopped by a watchpoint.  Mark all watchpoints
4734          as not triggered.  */
4735       ALL_BREAKPOINTS (b)
4736         if (is_hardware_watchpoint (b))
4737           {
4738             struct watchpoint *w = (struct watchpoint *) b;
4739
4740             w->watchpoint_triggered = watch_triggered_no;
4741           }
4742
4743       return 0;
4744     }
4745
4746   if (!target_stopped_data_address (target_stack, &addr))
4747     {
4748       /* We were stopped by a watchpoint, but we don't know where.
4749          Mark all watchpoints as unknown.  */
4750       ALL_BREAKPOINTS (b)
4751         if (is_hardware_watchpoint (b))
4752           {
4753             struct watchpoint *w = (struct watchpoint *) b;
4754
4755             w->watchpoint_triggered = watch_triggered_unknown;
4756           }
4757
4758       return 1;
4759     }
4760
4761   /* The target could report the data address.  Mark watchpoints
4762      affected by this data address as triggered, and all others as not
4763      triggered.  */
4764
4765   ALL_BREAKPOINTS (b)
4766     if (is_hardware_watchpoint (b))
4767       {
4768         struct watchpoint *w = (struct watchpoint *) b;
4769         struct bp_location *loc;
4770
4771         w->watchpoint_triggered = watch_triggered_no;
4772         for (loc = b->loc; loc; loc = loc->next)
4773           {
4774             if (is_masked_watchpoint (b))
4775               {
4776                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4777                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4778
4779                 if (newaddr == start)
4780                   {
4781                     w->watchpoint_triggered = watch_triggered_yes;
4782                     break;
4783                   }
4784               }
4785             /* Exact match not required.  Within range is sufficient.  */
4786             else if (target_watchpoint_addr_within_range (target_stack,
4787                                                          addr, loc->address,
4788                                                          loc->length))
4789               {
4790                 w->watchpoint_triggered = watch_triggered_yes;
4791                 break;
4792               }
4793           }
4794       }
4795
4796   return 1;
4797 }
4798
4799 /* Possible return values for watchpoint_check.  */
4800 enum wp_check_result
4801   {
4802     /* The watchpoint has been deleted.  */
4803     WP_DELETED = 1,
4804
4805     /* The value has changed.  */
4806     WP_VALUE_CHANGED = 2,
4807
4808     /* The value has not changed.  */
4809     WP_VALUE_NOT_CHANGED = 3,
4810
4811     /* Ignore this watchpoint, no matter if the value changed or not.  */
4812     WP_IGNORE = 4,
4813   };
4814
4815 #define BP_TEMPFLAG 1
4816 #define BP_HARDWAREFLAG 2
4817
4818 /* Evaluate watchpoint condition expression and check if its value
4819    changed.  */
4820
4821 static wp_check_result
4822 watchpoint_check (bpstat bs)
4823 {
4824   struct watchpoint *b;
4825   struct frame_info *fr;
4826   int within_current_scope;
4827
4828   /* BS is built from an existing struct breakpoint.  */
4829   gdb_assert (bs->breakpoint_at != NULL);
4830   b = (struct watchpoint *) bs->breakpoint_at;
4831
4832   /* If this is a local watchpoint, we only want to check if the
4833      watchpoint frame is in scope if the current thread is the thread
4834      that was used to create the watchpoint.  */
4835   if (!watchpoint_in_thread_scope (b))
4836     return WP_IGNORE;
4837
4838   if (b->exp_valid_block == NULL)
4839     within_current_scope = 1;
4840   else
4841     {
4842       struct frame_info *frame = get_current_frame ();
4843       struct gdbarch *frame_arch = get_frame_arch (frame);
4844       CORE_ADDR frame_pc = get_frame_pc (frame);
4845
4846       /* stack_frame_destroyed_p() returns a non-zero value if we're
4847          still in the function but the stack frame has already been
4848          invalidated.  Since we can't rely on the values of local
4849          variables after the stack has been destroyed, we are treating
4850          the watchpoint in that state as `not changed' without further
4851          checking.  Don't mark watchpoints as changed if the current
4852          frame is in an epilogue - even if they are in some other
4853          frame, our view of the stack is likely to be wrong and
4854          frame_find_by_id could error out.  */
4855       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
4856         return WP_IGNORE;
4857
4858       fr = frame_find_by_id (b->watchpoint_frame);
4859       within_current_scope = (fr != NULL);
4860
4861       /* If we've gotten confused in the unwinder, we might have
4862          returned a frame that can't describe this variable.  */
4863       if (within_current_scope)
4864         {
4865           struct symbol *function;
4866
4867           function = get_frame_function (fr);
4868           if (function == NULL
4869               || !contained_in (b->exp_valid_block,
4870                                 SYMBOL_BLOCK_VALUE (function)))
4871             within_current_scope = 0;
4872         }
4873
4874       if (within_current_scope)
4875         /* If we end up stopping, the current frame will get selected
4876            in normal_stop.  So this call to select_frame won't affect
4877            the user.  */
4878         select_frame (fr);
4879     }
4880
4881   if (within_current_scope)
4882     {
4883       /* We use value_{,free_to_}mark because it could be a *long*
4884          time before we return to the command level and call
4885          free_all_values.  We can't call free_all_values because we
4886          might be in the middle of evaluating a function call.  */
4887
4888       int pc = 0;
4889       struct value *mark;
4890       struct value *new_val;
4891
4892       if (is_masked_watchpoint (b))
4893         /* Since we don't know the exact trigger address (from
4894            stopped_data_address), just tell the user we've triggered
4895            a mask watchpoint.  */
4896         return WP_VALUE_CHANGED;
4897
4898       mark = value_mark ();
4899       fetch_subexp_value (b->exp.get (), &pc, &new_val, NULL, NULL, 0);
4900
4901       if (b->val_bitsize != 0)
4902         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
4903
4904       /* We use value_equal_contents instead of value_equal because
4905          the latter coerces an array to a pointer, thus comparing just
4906          the address of the array instead of its contents.  This is
4907          not what we want.  */
4908       if ((b->val != NULL) != (new_val != NULL)
4909           || (b->val != NULL && !value_equal_contents (b->val.get (),
4910                                                        new_val)))
4911         {
4912           bs->old_val = b->val;
4913           b->val = release_value (new_val);
4914           b->val_valid = 1;
4915           if (new_val != NULL)
4916             value_free_to_mark (mark);
4917           return WP_VALUE_CHANGED;
4918         }
4919       else
4920         {
4921           /* Nothing changed.  */
4922           value_free_to_mark (mark);
4923           return WP_VALUE_NOT_CHANGED;
4924         }
4925     }
4926   else
4927     {
4928       /* This seems like the only logical thing to do because
4929          if we temporarily ignored the watchpoint, then when
4930          we reenter the block in which it is valid it contains
4931          garbage (in the case of a function, it may have two
4932          garbage values, one before and one after the prologue).
4933          So we can't even detect the first assignment to it and
4934          watch after that (since the garbage may or may not equal
4935          the first value assigned).  */
4936       /* We print all the stop information in
4937          breakpoint_ops->print_it, but in this case, by the time we
4938          call breakpoint_ops->print_it this bp will be deleted
4939          already.  So we have no choice but print the information
4940          here.  */
4941
4942       SWITCH_THRU_ALL_UIS ()
4943         {
4944           struct ui_out *uiout = current_uiout;
4945
4946           if (uiout->is_mi_like_p ())
4947             uiout->field_string
4948               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4949           uiout->text ("\nWatchpoint ");
4950           uiout->field_int ("wpnum", b->number);
4951           uiout->text (" deleted because the program has left the block in\n"
4952                        "which its expression is valid.\n");
4953         }
4954
4955       /* Make sure the watchpoint's commands aren't executed.  */
4956       b->commands = NULL;
4957       watchpoint_del_at_next_stop (b);
4958
4959       return WP_DELETED;
4960     }
4961 }
4962
4963 /* Return true if it looks like target has stopped due to hitting
4964    breakpoint location BL.  This function does not check if we should
4965    stop, only if BL explains the stop.  */
4966
4967 static int
4968 bpstat_check_location (const struct bp_location *bl,
4969                        const address_space *aspace, CORE_ADDR bp_addr,
4970                        const struct target_waitstatus *ws)
4971 {
4972   struct breakpoint *b = bl->owner;
4973
4974   /* BL is from an existing breakpoint.  */
4975   gdb_assert (b != NULL);
4976
4977   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4978 }
4979
4980 /* Determine if the watched values have actually changed, and we
4981    should stop.  If not, set BS->stop to 0.  */
4982
4983 static void
4984 bpstat_check_watchpoint (bpstat bs)
4985 {
4986   const struct bp_location *bl;
4987   struct watchpoint *b;
4988
4989   /* BS is built for existing struct breakpoint.  */
4990   bl = bs->bp_location_at;
4991   gdb_assert (bl != NULL);
4992   b = (struct watchpoint *) bs->breakpoint_at;
4993   gdb_assert (b != NULL);
4994
4995     {
4996       int must_check_value = 0;
4997       
4998       if (b->type == bp_watchpoint)
4999         /* For a software watchpoint, we must always check the
5000            watched value.  */
5001         must_check_value = 1;
5002       else if (b->watchpoint_triggered == watch_triggered_yes)
5003         /* We have a hardware watchpoint (read, write, or access)
5004            and the target earlier reported an address watched by
5005            this watchpoint.  */
5006         must_check_value = 1;
5007       else if (b->watchpoint_triggered == watch_triggered_unknown
5008                && b->type == bp_hardware_watchpoint)
5009         /* We were stopped by a hardware watchpoint, but the target could
5010            not report the data address.  We must check the watchpoint's
5011            value.  Access and read watchpoints are out of luck; without
5012            a data address, we can't figure it out.  */
5013         must_check_value = 1;
5014
5015       if (must_check_value)
5016         {
5017           wp_check_result e;
5018
5019           TRY
5020             {
5021               e = watchpoint_check (bs);
5022             }
5023           CATCH (ex, RETURN_MASK_ALL)
5024             {
5025               exception_fprintf (gdb_stderr, ex,
5026                                  "Error evaluating expression "
5027                                  "for watchpoint %d\n",
5028                                  b->number);
5029
5030               SWITCH_THRU_ALL_UIS ()
5031                 {
5032                   printf_filtered (_("Watchpoint %d deleted.\n"),
5033                                    b->number);
5034                 }
5035               watchpoint_del_at_next_stop (b);
5036               e = WP_DELETED;
5037             }
5038           END_CATCH
5039
5040           switch (e)
5041             {
5042             case WP_DELETED:
5043               /* We've already printed what needs to be printed.  */
5044               bs->print_it = print_it_done;
5045               /* Stop.  */
5046               break;
5047             case WP_IGNORE:
5048               bs->print_it = print_it_noop;
5049               bs->stop = 0;
5050               break;
5051             case WP_VALUE_CHANGED:
5052               if (b->type == bp_read_watchpoint)
5053                 {
5054                   /* There are two cases to consider here:
5055
5056                      1. We're watching the triggered memory for reads.
5057                      In that case, trust the target, and always report
5058                      the watchpoint hit to the user.  Even though
5059                      reads don't cause value changes, the value may
5060                      have changed since the last time it was read, and
5061                      since we're not trapping writes, we will not see
5062                      those, and as such we should ignore our notion of
5063                      old value.
5064
5065                      2. We're watching the triggered memory for both
5066                      reads and writes.  There are two ways this may
5067                      happen:
5068
5069                      2.1. This is a target that can't break on data
5070                      reads only, but can break on accesses (reads or
5071                      writes), such as e.g., x86.  We detect this case
5072                      at the time we try to insert read watchpoints.
5073
5074                      2.2. Otherwise, the target supports read
5075                      watchpoints, but, the user set an access or write
5076                      watchpoint watching the same memory as this read
5077                      watchpoint.
5078
5079                      If we're watching memory writes as well as reads,
5080                      ignore watchpoint hits when we find that the
5081                      value hasn't changed, as reads don't cause
5082                      changes.  This still gives false positives when
5083                      the program writes the same value to memory as
5084                      what there was already in memory (we will confuse
5085                      it for a read), but it's much better than
5086                      nothing.  */
5087
5088                   int other_write_watchpoint = 0;
5089
5090                   if (bl->watchpoint_type == hw_read)
5091                     {
5092                       struct breakpoint *other_b;
5093
5094                       ALL_BREAKPOINTS (other_b)
5095                         if (other_b->type == bp_hardware_watchpoint
5096                             || other_b->type == bp_access_watchpoint)
5097                           {
5098                             struct watchpoint *other_w =
5099                               (struct watchpoint *) other_b;
5100
5101                             if (other_w->watchpoint_triggered
5102                                 == watch_triggered_yes)
5103                               {
5104                                 other_write_watchpoint = 1;
5105                                 break;
5106                               }
5107                           }
5108                     }
5109
5110                   if (other_write_watchpoint
5111                       || bl->watchpoint_type == hw_access)
5112                     {
5113                       /* We're watching the same memory for writes,
5114                          and the value changed since the last time we
5115                          updated it, so this trap must be for a write.
5116                          Ignore it.  */
5117                       bs->print_it = print_it_noop;
5118                       bs->stop = 0;
5119                     }
5120                 }
5121               break;
5122             case WP_VALUE_NOT_CHANGED:
5123               if (b->type == bp_hardware_watchpoint
5124                   || b->type == bp_watchpoint)
5125                 {
5126                   /* Don't stop: write watchpoints shouldn't fire if
5127                      the value hasn't changed.  */
5128                   bs->print_it = print_it_noop;
5129                   bs->stop = 0;
5130                 }
5131               /* Stop.  */
5132               break;
5133             default:
5134               /* Can't happen.  */
5135               break;
5136             }
5137         }
5138       else      /* must_check_value == 0 */
5139         {
5140           /* This is a case where some watchpoint(s) triggered, but
5141              not at the address of this watchpoint, or else no
5142              watchpoint triggered after all.  So don't print
5143              anything for this watchpoint.  */
5144           bs->print_it = print_it_noop;
5145           bs->stop = 0;
5146         }
5147     }
5148 }
5149
5150 /* For breakpoints that are currently marked as telling gdb to stop,
5151    check conditions (condition proper, frame, thread and ignore count)
5152    of breakpoint referred to by BS.  If we should not stop for this
5153    breakpoint, set BS->stop to 0.  */
5154
5155 static void
5156 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5157 {
5158   const struct bp_location *bl;
5159   struct breakpoint *b;
5160   /* Assume stop.  */
5161   bool condition_result = true;
5162   struct expression *cond;
5163
5164   gdb_assert (bs->stop);
5165
5166   /* BS is built for existing struct breakpoint.  */
5167   bl = bs->bp_location_at;
5168   gdb_assert (bl != NULL);
5169   b = bs->breakpoint_at;
5170   gdb_assert (b != NULL);
5171
5172   /* Even if the target evaluated the condition on its end and notified GDB, we
5173      need to do so again since GDB does not know if we stopped due to a
5174      breakpoint or a single step breakpoint.  */
5175
5176   if (frame_id_p (b->frame_id)
5177       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5178     {
5179       bs->stop = 0;
5180       return;
5181     }
5182
5183   /* If this is a thread/task-specific breakpoint, don't waste cpu
5184      evaluating the condition if this isn't the specified
5185      thread/task.  */
5186   if ((b->thread != -1 && b->thread != ptid_to_global_thread_id (ptid))
5187       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5188
5189     {
5190       bs->stop = 0;
5191       return;
5192     }
5193
5194   /* Evaluate extension language breakpoints that have a "stop" method
5195      implemented.  */
5196   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5197
5198   if (is_watchpoint (b))
5199     {
5200       struct watchpoint *w = (struct watchpoint *) b;
5201
5202       cond = w->cond_exp.get ();
5203     }
5204   else
5205     cond = bl->cond.get ();
5206
5207   if (cond && b->disposition != disp_del_at_next_stop)
5208     {
5209       int within_current_scope = 1;
5210       struct watchpoint * w;
5211
5212       /* We use value_mark and value_free_to_mark because it could
5213          be a long time before we return to the command level and
5214          call free_all_values.  We can't call free_all_values
5215          because we might be in the middle of evaluating a
5216          function call.  */
5217       struct value *mark = value_mark ();
5218
5219       if (is_watchpoint (b))
5220         w = (struct watchpoint *) b;
5221       else
5222         w = NULL;
5223
5224       /* Need to select the frame, with all that implies so that
5225          the conditions will have the right context.  Because we
5226          use the frame, we will not see an inlined function's
5227          variables when we arrive at a breakpoint at the start
5228          of the inlined function; the current frame will be the
5229          call site.  */
5230       if (w == NULL || w->cond_exp_valid_block == NULL)
5231         select_frame (get_current_frame ());
5232       else
5233         {
5234           struct frame_info *frame;
5235
5236           /* For local watchpoint expressions, which particular
5237              instance of a local is being watched matters, so we
5238              keep track of the frame to evaluate the expression
5239              in.  To evaluate the condition however, it doesn't
5240              really matter which instantiation of the function
5241              where the condition makes sense triggers the
5242              watchpoint.  This allows an expression like "watch
5243              global if q > 10" set in `func', catch writes to
5244              global on all threads that call `func', or catch
5245              writes on all recursive calls of `func' by a single
5246              thread.  We simply always evaluate the condition in
5247              the innermost frame that's executing where it makes
5248              sense to evaluate the condition.  It seems
5249              intuitive.  */
5250           frame = block_innermost_frame (w->cond_exp_valid_block);
5251           if (frame != NULL)
5252             select_frame (frame);
5253           else
5254             within_current_scope = 0;
5255         }
5256       if (within_current_scope)
5257         {
5258           TRY
5259             {
5260               condition_result = breakpoint_cond_eval (cond);
5261             }
5262           CATCH (ex, RETURN_MASK_ALL)
5263             {
5264               exception_fprintf (gdb_stderr, ex,
5265                                  "Error in testing breakpoint condition:\n");
5266             }
5267           END_CATCH
5268         }
5269       else
5270         {
5271           warning (_("Watchpoint condition cannot be tested "
5272                      "in the current scope"));
5273           /* If we failed to set the right context for this
5274              watchpoint, unconditionally report it.  */
5275         }
5276       /* FIXME-someday, should give breakpoint #.  */
5277       value_free_to_mark (mark);
5278     }
5279
5280   if (cond && !condition_result)
5281     {
5282       bs->stop = 0;
5283     }
5284   else if (b->ignore_count > 0)
5285     {
5286       b->ignore_count--;
5287       bs->stop = 0;
5288       /* Increase the hit count even though we don't stop.  */
5289       ++(b->hit_count);
5290       gdb::observers::breakpoint_modified.notify (b);
5291     }   
5292 }
5293
5294 /* Returns true if we need to track moribund locations of LOC's type
5295    on the current target.  */
5296
5297 static int
5298 need_moribund_for_location_type (struct bp_location *loc)
5299 {
5300   return ((loc->loc_type == bp_loc_software_breakpoint
5301            && !target_supports_stopped_by_sw_breakpoint ())
5302           || (loc->loc_type == bp_loc_hardware_breakpoint
5303               && !target_supports_stopped_by_hw_breakpoint ()));
5304 }
5305
5306 /* See breakpoint.h.  */
5307
5308 bpstat
5309 build_bpstat_chain (const address_space *aspace, CORE_ADDR bp_addr,
5310                     const struct target_waitstatus *ws)
5311 {
5312   struct breakpoint *b;
5313   bpstat bs_head = NULL, *bs_link = &bs_head;
5314
5315   ALL_BREAKPOINTS (b)
5316     {
5317       if (!breakpoint_enabled (b))
5318         continue;
5319
5320       for (bp_location *bl = b->loc; bl != NULL; bl = bl->next)
5321         {
5322           /* For hardware watchpoints, we look only at the first
5323              location.  The watchpoint_check function will work on the
5324              entire expression, not the individual locations.  For
5325              read watchpoints, the watchpoints_triggered function has
5326              checked all locations already.  */
5327           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5328             break;
5329
5330           if (!bl->enabled || bl->shlib_disabled)
5331             continue;
5332
5333           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5334             continue;
5335
5336           /* Come here if it's a watchpoint, or if the break address
5337              matches.  */
5338
5339           bpstat bs = new bpstats (bl, &bs_link);       /* Alloc a bpstat to
5340                                                            explain stop.  */
5341
5342           /* Assume we stop.  Should we find a watchpoint that is not
5343              actually triggered, or if the condition of the breakpoint
5344              evaluates as false, we'll reset 'stop' to 0.  */
5345           bs->stop = 1;
5346           bs->print = 1;
5347
5348           /* If this is a scope breakpoint, mark the associated
5349              watchpoint as triggered so that we will handle the
5350              out-of-scope event.  We'll get to the watchpoint next
5351              iteration.  */
5352           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5353             {
5354               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5355
5356               w->watchpoint_triggered = watch_triggered_yes;
5357             }
5358         }
5359     }
5360
5361   /* Check if a moribund breakpoint explains the stop.  */
5362   if (!target_supports_stopped_by_sw_breakpoint ()
5363       || !target_supports_stopped_by_hw_breakpoint ())
5364     {
5365       bp_location *loc;
5366
5367       for (int ix = 0;
5368            VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5369         {
5370           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5371               && need_moribund_for_location_type (loc))
5372             {
5373               bpstat bs = new bpstats (loc, &bs_link);
5374               /* For hits of moribund locations, we should just proceed.  */
5375               bs->stop = 0;
5376               bs->print = 0;
5377               bs->print_it = print_it_noop;
5378             }
5379         }
5380     }
5381
5382   return bs_head;
5383 }
5384
5385 /* See breakpoint.h.  */
5386
5387 bpstat
5388 bpstat_stop_status (const address_space *aspace,
5389                     CORE_ADDR bp_addr, ptid_t ptid,
5390                     const struct target_waitstatus *ws,
5391                     bpstat stop_chain)
5392 {
5393   struct breakpoint *b = NULL;
5394   /* First item of allocated bpstat's.  */
5395   bpstat bs_head = stop_chain;
5396   bpstat bs;
5397   int need_remove_insert;
5398   int removed_any;
5399
5400   /* First, build the bpstat chain with locations that explain a
5401      target stop, while being careful to not set the target running,
5402      as that may invalidate locations (in particular watchpoint
5403      locations are recreated).  Resuming will happen here with
5404      breakpoint conditions or watchpoint expressions that include
5405      inferior function calls.  */
5406   if (bs_head == NULL)
5407     bs_head = build_bpstat_chain (aspace, bp_addr, ws);
5408
5409   /* A bit of special processing for shlib breakpoints.  We need to
5410      process solib loading here, so that the lists of loaded and
5411      unloaded libraries are correct before we handle "catch load" and
5412      "catch unload".  */
5413   for (bs = bs_head; bs != NULL; bs = bs->next)
5414     {
5415       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5416         {
5417           handle_solib_event ();
5418           break;
5419         }
5420     }
5421
5422   /* Now go through the locations that caused the target to stop, and
5423      check whether we're interested in reporting this stop to higher
5424      layers, or whether we should resume the target transparently.  */
5425
5426   removed_any = 0;
5427
5428   for (bs = bs_head; bs != NULL; bs = bs->next)
5429     {
5430       if (!bs->stop)
5431         continue;
5432
5433       b = bs->breakpoint_at;
5434       b->ops->check_status (bs);
5435       if (bs->stop)
5436         {
5437           bpstat_check_breakpoint_conditions (bs, ptid);
5438
5439           if (bs->stop)
5440             {
5441               ++(b->hit_count);
5442               gdb::observers::breakpoint_modified.notify (b);
5443
5444               /* We will stop here.  */
5445               if (b->disposition == disp_disable)
5446                 {
5447                   --(b->enable_count);
5448                   if (b->enable_count <= 0)
5449                     b->enable_state = bp_disabled;
5450                   removed_any = 1;
5451                 }
5452               if (b->silent)
5453                 bs->print = 0;
5454               bs->commands = b->commands;
5455               if (command_line_is_silent (bs->commands
5456                                           ? bs->commands.get () : NULL))
5457                 bs->print = 0;
5458
5459               b->ops->after_condition_true (bs);
5460             }
5461
5462         }
5463
5464       /* Print nothing for this entry if we don't stop or don't
5465          print.  */
5466       if (!bs->stop || !bs->print)
5467         bs->print_it = print_it_noop;
5468     }
5469
5470   /* If we aren't stopping, the value of some hardware watchpoint may
5471      not have changed, but the intermediate memory locations we are
5472      watching may have.  Don't bother if we're stopping; this will get
5473      done later.  */
5474   need_remove_insert = 0;
5475   if (! bpstat_causes_stop (bs_head))
5476     for (bs = bs_head; bs != NULL; bs = bs->next)
5477       if (!bs->stop
5478           && bs->breakpoint_at
5479           && is_hardware_watchpoint (bs->breakpoint_at))
5480         {
5481           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5482
5483           update_watchpoint (w, 0 /* don't reparse.  */);
5484           need_remove_insert = 1;
5485         }
5486
5487   if (need_remove_insert)
5488     update_global_location_list (UGLL_MAY_INSERT);
5489   else if (removed_any)
5490     update_global_location_list (UGLL_DONT_INSERT);
5491
5492   return bs_head;
5493 }
5494
5495 static void
5496 handle_jit_event (void)
5497 {
5498   struct frame_info *frame;
5499   struct gdbarch *gdbarch;
5500
5501   if (debug_infrun)
5502     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5503
5504   /* Switch terminal for any messages produced by
5505      breakpoint_re_set.  */
5506   target_terminal::ours_for_output ();
5507
5508   frame = get_current_frame ();
5509   gdbarch = get_frame_arch (frame);
5510
5511   jit_event_handler (gdbarch);
5512
5513   target_terminal::inferior ();
5514 }
5515
5516 /* Prepare WHAT final decision for infrun.  */
5517
5518 /* Decide what infrun needs to do with this bpstat.  */
5519
5520 struct bpstat_what
5521 bpstat_what (bpstat bs_head)
5522 {
5523   struct bpstat_what retval;
5524   bpstat bs;
5525
5526   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5527   retval.call_dummy = STOP_NONE;
5528   retval.is_longjmp = 0;
5529
5530   for (bs = bs_head; bs != NULL; bs = bs->next)
5531     {
5532       /* Extract this BS's action.  After processing each BS, we check
5533          if its action overrides all we've seem so far.  */
5534       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5535       enum bptype bptype;
5536
5537       if (bs->breakpoint_at == NULL)
5538         {
5539           /* I suspect this can happen if it was a momentary
5540              breakpoint which has since been deleted.  */
5541           bptype = bp_none;
5542         }
5543       else
5544         bptype = bs->breakpoint_at->type;
5545
5546       switch (bptype)
5547         {
5548         case bp_none:
5549           break;
5550         case bp_breakpoint:
5551         case bp_hardware_breakpoint:
5552         case bp_single_step:
5553         case bp_until:
5554         case bp_finish:
5555         case bp_shlib_event:
5556           if (bs->stop)
5557             {
5558               if (bs->print)
5559                 this_action = BPSTAT_WHAT_STOP_NOISY;
5560               else
5561                 this_action = BPSTAT_WHAT_STOP_SILENT;
5562             }
5563           else
5564             this_action = BPSTAT_WHAT_SINGLE;
5565           break;
5566         case bp_watchpoint:
5567         case bp_hardware_watchpoint:
5568         case bp_read_watchpoint:
5569         case bp_access_watchpoint:
5570           if (bs->stop)
5571             {
5572               if (bs->print)
5573                 this_action = BPSTAT_WHAT_STOP_NOISY;
5574               else
5575                 this_action = BPSTAT_WHAT_STOP_SILENT;
5576             }
5577           else
5578             {
5579               /* There was a watchpoint, but we're not stopping.
5580                  This requires no further action.  */
5581             }
5582           break;
5583         case bp_longjmp:
5584         case bp_longjmp_call_dummy:
5585         case bp_exception:
5586           if (bs->stop)
5587             {
5588               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5589               retval.is_longjmp = bptype != bp_exception;
5590             }
5591           else
5592             this_action = BPSTAT_WHAT_SINGLE;
5593           break;
5594         case bp_longjmp_resume:
5595         case bp_exception_resume:
5596           if (bs->stop)
5597             {
5598               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5599               retval.is_longjmp = bptype == bp_longjmp_resume;
5600             }
5601           else
5602             this_action = BPSTAT_WHAT_SINGLE;
5603           break;
5604         case bp_step_resume:
5605           if (bs->stop)
5606             this_action = BPSTAT_WHAT_STEP_RESUME;
5607           else
5608             {
5609               /* It is for the wrong frame.  */
5610               this_action = BPSTAT_WHAT_SINGLE;
5611             }
5612           break;
5613         case bp_hp_step_resume:
5614           if (bs->stop)
5615             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5616           else
5617             {
5618               /* It is for the wrong frame.  */
5619               this_action = BPSTAT_WHAT_SINGLE;
5620             }
5621           break;
5622         case bp_watchpoint_scope:
5623         case bp_thread_event:
5624         case bp_overlay_event:
5625         case bp_longjmp_master:
5626         case bp_std_terminate_master:
5627         case bp_exception_master:
5628           this_action = BPSTAT_WHAT_SINGLE;
5629           break;
5630         case bp_catchpoint:
5631           if (bs->stop)
5632             {
5633               if (bs->print)
5634                 this_action = BPSTAT_WHAT_STOP_NOISY;
5635               else
5636                 this_action = BPSTAT_WHAT_STOP_SILENT;
5637             }
5638           else
5639             {
5640               /* There was a catchpoint, but we're not stopping.
5641                  This requires no further action.  */
5642             }
5643           break;
5644         case bp_jit_event:
5645           this_action = BPSTAT_WHAT_SINGLE;
5646           break;
5647         case bp_call_dummy:
5648           /* Make sure the action is stop (silent or noisy),
5649              so infrun.c pops the dummy frame.  */
5650           retval.call_dummy = STOP_STACK_DUMMY;
5651           this_action = BPSTAT_WHAT_STOP_SILENT;
5652           break;
5653         case bp_std_terminate:
5654           /* Make sure the action is stop (silent or noisy),
5655              so infrun.c pops the dummy frame.  */
5656           retval.call_dummy = STOP_STD_TERMINATE;
5657           this_action = BPSTAT_WHAT_STOP_SILENT;
5658           break;
5659         case bp_tracepoint:
5660         case bp_fast_tracepoint:
5661         case bp_static_tracepoint:
5662           /* Tracepoint hits should not be reported back to GDB, and
5663              if one got through somehow, it should have been filtered
5664              out already.  */
5665           internal_error (__FILE__, __LINE__,
5666                           _("bpstat_what: tracepoint encountered"));
5667           break;
5668         case bp_gnu_ifunc_resolver:
5669           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5670           this_action = BPSTAT_WHAT_SINGLE;
5671           break;
5672         case bp_gnu_ifunc_resolver_return:
5673           /* The breakpoint will be removed, execution will restart from the
5674              PC of the former breakpoint.  */
5675           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5676           break;
5677
5678         case bp_dprintf:
5679           if (bs->stop)
5680             this_action = BPSTAT_WHAT_STOP_SILENT;
5681           else
5682             this_action = BPSTAT_WHAT_SINGLE;
5683           break;
5684
5685         default:
5686           internal_error (__FILE__, __LINE__,
5687                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5688         }
5689
5690       retval.main_action = std::max (retval.main_action, this_action);
5691     }
5692
5693   return retval;
5694 }
5695
5696 void
5697 bpstat_run_callbacks (bpstat bs_head)
5698 {
5699   bpstat bs;
5700
5701   for (bs = bs_head; bs != NULL; bs = bs->next)
5702     {
5703       struct breakpoint *b = bs->breakpoint_at;
5704
5705       if (b == NULL)
5706         continue;
5707       switch (b->type)
5708         {
5709         case bp_jit_event:
5710           handle_jit_event ();
5711           break;
5712         case bp_gnu_ifunc_resolver:
5713           gnu_ifunc_resolver_stop (b);
5714           break;
5715         case bp_gnu_ifunc_resolver_return:
5716           gnu_ifunc_resolver_return_stop (b);
5717           break;
5718         }
5719     }
5720 }
5721
5722 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5723    without hardware support).  This isn't related to a specific bpstat,
5724    just to things like whether watchpoints are set.  */
5725
5726 int
5727 bpstat_should_step (void)
5728 {
5729   struct breakpoint *b;
5730
5731   ALL_BREAKPOINTS (b)
5732     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5733       return 1;
5734   return 0;
5735 }
5736
5737 int
5738 bpstat_causes_stop (bpstat bs)
5739 {
5740   for (; bs != NULL; bs = bs->next)
5741     if (bs->stop)
5742       return 1;
5743
5744   return 0;
5745 }
5746
5747 \f
5748
5749 /* Compute a string of spaces suitable to indent the next line
5750    so it starts at the position corresponding to the table column
5751    named COL_NAME in the currently active table of UIOUT.  */
5752
5753 static char *
5754 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5755 {
5756   static char wrap_indent[80];
5757   int i, total_width, width, align;
5758   const char *text;
5759
5760   total_width = 0;
5761   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
5762     {
5763       if (strcmp (text, col_name) == 0)
5764         {
5765           gdb_assert (total_width < sizeof wrap_indent);
5766           memset (wrap_indent, ' ', total_width);
5767           wrap_indent[total_width] = 0;
5768
5769           return wrap_indent;
5770         }
5771
5772       total_width += width + 1;
5773     }
5774
5775   return NULL;
5776 }
5777
5778 /* Determine if the locations of this breakpoint will have their conditions
5779    evaluated by the target, host or a mix of both.  Returns the following:
5780
5781     "host": Host evals condition.
5782     "host or target": Host or Target evals condition.
5783     "target": Target evals condition.
5784 */
5785
5786 static const char *
5787 bp_condition_evaluator (struct breakpoint *b)
5788 {
5789   struct bp_location *bl;
5790   char host_evals = 0;
5791   char target_evals = 0;
5792
5793   if (!b)
5794     return NULL;
5795
5796   if (!is_breakpoint (b))
5797     return NULL;
5798
5799   if (gdb_evaluates_breakpoint_condition_p ()
5800       || !target_supports_evaluation_of_breakpoint_conditions ())
5801     return condition_evaluation_host;
5802
5803   for (bl = b->loc; bl; bl = bl->next)
5804     {
5805       if (bl->cond_bytecode)
5806         target_evals++;
5807       else
5808         host_evals++;
5809     }
5810
5811   if (host_evals && target_evals)
5812     return condition_evaluation_both;
5813   else if (target_evals)
5814     return condition_evaluation_target;
5815   else
5816     return condition_evaluation_host;
5817 }
5818
5819 /* Determine the breakpoint location's condition evaluator.  This is
5820    similar to bp_condition_evaluator, but for locations.  */
5821
5822 static const char *
5823 bp_location_condition_evaluator (struct bp_location *bl)
5824 {
5825   if (bl && !is_breakpoint (bl->owner))
5826     return NULL;
5827
5828   if (gdb_evaluates_breakpoint_condition_p ()
5829       || !target_supports_evaluation_of_breakpoint_conditions ())
5830     return condition_evaluation_host;
5831
5832   if (bl && bl->cond_bytecode)
5833     return condition_evaluation_target;
5834   else
5835     return condition_evaluation_host;
5836 }
5837
5838 /* Print the LOC location out of the list of B->LOC locations.  */
5839
5840 static void
5841 print_breakpoint_location (struct breakpoint *b,
5842                            struct bp_location *loc)
5843 {
5844   struct ui_out *uiout = current_uiout;
5845
5846   scoped_restore_current_program_space restore_pspace;
5847
5848   if (loc != NULL && loc->shlib_disabled)
5849     loc = NULL;
5850
5851   if (loc != NULL)
5852     set_current_program_space (loc->pspace);
5853
5854   if (b->display_canonical)
5855     uiout->field_string ("what", event_location_to_string (b->location.get ()));
5856   else if (loc && loc->symtab)
5857     {
5858       const struct symbol *sym = loc->symbol;
5859
5860       if (sym == NULL)
5861         sym = find_pc_sect_function (loc->address, loc->section);
5862
5863       if (sym)
5864         {
5865           uiout->text ("in ");
5866           uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
5867           uiout->text (" ");
5868           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
5869           uiout->text ("at ");
5870         }
5871       uiout->field_string ("file",
5872                            symtab_to_filename_for_display (loc->symtab));
5873       uiout->text (":");
5874
5875       if (uiout->is_mi_like_p ())
5876         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
5877       
5878       uiout->field_int ("line", loc->line_number);
5879     }
5880   else if (loc)
5881     {
5882       string_file stb;
5883
5884       print_address_symbolic (loc->gdbarch, loc->address, &stb,
5885                               demangle, "");
5886       uiout->field_stream ("at", stb);
5887     }
5888   else
5889     {
5890       uiout->field_string ("pending",
5891                            event_location_to_string (b->location.get ()));
5892       /* If extra_string is available, it could be holding a condition
5893          or dprintf arguments.  In either case, make sure it is printed,
5894          too, but only for non-MI streams.  */
5895       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
5896         {
5897           if (b->type == bp_dprintf)
5898             uiout->text (",");
5899           else
5900             uiout->text (" ");
5901           uiout->text (b->extra_string);
5902         }
5903     }
5904
5905   if (loc && is_breakpoint (b)
5906       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5907       && bp_condition_evaluator (b) == condition_evaluation_both)
5908     {
5909       uiout->text (" (");
5910       uiout->field_string ("evaluated-by",
5911                            bp_location_condition_evaluator (loc));
5912       uiout->text (")");
5913     }
5914 }
5915
5916 static const char *
5917 bptype_string (enum bptype type)
5918 {
5919   struct ep_type_description
5920     {
5921       enum bptype type;
5922       const char *description;
5923     };
5924   static struct ep_type_description bptypes[] =
5925   {
5926     {bp_none, "?deleted?"},
5927     {bp_breakpoint, "breakpoint"},
5928     {bp_hardware_breakpoint, "hw breakpoint"},
5929     {bp_single_step, "sw single-step"},
5930     {bp_until, "until"},
5931     {bp_finish, "finish"},
5932     {bp_watchpoint, "watchpoint"},
5933     {bp_hardware_watchpoint, "hw watchpoint"},
5934     {bp_read_watchpoint, "read watchpoint"},
5935     {bp_access_watchpoint, "acc watchpoint"},
5936     {bp_longjmp, "longjmp"},
5937     {bp_longjmp_resume, "longjmp resume"},
5938     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5939     {bp_exception, "exception"},
5940     {bp_exception_resume, "exception resume"},
5941     {bp_step_resume, "step resume"},
5942     {bp_hp_step_resume, "high-priority step resume"},
5943     {bp_watchpoint_scope, "watchpoint scope"},
5944     {bp_call_dummy, "call dummy"},
5945     {bp_std_terminate, "std::terminate"},
5946     {bp_shlib_event, "shlib events"},
5947     {bp_thread_event, "thread events"},
5948     {bp_overlay_event, "overlay events"},
5949     {bp_longjmp_master, "longjmp master"},
5950     {bp_std_terminate_master, "std::terminate master"},
5951     {bp_exception_master, "exception master"},
5952     {bp_catchpoint, "catchpoint"},
5953     {bp_tracepoint, "tracepoint"},
5954     {bp_fast_tracepoint, "fast tracepoint"},
5955     {bp_static_tracepoint, "static tracepoint"},
5956     {bp_dprintf, "dprintf"},
5957     {bp_jit_event, "jit events"},
5958     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5959     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5960   };
5961
5962   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5963       || ((int) type != bptypes[(int) type].type))
5964     internal_error (__FILE__, __LINE__,
5965                     _("bptypes table does not describe type #%d."),
5966                     (int) type);
5967
5968   return bptypes[(int) type].description;
5969 }
5970
5971 /* For MI, output a field named 'thread-groups' with a list as the value.
5972    For CLI, prefix the list with the string 'inf'. */
5973
5974 static void
5975 output_thread_groups (struct ui_out *uiout,
5976                       const char *field_name,
5977                       const std::vector<int> &inf_nums,
5978                       int mi_only)
5979 {
5980   int is_mi = uiout->is_mi_like_p ();
5981
5982   /* For backward compatibility, don't display inferiors in CLI unless
5983      there are several.  Always display them for MI. */
5984   if (!is_mi && mi_only)
5985     return;
5986
5987   ui_out_emit_list list_emitter (uiout, field_name);
5988
5989   for (size_t i = 0; i < inf_nums.size (); i++)
5990     {
5991       if (is_mi)
5992         {
5993           char mi_group[10];
5994
5995           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf_nums[i]);
5996           uiout->field_string (NULL, mi_group);
5997         }
5998       else
5999         {
6000           if (i == 0)
6001             uiout->text (" inf ");
6002           else
6003             uiout->text (", ");
6004         
6005           uiout->text (plongest (inf_nums[i]));
6006         }
6007     }
6008 }
6009
6010 /* Print B to gdb_stdout.  */
6011
6012 static void
6013 print_one_breakpoint_location (struct breakpoint *b,
6014                                struct bp_location *loc,
6015                                int loc_number,
6016                                struct bp_location **last_loc,
6017                                int allflag)
6018 {
6019   struct command_line *l;
6020   static char bpenables[] = "nynny";
6021
6022   struct ui_out *uiout = current_uiout;
6023   int header_of_multiple = 0;
6024   int part_of_multiple = (loc != NULL);
6025   struct value_print_options opts;
6026
6027   get_user_print_options (&opts);
6028
6029   gdb_assert (!loc || loc_number != 0);
6030   /* See comment in print_one_breakpoint concerning treatment of
6031      breakpoints with single disabled location.  */
6032   if (loc == NULL 
6033       && (b->loc != NULL 
6034           && (b->loc->next != NULL || !b->loc->enabled)))
6035     header_of_multiple = 1;
6036   if (loc == NULL)
6037     loc = b->loc;
6038
6039   annotate_record ();
6040
6041   /* 1 */
6042   annotate_field (0);
6043   if (part_of_multiple)
6044     {
6045       char *formatted;
6046       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6047       uiout->field_string ("number", formatted);
6048       xfree (formatted);
6049     }
6050   else
6051     {
6052       uiout->field_int ("number", b->number);
6053     }
6054
6055   /* 2 */
6056   annotate_field (1);
6057   if (part_of_multiple)
6058     uiout->field_skip ("type");
6059   else
6060     uiout->field_string ("type", bptype_string (b->type));
6061
6062   /* 3 */
6063   annotate_field (2);
6064   if (part_of_multiple)
6065     uiout->field_skip ("disp");
6066   else
6067     uiout->field_string ("disp", bpdisp_text (b->disposition));
6068
6069
6070   /* 4 */
6071   annotate_field (3);
6072   if (part_of_multiple)
6073     uiout->field_string ("enabled", loc->enabled ? "y" : "n");
6074   else
6075     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6076   uiout->spaces (2);
6077
6078   
6079   /* 5 and 6 */
6080   if (b->ops != NULL && b->ops->print_one != NULL)
6081     {
6082       /* Although the print_one can possibly print all locations,
6083          calling it here is not likely to get any nice result.  So,
6084          make sure there's just one location.  */
6085       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6086       b->ops->print_one (b, last_loc);
6087     }
6088   else
6089     switch (b->type)
6090       {
6091       case bp_none:
6092         internal_error (__FILE__, __LINE__,
6093                         _("print_one_breakpoint: bp_none encountered\n"));
6094         break;
6095
6096       case bp_watchpoint:
6097       case bp_hardware_watchpoint:
6098       case bp_read_watchpoint:
6099       case bp_access_watchpoint:
6100         {
6101           struct watchpoint *w = (struct watchpoint *) b;
6102
6103           /* Field 4, the address, is omitted (which makes the columns
6104              not line up too nicely with the headers, but the effect
6105              is relatively readable).  */
6106           if (opts.addressprint)
6107             uiout->field_skip ("addr");
6108           annotate_field (5);
6109           uiout->field_string ("what", w->exp_string);
6110         }
6111         break;
6112
6113       case bp_breakpoint:
6114       case bp_hardware_breakpoint:
6115       case bp_single_step:
6116       case bp_until:
6117       case bp_finish:
6118       case bp_longjmp:
6119       case bp_longjmp_resume:
6120       case bp_longjmp_call_dummy:
6121       case bp_exception:
6122       case bp_exception_resume:
6123       case bp_step_resume:
6124       case bp_hp_step_resume:
6125       case bp_watchpoint_scope:
6126       case bp_call_dummy:
6127       case bp_std_terminate:
6128       case bp_shlib_event:
6129       case bp_thread_event:
6130       case bp_overlay_event:
6131       case bp_longjmp_master:
6132       case bp_std_terminate_master:
6133       case bp_exception_master:
6134       case bp_tracepoint:
6135       case bp_fast_tracepoint:
6136       case bp_static_tracepoint:
6137       case bp_dprintf:
6138       case bp_jit_event:
6139       case bp_gnu_ifunc_resolver:
6140       case bp_gnu_ifunc_resolver_return:
6141         if (opts.addressprint)
6142           {
6143             annotate_field (4);
6144             if (header_of_multiple)
6145               uiout->field_string ("addr", "<MULTIPLE>");
6146             else if (b->loc == NULL || loc->shlib_disabled)
6147               uiout->field_string ("addr", "<PENDING>");
6148             else
6149               uiout->field_core_addr ("addr",
6150                                       loc->gdbarch, loc->address);
6151           }
6152         annotate_field (5);
6153         if (!header_of_multiple)
6154           print_breakpoint_location (b, loc);
6155         if (b->loc)
6156           *last_loc = b->loc;
6157         break;
6158       }
6159
6160
6161   if (loc != NULL && !header_of_multiple)
6162     {
6163       struct inferior *inf;
6164       std::vector<int> inf_nums;
6165       int mi_only = 1;
6166
6167       ALL_INFERIORS (inf)
6168         {
6169           if (inf->pspace == loc->pspace)
6170             inf_nums.push_back (inf->num);
6171         }
6172
6173         /* For backward compatibility, don't display inferiors in CLI unless
6174            there are several.  Always display for MI. */
6175         if (allflag
6176             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6177                 && (number_of_program_spaces () > 1
6178                     || number_of_inferiors () > 1)
6179                 /* LOC is for existing B, it cannot be in
6180                    moribund_locations and thus having NULL OWNER.  */
6181                 && loc->owner->type != bp_catchpoint))
6182         mi_only = 0;
6183       output_thread_groups (uiout, "thread-groups", inf_nums, mi_only);
6184     }
6185
6186   if (!part_of_multiple)
6187     {
6188       if (b->thread != -1)
6189         {
6190           /* FIXME: This seems to be redundant and lost here; see the
6191              "stop only in" line a little further down.  */
6192           uiout->text (" thread ");
6193           uiout->field_int ("thread", b->thread);
6194         }
6195       else if (b->task != 0)
6196         {
6197           uiout->text (" task ");
6198           uiout->field_int ("task", b->task);
6199         }
6200     }
6201
6202   uiout->text ("\n");
6203
6204   if (!part_of_multiple)
6205     b->ops->print_one_detail (b, uiout);
6206
6207   if (part_of_multiple && frame_id_p (b->frame_id))
6208     {
6209       annotate_field (6);
6210       uiout->text ("\tstop only in stack frame at ");
6211       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6212          the frame ID.  */
6213       uiout->field_core_addr ("frame",
6214                               b->gdbarch, b->frame_id.stack_addr);
6215       uiout->text ("\n");
6216     }
6217   
6218   if (!part_of_multiple && b->cond_string)
6219     {
6220       annotate_field (7);
6221       if (is_tracepoint (b))
6222         uiout->text ("\ttrace only if ");
6223       else
6224         uiout->text ("\tstop only if ");
6225       uiout->field_string ("cond", b->cond_string);
6226
6227       /* Print whether the target is doing the breakpoint's condition
6228          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6229       if (is_breakpoint (b)
6230           && breakpoint_condition_evaluation_mode ()
6231           == condition_evaluation_target)
6232         {
6233           uiout->text (" (");
6234           uiout->field_string ("evaluated-by",
6235                                bp_condition_evaluator (b));
6236           uiout->text (" evals)");
6237         }
6238       uiout->text ("\n");
6239     }
6240
6241   if (!part_of_multiple && b->thread != -1)
6242     {
6243       /* FIXME should make an annotation for this.  */
6244       uiout->text ("\tstop only in thread ");
6245       if (uiout->is_mi_like_p ())
6246         uiout->field_int ("thread", b->thread);
6247       else
6248         {
6249           struct thread_info *thr = find_thread_global_id (b->thread);
6250
6251           uiout->field_string ("thread", print_thread_id (thr));
6252         }
6253       uiout->text ("\n");
6254     }
6255   
6256   if (!part_of_multiple)
6257     {
6258       if (b->hit_count)
6259         {
6260           /* FIXME should make an annotation for this.  */
6261           if (is_catchpoint (b))
6262             uiout->text ("\tcatchpoint");
6263           else if (is_tracepoint (b))
6264             uiout->text ("\ttracepoint");
6265           else
6266             uiout->text ("\tbreakpoint");
6267           uiout->text (" already hit ");
6268           uiout->field_int ("times", b->hit_count);
6269           if (b->hit_count == 1)
6270             uiout->text (" time\n");
6271           else
6272             uiout->text (" times\n");
6273         }
6274       else
6275         {
6276           /* Output the count also if it is zero, but only if this is mi.  */
6277           if (uiout->is_mi_like_p ())
6278             uiout->field_int ("times", b->hit_count);
6279         }
6280     }
6281
6282   if (!part_of_multiple && b->ignore_count)
6283     {
6284       annotate_field (8);
6285       uiout->text ("\tignore next ");
6286       uiout->field_int ("ignore", b->ignore_count);
6287       uiout->text (" hits\n");
6288     }
6289
6290   /* Note that an enable count of 1 corresponds to "enable once"
6291      behavior, which is reported by the combination of enablement and
6292      disposition, so we don't need to mention it here.  */
6293   if (!part_of_multiple && b->enable_count > 1)
6294     {
6295       annotate_field (8);
6296       uiout->text ("\tdisable after ");
6297       /* Tweak the wording to clarify that ignore and enable counts
6298          are distinct, and have additive effect.  */
6299       if (b->ignore_count)
6300         uiout->text ("additional ");
6301       else
6302         uiout->text ("next ");
6303       uiout->field_int ("enable", b->enable_count);
6304       uiout->text (" hits\n");
6305     }
6306
6307   if (!part_of_multiple && is_tracepoint (b))
6308     {
6309       struct tracepoint *tp = (struct tracepoint *) b;
6310
6311       if (tp->traceframe_usage)
6312         {
6313           uiout->text ("\ttrace buffer usage ");
6314           uiout->field_int ("traceframe-usage", tp->traceframe_usage);
6315           uiout->text (" bytes\n");
6316         }
6317     }
6318
6319   l = b->commands ? b->commands.get () : NULL;
6320   if (!part_of_multiple && l)
6321     {
6322       annotate_field (9);
6323       ui_out_emit_tuple tuple_emitter (uiout, "script");
6324       print_command_lines (uiout, l, 4);
6325     }
6326
6327   if (is_tracepoint (b))
6328     {
6329       struct tracepoint *t = (struct tracepoint *) b;
6330
6331       if (!part_of_multiple && t->pass_count)
6332         {
6333           annotate_field (10);
6334           uiout->text ("\tpass count ");
6335           uiout->field_int ("pass", t->pass_count);
6336           uiout->text (" \n");
6337         }
6338
6339       /* Don't display it when tracepoint or tracepoint location is
6340          pending.   */
6341       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6342         {
6343           annotate_field (11);
6344
6345           if (uiout->is_mi_like_p ())
6346             uiout->field_string ("installed",
6347                                  loc->inserted ? "y" : "n");
6348           else
6349             {
6350               if (loc->inserted)
6351                 uiout->text ("\t");
6352               else
6353                 uiout->text ("\tnot ");
6354               uiout->text ("installed on target\n");
6355             }
6356         }
6357     }
6358
6359   if (uiout->is_mi_like_p () && !part_of_multiple)
6360     {
6361       if (is_watchpoint (b))
6362         {
6363           struct watchpoint *w = (struct watchpoint *) b;
6364
6365           uiout->field_string ("original-location", w->exp_string);
6366         }
6367       else if (b->location != NULL
6368                && event_location_to_string (b->location.get ()) != NULL)
6369         uiout->field_string ("original-location",
6370                              event_location_to_string (b->location.get ()));
6371     }
6372 }
6373
6374 static void
6375 print_one_breakpoint (struct breakpoint *b,
6376                       struct bp_location **last_loc, 
6377                       int allflag)
6378 {
6379   struct ui_out *uiout = current_uiout;
6380
6381   {
6382     ui_out_emit_tuple tuple_emitter (uiout, "bkpt");
6383
6384     print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6385   }
6386
6387   /* If this breakpoint has custom print function,
6388      it's already printed.  Otherwise, print individual
6389      locations, if any.  */
6390   if (b->ops == NULL || b->ops->print_one == NULL)
6391     {
6392       /* If breakpoint has a single location that is disabled, we
6393          print it as if it had several locations, since otherwise it's
6394          hard to represent "breakpoint enabled, location disabled"
6395          situation.
6396
6397          Note that while hardware watchpoints have several locations
6398          internally, that's not a property exposed to user.  */
6399       if (b->loc 
6400           && !is_hardware_watchpoint (b)
6401           && (b->loc->next || !b->loc->enabled))
6402         {
6403           struct bp_location *loc;
6404           int n = 1;
6405
6406           for (loc = b->loc; loc; loc = loc->next, ++n)
6407             {
6408               ui_out_emit_tuple tuple_emitter (uiout, NULL);
6409               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6410             }
6411         }
6412     }
6413 }
6414
6415 static int
6416 breakpoint_address_bits (struct breakpoint *b)
6417 {
6418   int print_address_bits = 0;
6419   struct bp_location *loc;
6420
6421   /* Software watchpoints that aren't watching memory don't have an
6422      address to print.  */
6423   if (is_no_memory_software_watchpoint (b))
6424     return 0;
6425
6426   for (loc = b->loc; loc; loc = loc->next)
6427     {
6428       int addr_bit;
6429
6430       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6431       if (addr_bit > print_address_bits)
6432         print_address_bits = addr_bit;
6433     }
6434
6435   return print_address_bits;
6436 }
6437
6438 /* See breakpoint.h.  */
6439
6440 void
6441 print_breakpoint (breakpoint *b)
6442 {
6443   struct bp_location *dummy_loc = NULL;
6444   print_one_breakpoint (b, &dummy_loc, 0);
6445 }
6446
6447 /* Return true if this breakpoint was set by the user, false if it is
6448    internal or momentary.  */
6449
6450 int
6451 user_breakpoint_p (struct breakpoint *b)
6452 {
6453   return b->number > 0;
6454 }
6455
6456 /* See breakpoint.h.  */
6457
6458 int
6459 pending_breakpoint_p (struct breakpoint *b)
6460 {
6461   return b->loc == NULL;
6462 }
6463
6464 /* Print information on user settable breakpoint (watchpoint, etc)
6465    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6466    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6467    FILTER is non-NULL, call it on each breakpoint and only include the
6468    ones for which it returns non-zero.  Return the total number of
6469    breakpoints listed.  */
6470
6471 static int
6472 breakpoint_1 (const char *args, int allflag, 
6473               int (*filter) (const struct breakpoint *))
6474 {
6475   struct breakpoint *b;
6476   struct bp_location *last_loc = NULL;
6477   int nr_printable_breakpoints;
6478   struct value_print_options opts;
6479   int print_address_bits = 0;
6480   int print_type_col_width = 14;
6481   struct ui_out *uiout = current_uiout;
6482
6483   get_user_print_options (&opts);
6484
6485   /* Compute the number of rows in the table, as well as the size
6486      required for address fields.  */
6487   nr_printable_breakpoints = 0;
6488   ALL_BREAKPOINTS (b)
6489     {
6490       /* If we have a filter, only list the breakpoints it accepts.  */
6491       if (filter && !filter (b))
6492         continue;
6493
6494       /* If we have an "args" string, it is a list of breakpoints to 
6495          accept.  Skip the others.  */
6496       if (args != NULL && *args != '\0')
6497         {
6498           if (allflag && parse_and_eval_long (args) != b->number)
6499             continue;
6500           if (!allflag && !number_is_in_list (args, b->number))
6501             continue;
6502         }
6503
6504       if (allflag || user_breakpoint_p (b))
6505         {
6506           int addr_bit, type_len;
6507
6508           addr_bit = breakpoint_address_bits (b);
6509           if (addr_bit > print_address_bits)
6510             print_address_bits = addr_bit;
6511
6512           type_len = strlen (bptype_string (b->type));
6513           if (type_len > print_type_col_width)
6514             print_type_col_width = type_len;
6515
6516           nr_printable_breakpoints++;
6517         }
6518     }
6519
6520   {
6521     ui_out_emit_table table_emitter (uiout,
6522                                      opts.addressprint ? 6 : 5,
6523                                      nr_printable_breakpoints,
6524                                      "BreakpointTable");
6525
6526     if (nr_printable_breakpoints > 0)
6527       annotate_breakpoints_headers ();
6528     if (nr_printable_breakpoints > 0)
6529       annotate_field (0);
6530     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6531     if (nr_printable_breakpoints > 0)
6532       annotate_field (1);
6533     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6534     if (nr_printable_breakpoints > 0)
6535       annotate_field (2);
6536     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6537     if (nr_printable_breakpoints > 0)
6538       annotate_field (3);
6539     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6540     if (opts.addressprint)
6541       {
6542         if (nr_printable_breakpoints > 0)
6543           annotate_field (4);
6544         if (print_address_bits <= 32)
6545           uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6546         else
6547           uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6548       }
6549     if (nr_printable_breakpoints > 0)
6550       annotate_field (5);
6551     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6552     uiout->table_body ();
6553     if (nr_printable_breakpoints > 0)
6554       annotate_breakpoints_table ();
6555
6556     ALL_BREAKPOINTS (b)
6557       {
6558         QUIT;
6559         /* If we have a filter, only list the breakpoints it accepts.  */
6560         if (filter && !filter (b))
6561           continue;
6562
6563         /* If we have an "args" string, it is a list of breakpoints to 
6564            accept.  Skip the others.  */
6565
6566         if (args != NULL && *args != '\0')
6567           {
6568             if (allflag)        /* maintenance info breakpoint */
6569               {
6570                 if (parse_and_eval_long (args) != b->number)
6571                   continue;
6572               }
6573             else                /* all others */
6574               {
6575                 if (!number_is_in_list (args, b->number))
6576                   continue;
6577               }
6578           }
6579         /* We only print out user settable breakpoints unless the
6580            allflag is set.  */
6581         if (allflag || user_breakpoint_p (b))
6582           print_one_breakpoint (b, &last_loc, allflag);
6583       }
6584   }
6585
6586   if (nr_printable_breakpoints == 0)
6587     {
6588       /* If there's a filter, let the caller decide how to report
6589          empty list.  */
6590       if (!filter)
6591         {
6592           if (args == NULL || *args == '\0')
6593             uiout->message ("No breakpoints or watchpoints.\n");
6594           else
6595             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6596                             args);
6597         }
6598     }
6599   else
6600     {
6601       if (last_loc && !server_command)
6602         set_next_address (last_loc->gdbarch, last_loc->address);
6603     }
6604
6605   /* FIXME?  Should this be moved up so that it is only called when
6606      there have been breakpoints? */
6607   annotate_breakpoints_table_end ();
6608
6609   return nr_printable_breakpoints;
6610 }
6611
6612 /* Display the value of default-collect in a way that is generally
6613    compatible with the breakpoint list.  */
6614
6615 static void
6616 default_collect_info (void)
6617 {
6618   struct ui_out *uiout = current_uiout;
6619
6620   /* If it has no value (which is frequently the case), say nothing; a
6621      message like "No default-collect." gets in user's face when it's
6622      not wanted.  */
6623   if (!*default_collect)
6624     return;
6625
6626   /* The following phrase lines up nicely with per-tracepoint collect
6627      actions.  */
6628   uiout->text ("default collect ");
6629   uiout->field_string ("default-collect", default_collect);
6630   uiout->text (" \n");
6631 }
6632   
6633 static void
6634 info_breakpoints_command (const char *args, int from_tty)
6635 {
6636   breakpoint_1 (args, 0, NULL);
6637
6638   default_collect_info ();
6639 }
6640
6641 static void
6642 info_watchpoints_command (const char *args, int from_tty)
6643 {
6644   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6645   struct ui_out *uiout = current_uiout;
6646
6647   if (num_printed == 0)
6648     {
6649       if (args == NULL || *args == '\0')
6650         uiout->message ("No watchpoints.\n");
6651       else
6652         uiout->message ("No watchpoint matching '%s'.\n", args);
6653     }
6654 }
6655
6656 static void
6657 maintenance_info_breakpoints (const char *args, int from_tty)
6658 {
6659   breakpoint_1 (args, 1, NULL);
6660
6661   default_collect_info ();
6662 }
6663
6664 static int
6665 breakpoint_has_pc (struct breakpoint *b,
6666                    struct program_space *pspace,
6667                    CORE_ADDR pc, struct obj_section *section)
6668 {
6669   struct bp_location *bl = b->loc;
6670
6671   for (; bl; bl = bl->next)
6672     {
6673       if (bl->pspace == pspace
6674           && bl->address == pc
6675           && (!overlay_debugging || bl->section == section))
6676         return 1;         
6677     }
6678   return 0;
6679 }
6680
6681 /* Print a message describing any user-breakpoints set at PC.  This
6682    concerns with logical breakpoints, so we match program spaces, not
6683    address spaces.  */
6684
6685 static void
6686 describe_other_breakpoints (struct gdbarch *gdbarch,
6687                             struct program_space *pspace, CORE_ADDR pc,
6688                             struct obj_section *section, int thread)
6689 {
6690   int others = 0;
6691   struct breakpoint *b;
6692
6693   ALL_BREAKPOINTS (b)
6694     others += (user_breakpoint_p (b)
6695                && breakpoint_has_pc (b, pspace, pc, section));
6696   if (others > 0)
6697     {
6698       if (others == 1)
6699         printf_filtered (_("Note: breakpoint "));
6700       else /* if (others == ???) */
6701         printf_filtered (_("Note: breakpoints "));
6702       ALL_BREAKPOINTS (b)
6703         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6704           {
6705             others--;
6706             printf_filtered ("%d", b->number);
6707             if (b->thread == -1 && thread != -1)
6708               printf_filtered (" (all threads)");
6709             else if (b->thread != -1)
6710               printf_filtered (" (thread %d)", b->thread);
6711             printf_filtered ("%s%s ",
6712                              ((b->enable_state == bp_disabled
6713                                || b->enable_state == bp_call_disabled)
6714                               ? " (disabled)"
6715                               : ""),
6716                              (others > 1) ? "," 
6717                              : ((others == 1) ? " and" : ""));
6718           }
6719       printf_filtered (_("also set at pc "));
6720       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6721       printf_filtered (".\n");
6722     }
6723 }
6724 \f
6725
6726 /* Return true iff it is meaningful to use the address member of
6727    BPT locations.  For some breakpoint types, the locations' address members
6728    are irrelevant and it makes no sense to attempt to compare them to other
6729    addresses (or use them for any other purpose either).
6730
6731    More specifically, each of the following breakpoint types will
6732    always have a zero valued location address and we don't want to mark
6733    breakpoints of any of these types to be a duplicate of an actual
6734    breakpoint location at address zero:
6735
6736       bp_watchpoint
6737       bp_catchpoint
6738
6739 */
6740
6741 static int
6742 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6743 {
6744   enum bptype type = bpt->type;
6745
6746   return (type != bp_watchpoint && type != bp_catchpoint);
6747 }
6748
6749 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6750    true if LOC1 and LOC2 represent the same watchpoint location.  */
6751
6752 static int
6753 watchpoint_locations_match (struct bp_location *loc1, 
6754                             struct bp_location *loc2)
6755 {
6756   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6757   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6758
6759   /* Both of them must exist.  */
6760   gdb_assert (w1 != NULL);
6761   gdb_assert (w2 != NULL);
6762
6763   /* If the target can evaluate the condition expression in hardware,
6764      then we we need to insert both watchpoints even if they are at
6765      the same place.  Otherwise the watchpoint will only trigger when
6766      the condition of whichever watchpoint was inserted evaluates to
6767      true, not giving a chance for GDB to check the condition of the
6768      other watchpoint.  */
6769   if ((w1->cond_exp
6770        && target_can_accel_watchpoint_condition (loc1->address, 
6771                                                  loc1->length,
6772                                                  loc1->watchpoint_type,
6773                                                  w1->cond_exp.get ()))
6774       || (w2->cond_exp
6775           && target_can_accel_watchpoint_condition (loc2->address, 
6776                                                     loc2->length,
6777                                                     loc2->watchpoint_type,
6778                                                     w2->cond_exp.get ())))
6779     return 0;
6780
6781   /* Note that this checks the owner's type, not the location's.  In
6782      case the target does not support read watchpoints, but does
6783      support access watchpoints, we'll have bp_read_watchpoint
6784      watchpoints with hw_access locations.  Those should be considered
6785      duplicates of hw_read locations.  The hw_read locations will
6786      become hw_access locations later.  */
6787   return (loc1->owner->type == loc2->owner->type
6788           && loc1->pspace->aspace == loc2->pspace->aspace
6789           && loc1->address == loc2->address
6790           && loc1->length == loc2->length);
6791 }
6792
6793 /* See breakpoint.h.  */
6794
6795 int
6796 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
6797                           const address_space *aspace2, CORE_ADDR addr2)
6798 {
6799   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6800            || aspace1 == aspace2)
6801           && addr1 == addr2);
6802 }
6803
6804 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6805    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6806    matches ASPACE2.  On targets that have global breakpoints, the address
6807    space doesn't really matter.  */
6808
6809 static int
6810 breakpoint_address_match_range (const address_space *aspace1,
6811                                 CORE_ADDR addr1,
6812                                 int len1, const address_space *aspace2,
6813                                 CORE_ADDR addr2)
6814 {
6815   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6816            || aspace1 == aspace2)
6817           && addr2 >= addr1 && addr2 < addr1 + len1);
6818 }
6819
6820 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6821    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6822    matches the breakpoint's address space.  On targets that have global
6823    breakpoints, the address space doesn't really matter.  */
6824
6825 static int
6826 breakpoint_location_address_match (struct bp_location *bl,
6827                                    const address_space *aspace,
6828                                    CORE_ADDR addr)
6829 {
6830   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6831                                     aspace, addr)
6832           || (bl->length
6833               && breakpoint_address_match_range (bl->pspace->aspace,
6834                                                  bl->address, bl->length,
6835                                                  aspace, addr)));
6836 }
6837
6838 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
6839    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
6840    match happens only if ASPACE matches the breakpoint's address
6841    space.  On targets that have global breakpoints, the address space
6842    doesn't really matter.  */
6843
6844 static int
6845 breakpoint_location_address_range_overlap (struct bp_location *bl,
6846                                            const address_space *aspace,
6847                                            CORE_ADDR addr, int len)
6848 {
6849   if (gdbarch_has_global_breakpoints (target_gdbarch ())
6850       || bl->pspace->aspace == aspace)
6851     {
6852       int bl_len = bl->length != 0 ? bl->length : 1;
6853
6854       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
6855         return 1;
6856     }
6857   return 0;
6858 }
6859
6860 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6861    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6862    true, otherwise returns false.  */
6863
6864 static int
6865 tracepoint_locations_match (struct bp_location *loc1,
6866                             struct bp_location *loc2)
6867 {
6868   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6869     /* Since tracepoint locations are never duplicated with others', tracepoint
6870        locations at the same address of different tracepoints are regarded as
6871        different locations.  */
6872     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6873   else
6874     return 0;
6875 }
6876
6877 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6878    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6879    represent the same location.  */
6880
6881 static int
6882 breakpoint_locations_match (struct bp_location *loc1, 
6883                             struct bp_location *loc2)
6884 {
6885   int hw_point1, hw_point2;
6886
6887   /* Both of them must not be in moribund_locations.  */
6888   gdb_assert (loc1->owner != NULL);
6889   gdb_assert (loc2->owner != NULL);
6890
6891   hw_point1 = is_hardware_watchpoint (loc1->owner);
6892   hw_point2 = is_hardware_watchpoint (loc2->owner);
6893
6894   if (hw_point1 != hw_point2)
6895     return 0;
6896   else if (hw_point1)
6897     return watchpoint_locations_match (loc1, loc2);
6898   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6899     return tracepoint_locations_match (loc1, loc2);
6900   else
6901     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6902     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6903                                      loc2->pspace->aspace, loc2->address)
6904             && loc1->length == loc2->length);
6905 }
6906
6907 static void
6908 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6909                                int bnum, int have_bnum)
6910 {
6911   /* The longest string possibly returned by hex_string_custom
6912      is 50 chars.  These must be at least that big for safety.  */
6913   char astr1[64];
6914   char astr2[64];
6915
6916   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6917   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6918   if (have_bnum)
6919     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6920              bnum, astr1, astr2);
6921   else
6922     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6923 }
6924
6925 /* Adjust a breakpoint's address to account for architectural
6926    constraints on breakpoint placement.  Return the adjusted address.
6927    Note: Very few targets require this kind of adjustment.  For most
6928    targets, this function is simply the identity function.  */
6929
6930 static CORE_ADDR
6931 adjust_breakpoint_address (struct gdbarch *gdbarch,
6932                            CORE_ADDR bpaddr, enum bptype bptype)
6933 {
6934   if (bptype == bp_watchpoint
6935       || bptype == bp_hardware_watchpoint
6936       || bptype == bp_read_watchpoint
6937       || bptype == bp_access_watchpoint
6938       || bptype == bp_catchpoint)
6939     {
6940       /* Watchpoints and the various bp_catch_* eventpoints should not
6941          have their addresses modified.  */
6942       return bpaddr;
6943     }
6944   else if (bptype == bp_single_step)
6945     {
6946       /* Single-step breakpoints should not have their addresses
6947          modified.  If there's any architectural constrain that
6948          applies to this address, then it should have already been
6949          taken into account when the breakpoint was created in the
6950          first place.  If we didn't do this, stepping through e.g.,
6951          Thumb-2 IT blocks would break.  */
6952       return bpaddr;
6953     }
6954   else
6955     {
6956       CORE_ADDR adjusted_bpaddr = bpaddr;
6957
6958       if (gdbarch_adjust_breakpoint_address_p (gdbarch))
6959         {
6960           /* Some targets have architectural constraints on the placement
6961              of breakpoint instructions.  Obtain the adjusted address.  */
6962           adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6963         }
6964
6965       adjusted_bpaddr = address_significant (gdbarch, adjusted_bpaddr);
6966
6967       /* An adjusted breakpoint address can significantly alter
6968          a user's expectations.  Print a warning if an adjustment
6969          is required.  */
6970       if (adjusted_bpaddr != bpaddr)
6971         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6972
6973       return adjusted_bpaddr;
6974     }
6975 }
6976
6977 bp_location::bp_location (const bp_location_ops *ops, breakpoint *owner)
6978 {
6979   bp_location *loc = this;
6980
6981   gdb_assert (ops != NULL);
6982
6983   loc->ops = ops;
6984   loc->owner = owner;
6985   loc->cond_bytecode = NULL;
6986   loc->shlib_disabled = 0;
6987   loc->enabled = 1;
6988
6989   switch (owner->type)
6990     {
6991     case bp_breakpoint:
6992     case bp_single_step:
6993     case bp_until:
6994     case bp_finish:
6995     case bp_longjmp:
6996     case bp_longjmp_resume:
6997     case bp_longjmp_call_dummy:
6998     case bp_exception:
6999     case bp_exception_resume:
7000     case bp_step_resume:
7001     case bp_hp_step_resume:
7002     case bp_watchpoint_scope:
7003     case bp_call_dummy:
7004     case bp_std_terminate:
7005     case bp_shlib_event:
7006     case bp_thread_event:
7007     case bp_overlay_event:
7008     case bp_jit_event:
7009     case bp_longjmp_master:
7010     case bp_std_terminate_master:
7011     case bp_exception_master:
7012     case bp_gnu_ifunc_resolver:
7013     case bp_gnu_ifunc_resolver_return:
7014     case bp_dprintf:
7015       loc->loc_type = bp_loc_software_breakpoint;
7016       mark_breakpoint_location_modified (loc);
7017       break;
7018     case bp_hardware_breakpoint:
7019       loc->loc_type = bp_loc_hardware_breakpoint;
7020       mark_breakpoint_location_modified (loc);
7021       break;
7022     case bp_hardware_watchpoint:
7023     case bp_read_watchpoint:
7024     case bp_access_watchpoint:
7025       loc->loc_type = bp_loc_hardware_watchpoint;
7026       break;
7027     case bp_watchpoint:
7028     case bp_catchpoint:
7029     case bp_tracepoint:
7030     case bp_fast_tracepoint:
7031     case bp_static_tracepoint:
7032       loc->loc_type = bp_loc_other;
7033       break;
7034     default:
7035       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7036     }
7037
7038   loc->refc = 1;
7039 }
7040
7041 /* Allocate a struct bp_location.  */
7042
7043 static struct bp_location *
7044 allocate_bp_location (struct breakpoint *bpt)
7045 {
7046   return bpt->ops->allocate_location (bpt);
7047 }
7048
7049 static void
7050 free_bp_location (struct bp_location *loc)
7051 {
7052   loc->ops->dtor (loc);
7053   delete loc;
7054 }
7055
7056 /* Increment reference count.  */
7057
7058 static void
7059 incref_bp_location (struct bp_location *bl)
7060 {
7061   ++bl->refc;
7062 }
7063
7064 /* Decrement reference count.  If the reference count reaches 0,
7065    destroy the bp_location.  Sets *BLP to NULL.  */
7066
7067 static void
7068 decref_bp_location (struct bp_location **blp)
7069 {
7070   gdb_assert ((*blp)->refc > 0);
7071
7072   if (--(*blp)->refc == 0)
7073     free_bp_location (*blp);
7074   *blp = NULL;
7075 }
7076
7077 /* Add breakpoint B at the end of the global breakpoint chain.  */
7078
7079 static breakpoint *
7080 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7081 {
7082   struct breakpoint *b1;
7083   struct breakpoint *result = b.get ();
7084
7085   /* Add this breakpoint to the end of the chain so that a list of
7086      breakpoints will come out in order of increasing numbers.  */
7087
7088   b1 = breakpoint_chain;
7089   if (b1 == 0)
7090     breakpoint_chain = b.release ();
7091   else
7092     {
7093       while (b1->next)
7094         b1 = b1->next;
7095       b1->next = b.release ();
7096     }
7097
7098   return result;
7099 }
7100
7101 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7102
7103 static void
7104 init_raw_breakpoint_without_location (struct breakpoint *b,
7105                                       struct gdbarch *gdbarch,
7106                                       enum bptype bptype,
7107                                       const struct breakpoint_ops *ops)
7108 {
7109   gdb_assert (ops != NULL);
7110
7111   b->ops = ops;
7112   b->type = bptype;
7113   b->gdbarch = gdbarch;
7114   b->language = current_language->la_language;
7115   b->input_radix = input_radix;
7116   b->related_breakpoint = b;
7117 }
7118
7119 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7120    that has type BPTYPE and has no locations as yet.  */
7121
7122 static struct breakpoint *
7123 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7124                                      enum bptype bptype,
7125                                      const struct breakpoint_ops *ops)
7126 {
7127   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7128
7129   init_raw_breakpoint_without_location (b.get (), gdbarch, bptype, ops);
7130   return add_to_breakpoint_chain (std::move (b));
7131 }
7132
7133 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7134    resolutions should be made as the user specified the location explicitly
7135    enough.  */
7136
7137 static void
7138 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7139 {
7140   gdb_assert (loc->owner != NULL);
7141
7142   if (loc->owner->type == bp_breakpoint
7143       || loc->owner->type == bp_hardware_breakpoint
7144       || is_tracepoint (loc->owner))
7145     {
7146       const char *function_name;
7147
7148       if (loc->msymbol != NULL
7149           && (MSYMBOL_TYPE (loc->msymbol) == mst_text_gnu_ifunc
7150               || MSYMBOL_TYPE (loc->msymbol) == mst_data_gnu_ifunc)
7151           && !explicit_loc)
7152         {
7153           struct breakpoint *b = loc->owner;
7154
7155           function_name = MSYMBOL_LINKAGE_NAME (loc->msymbol);
7156
7157           if (b->type == bp_breakpoint && b->loc == loc
7158               && loc->next == NULL && b->related_breakpoint == b)
7159             {
7160               /* Create only the whole new breakpoint of this type but do not
7161                  mess more complicated breakpoints with multiple locations.  */
7162               b->type = bp_gnu_ifunc_resolver;
7163               /* Remember the resolver's address for use by the return
7164                  breakpoint.  */
7165               loc->related_address = loc->address;
7166             }
7167         }
7168       else
7169         find_pc_partial_function (loc->address, &function_name, NULL, NULL);
7170
7171       if (function_name)
7172         loc->function_name = xstrdup (function_name);
7173     }
7174 }
7175
7176 /* Attempt to determine architecture of location identified by SAL.  */
7177 struct gdbarch *
7178 get_sal_arch (struct symtab_and_line sal)
7179 {
7180   if (sal.section)
7181     return get_objfile_arch (sal.section->objfile);
7182   if (sal.symtab)
7183     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7184
7185   return NULL;
7186 }
7187
7188 /* Low level routine for partially initializing a breakpoint of type
7189    BPTYPE.  The newly created breakpoint's address, section, source
7190    file name, and line number are provided by SAL.
7191
7192    It is expected that the caller will complete the initialization of
7193    the newly created breakpoint struct as well as output any status
7194    information regarding the creation of a new breakpoint.  */
7195
7196 static void
7197 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7198                      struct symtab_and_line sal, enum bptype bptype,
7199                      const struct breakpoint_ops *ops)
7200 {
7201   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7202
7203   add_location_to_breakpoint (b, &sal);
7204
7205   if (bptype != bp_catchpoint)
7206     gdb_assert (sal.pspace != NULL);
7207
7208   /* Store the program space that was used to set the breakpoint,
7209      except for ordinary breakpoints, which are independent of the
7210      program space.  */
7211   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7212     b->pspace = sal.pspace;
7213 }
7214
7215 /* set_raw_breakpoint is a low level routine for allocating and
7216    partially initializing a breakpoint of type BPTYPE.  The newly
7217    created breakpoint's address, section, source file name, and line
7218    number are provided by SAL.  The newly created and partially
7219    initialized breakpoint is added to the breakpoint chain and
7220    is also returned as the value of this function.
7221
7222    It is expected that the caller will complete the initialization of
7223    the newly created breakpoint struct as well as output any status
7224    information regarding the creation of a new breakpoint.  In
7225    particular, set_raw_breakpoint does NOT set the breakpoint
7226    number!  Care should be taken to not allow an error to occur
7227    prior to completing the initialization of the breakpoint.  If this
7228    should happen, a bogus breakpoint will be left on the chain.  */
7229
7230 struct breakpoint *
7231 set_raw_breakpoint (struct gdbarch *gdbarch,
7232                     struct symtab_and_line sal, enum bptype bptype,
7233                     const struct breakpoint_ops *ops)
7234 {
7235   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7236
7237   init_raw_breakpoint (b.get (), gdbarch, sal, bptype, ops);
7238   return add_to_breakpoint_chain (std::move (b));
7239 }
7240
7241 /* Call this routine when stepping and nexting to enable a breakpoint
7242    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7243    initiated the operation.  */
7244
7245 void
7246 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7247 {
7248   struct breakpoint *b, *b_tmp;
7249   int thread = tp->global_num;
7250
7251   /* To avoid having to rescan all objfile symbols at every step,
7252      we maintain a list of continually-inserted but always disabled
7253      longjmp "master" breakpoints.  Here, we simply create momentary
7254      clones of those and enable them for the requested thread.  */
7255   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7256     if (b->pspace == current_program_space
7257         && (b->type == bp_longjmp_master
7258             || b->type == bp_exception_master))
7259       {
7260         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7261         struct breakpoint *clone;
7262
7263         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7264            after their removal.  */
7265         clone = momentary_breakpoint_from_master (b, type,
7266                                                   &momentary_breakpoint_ops, 1);
7267         clone->thread = thread;
7268       }
7269
7270   tp->initiating_frame = frame;
7271 }
7272
7273 /* Delete all longjmp breakpoints from THREAD.  */
7274 void
7275 delete_longjmp_breakpoint (int thread)
7276 {
7277   struct breakpoint *b, *b_tmp;
7278
7279   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7280     if (b->type == bp_longjmp || b->type == bp_exception)
7281       {
7282         if (b->thread == thread)
7283           delete_breakpoint (b);
7284       }
7285 }
7286
7287 void
7288 delete_longjmp_breakpoint_at_next_stop (int thread)
7289 {
7290   struct breakpoint *b, *b_tmp;
7291
7292   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7293     if (b->type == bp_longjmp || b->type == bp_exception)
7294       {
7295         if (b->thread == thread)
7296           b->disposition = disp_del_at_next_stop;
7297       }
7298 }
7299
7300 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7301    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7302    pointer to any of them.  Return NULL if this system cannot place longjmp
7303    breakpoints.  */
7304
7305 struct breakpoint *
7306 set_longjmp_breakpoint_for_call_dummy (void)
7307 {
7308   struct breakpoint *b, *retval = NULL;
7309
7310   ALL_BREAKPOINTS (b)
7311     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7312       {
7313         struct breakpoint *new_b;
7314
7315         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7316                                                   &momentary_breakpoint_ops,
7317                                                   1);
7318         new_b->thread = ptid_to_global_thread_id (inferior_ptid);
7319
7320         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7321
7322         gdb_assert (new_b->related_breakpoint == new_b);
7323         if (retval == NULL)
7324           retval = new_b;
7325         new_b->related_breakpoint = retval;
7326         while (retval->related_breakpoint != new_b->related_breakpoint)
7327           retval = retval->related_breakpoint;
7328         retval->related_breakpoint = new_b;
7329       }
7330
7331   return retval;
7332 }
7333
7334 /* Verify all existing dummy frames and their associated breakpoints for
7335    TP.  Remove those which can no longer be found in the current frame
7336    stack.
7337
7338    You should call this function only at places where it is safe to currently
7339    unwind the whole stack.  Failed stack unwind would discard live dummy
7340    frames.  */
7341
7342 void
7343 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7344 {
7345   struct breakpoint *b, *b_tmp;
7346
7347   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7348     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7349       {
7350         struct breakpoint *dummy_b = b->related_breakpoint;
7351
7352         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7353           dummy_b = dummy_b->related_breakpoint;
7354         if (dummy_b->type != bp_call_dummy
7355             || frame_find_by_id (dummy_b->frame_id) != NULL)
7356           continue;
7357         
7358         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7359
7360         while (b->related_breakpoint != b)
7361           {
7362             if (b_tmp == b->related_breakpoint)
7363               b_tmp = b->related_breakpoint->next;
7364             delete_breakpoint (b->related_breakpoint);
7365           }
7366         delete_breakpoint (b);
7367       }
7368 }
7369
7370 void
7371 enable_overlay_breakpoints (void)
7372 {
7373   struct breakpoint *b;
7374
7375   ALL_BREAKPOINTS (b)
7376     if (b->type == bp_overlay_event)
7377     {
7378       b->enable_state = bp_enabled;
7379       update_global_location_list (UGLL_MAY_INSERT);
7380       overlay_events_enabled = 1;
7381     }
7382 }
7383
7384 void
7385 disable_overlay_breakpoints (void)
7386 {
7387   struct breakpoint *b;
7388
7389   ALL_BREAKPOINTS (b)
7390     if (b->type == bp_overlay_event)
7391     {
7392       b->enable_state = bp_disabled;
7393       update_global_location_list (UGLL_DONT_INSERT);
7394       overlay_events_enabled = 0;
7395     }
7396 }
7397
7398 /* Set an active std::terminate breakpoint for each std::terminate
7399    master breakpoint.  */
7400 void
7401 set_std_terminate_breakpoint (void)
7402 {
7403   struct breakpoint *b, *b_tmp;
7404
7405   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7406     if (b->pspace == current_program_space
7407         && b->type == bp_std_terminate_master)
7408       {
7409         momentary_breakpoint_from_master (b, bp_std_terminate,
7410                                           &momentary_breakpoint_ops, 1);
7411       }
7412 }
7413
7414 /* Delete all the std::terminate breakpoints.  */
7415 void
7416 delete_std_terminate_breakpoint (void)
7417 {
7418   struct breakpoint *b, *b_tmp;
7419
7420   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7421     if (b->type == bp_std_terminate)
7422       delete_breakpoint (b);
7423 }
7424
7425 struct breakpoint *
7426 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7427 {
7428   struct breakpoint *b;
7429
7430   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7431                                   &internal_breakpoint_ops);
7432
7433   b->enable_state = bp_enabled;
7434   /* location has to be used or breakpoint_re_set will delete me.  */
7435   b->location = new_address_location (b->loc->address, NULL, 0);
7436
7437   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7438
7439   return b;
7440 }
7441
7442 struct lang_and_radix
7443   {
7444     enum language lang;
7445     int radix;
7446   };
7447
7448 /* Create a breakpoint for JIT code registration and unregistration.  */
7449
7450 struct breakpoint *
7451 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7452 {
7453   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7454                                      &internal_breakpoint_ops);
7455 }
7456
7457 /* Remove JIT code registration and unregistration breakpoint(s).  */
7458
7459 void
7460 remove_jit_event_breakpoints (void)
7461 {
7462   struct breakpoint *b, *b_tmp;
7463
7464   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7465     if (b->type == bp_jit_event
7466         && b->loc->pspace == current_program_space)
7467       delete_breakpoint (b);
7468 }
7469
7470 void
7471 remove_solib_event_breakpoints (void)
7472 {
7473   struct breakpoint *b, *b_tmp;
7474
7475   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7476     if (b->type == bp_shlib_event
7477         && b->loc->pspace == current_program_space)
7478       delete_breakpoint (b);
7479 }
7480
7481 /* See breakpoint.h.  */
7482
7483 void
7484 remove_solib_event_breakpoints_at_next_stop (void)
7485 {
7486   struct breakpoint *b, *b_tmp;
7487
7488   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7489     if (b->type == bp_shlib_event
7490         && b->loc->pspace == current_program_space)
7491       b->disposition = disp_del_at_next_stop;
7492 }
7493
7494 /* Helper for create_solib_event_breakpoint /
7495    create_and_insert_solib_event_breakpoint.  Allows specifying which
7496    INSERT_MODE to pass through to update_global_location_list.  */
7497
7498 static struct breakpoint *
7499 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7500                                  enum ugll_insert_mode insert_mode)
7501 {
7502   struct breakpoint *b;
7503
7504   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7505                                   &internal_breakpoint_ops);
7506   update_global_location_list_nothrow (insert_mode);
7507   return b;
7508 }
7509
7510 struct breakpoint *
7511 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7512 {
7513   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7514 }
7515
7516 /* See breakpoint.h.  */
7517
7518 struct breakpoint *
7519 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7520 {
7521   struct breakpoint *b;
7522
7523   /* Explicitly tell update_global_location_list to insert
7524      locations.  */
7525   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7526   if (!b->loc->inserted)
7527     {
7528       delete_breakpoint (b);
7529       return NULL;
7530     }
7531   return b;
7532 }
7533
7534 /* Disable any breakpoints that are on code in shared libraries.  Only
7535    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7536
7537 void
7538 disable_breakpoints_in_shlibs (void)
7539 {
7540   struct bp_location *loc, **locp_tmp;
7541
7542   ALL_BP_LOCATIONS (loc, locp_tmp)
7543   {
7544     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7545     struct breakpoint *b = loc->owner;
7546
7547     /* We apply the check to all breakpoints, including disabled for
7548        those with loc->duplicate set.  This is so that when breakpoint
7549        becomes enabled, or the duplicate is removed, gdb will try to
7550        insert all breakpoints.  If we don't set shlib_disabled here,
7551        we'll try to insert those breakpoints and fail.  */
7552     if (((b->type == bp_breakpoint)
7553          || (b->type == bp_jit_event)
7554          || (b->type == bp_hardware_breakpoint)
7555          || (is_tracepoint (b)))
7556         && loc->pspace == current_program_space
7557         && !loc->shlib_disabled
7558         && solib_name_from_address (loc->pspace, loc->address)
7559         )
7560       {
7561         loc->shlib_disabled = 1;
7562       }
7563   }
7564 }
7565
7566 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7567    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7568    disabled ones can just stay disabled.  */
7569
7570 static void
7571 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7572 {
7573   struct bp_location *loc, **locp_tmp;
7574   int disabled_shlib_breaks = 0;
7575
7576   ALL_BP_LOCATIONS (loc, locp_tmp)
7577   {
7578     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7579     struct breakpoint *b = loc->owner;
7580
7581     if (solib->pspace == loc->pspace
7582         && !loc->shlib_disabled
7583         && (((b->type == bp_breakpoint
7584               || b->type == bp_jit_event
7585               || b->type == bp_hardware_breakpoint)
7586              && (loc->loc_type == bp_loc_hardware_breakpoint
7587                  || loc->loc_type == bp_loc_software_breakpoint))
7588             || is_tracepoint (b))
7589         && solib_contains_address_p (solib, loc->address))
7590       {
7591         loc->shlib_disabled = 1;
7592         /* At this point, we cannot rely on remove_breakpoint
7593            succeeding so we must mark the breakpoint as not inserted
7594            to prevent future errors occurring in remove_breakpoints.  */
7595         loc->inserted = 0;
7596
7597         /* This may cause duplicate notifications for the same breakpoint.  */
7598         gdb::observers::breakpoint_modified.notify (b);
7599
7600         if (!disabled_shlib_breaks)
7601           {
7602             target_terminal::ours_for_output ();
7603             warning (_("Temporarily disabling breakpoints "
7604                        "for unloaded shared library \"%s\""),
7605                      solib->so_name);
7606           }
7607         disabled_shlib_breaks = 1;
7608       }
7609   }
7610 }
7611
7612 /* Disable any breakpoints and tracepoints in OBJFILE upon
7613    notification of free_objfile.  Only apply to enabled breakpoints,
7614    disabled ones can just stay disabled.  */
7615
7616 static void
7617 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7618 {
7619   struct breakpoint *b;
7620
7621   if (objfile == NULL)
7622     return;
7623
7624   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7625      managed by the user with add-symbol-file/remove-symbol-file.
7626      Similarly to how breakpoints in shared libraries are handled in
7627      response to "nosharedlibrary", mark breakpoints in such modules
7628      shlib_disabled so they end up uninserted on the next global
7629      location list update.  Shared libraries not loaded by the user
7630      aren't handled here -- they're already handled in
7631      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7632      solib_unloaded observer.  We skip objfiles that are not
7633      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7634      main objfile).  */
7635   if ((objfile->flags & OBJF_SHARED) == 0
7636       || (objfile->flags & OBJF_USERLOADED) == 0)
7637     return;
7638
7639   ALL_BREAKPOINTS (b)
7640     {
7641       struct bp_location *loc;
7642       int bp_modified = 0;
7643
7644       if (!is_breakpoint (b) && !is_tracepoint (b))
7645         continue;
7646
7647       for (loc = b->loc; loc != NULL; loc = loc->next)
7648         {
7649           CORE_ADDR loc_addr = loc->address;
7650
7651           if (loc->loc_type != bp_loc_hardware_breakpoint
7652               && loc->loc_type != bp_loc_software_breakpoint)
7653             continue;
7654
7655           if (loc->shlib_disabled != 0)
7656             continue;
7657
7658           if (objfile->pspace != loc->pspace)
7659             continue;
7660
7661           if (loc->loc_type != bp_loc_hardware_breakpoint
7662               && loc->loc_type != bp_loc_software_breakpoint)
7663             continue;
7664
7665           if (is_addr_in_objfile (loc_addr, objfile))
7666             {
7667               loc->shlib_disabled = 1;
7668               /* At this point, we don't know whether the object was
7669                  unmapped from the inferior or not, so leave the
7670                  inserted flag alone.  We'll handle failure to
7671                  uninsert quietly, in case the object was indeed
7672                  unmapped.  */
7673
7674               mark_breakpoint_location_modified (loc);
7675
7676               bp_modified = 1;
7677             }
7678         }
7679
7680       if (bp_modified)
7681         gdb::observers::breakpoint_modified.notify (b);
7682     }
7683 }
7684
7685 /* FORK & VFORK catchpoints.  */
7686
7687 /* An instance of this type is used to represent a fork or vfork
7688    catchpoint.  A breakpoint is really of this type iff its ops pointer points
7689    to CATCH_FORK_BREAKPOINT_OPS.  */
7690
7691 struct fork_catchpoint : public breakpoint
7692 {
7693   /* Process id of a child process whose forking triggered this
7694      catchpoint.  This field is only valid immediately after this
7695      catchpoint has triggered.  */
7696   ptid_t forked_inferior_pid;
7697 };
7698
7699 /* Implement the "insert" breakpoint_ops method for fork
7700    catchpoints.  */
7701
7702 static int
7703 insert_catch_fork (struct bp_location *bl)
7704 {
7705   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7706 }
7707
7708 /* Implement the "remove" breakpoint_ops method for fork
7709    catchpoints.  */
7710
7711 static int
7712 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
7713 {
7714   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7715 }
7716
7717 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7718    catchpoints.  */
7719
7720 static int
7721 breakpoint_hit_catch_fork (const struct bp_location *bl,
7722                            const address_space *aspace, CORE_ADDR bp_addr,
7723                            const struct target_waitstatus *ws)
7724 {
7725   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7726
7727   if (ws->kind != TARGET_WAITKIND_FORKED)
7728     return 0;
7729
7730   c->forked_inferior_pid = ws->value.related_pid;
7731   return 1;
7732 }
7733
7734 /* Implement the "print_it" breakpoint_ops method for fork
7735    catchpoints.  */
7736
7737 static enum print_stop_action
7738 print_it_catch_fork (bpstat bs)
7739 {
7740   struct ui_out *uiout = current_uiout;
7741   struct breakpoint *b = bs->breakpoint_at;
7742   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7743
7744   annotate_catchpoint (b->number);
7745   maybe_print_thread_hit_breakpoint (uiout);
7746   if (b->disposition == disp_del)
7747     uiout->text ("Temporary catchpoint ");
7748   else
7749     uiout->text ("Catchpoint ");
7750   if (uiout->is_mi_like_p ())
7751     {
7752       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
7753       uiout->field_string ("disp", bpdisp_text (b->disposition));
7754     }
7755   uiout->field_int ("bkptno", b->number);
7756   uiout->text (" (forked process ");
7757   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
7758   uiout->text ("), ");
7759   return PRINT_SRC_AND_LOC;
7760 }
7761
7762 /* Implement the "print_one" breakpoint_ops method for fork
7763    catchpoints.  */
7764
7765 static void
7766 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7767 {
7768   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7769   struct value_print_options opts;
7770   struct ui_out *uiout = current_uiout;
7771
7772   get_user_print_options (&opts);
7773
7774   /* Field 4, the address, is omitted (which makes the columns not
7775      line up too nicely with the headers, but the effect is relatively
7776      readable).  */
7777   if (opts.addressprint)
7778     uiout->field_skip ("addr");
7779   annotate_field (5);
7780   uiout->text ("fork");
7781   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7782     {
7783       uiout->text (", process ");
7784       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
7785       uiout->spaces (1);
7786     }
7787
7788   if (uiout->is_mi_like_p ())
7789     uiout->field_string ("catch-type", "fork");
7790 }
7791
7792 /* Implement the "print_mention" breakpoint_ops method for fork
7793    catchpoints.  */
7794
7795 static void
7796 print_mention_catch_fork (struct breakpoint *b)
7797 {
7798   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7799 }
7800
7801 /* Implement the "print_recreate" breakpoint_ops method for fork
7802    catchpoints.  */
7803
7804 static void
7805 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7806 {
7807   fprintf_unfiltered (fp, "catch fork");
7808   print_recreate_thread (b, fp);
7809 }
7810
7811 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7812
7813 static struct breakpoint_ops catch_fork_breakpoint_ops;
7814
7815 /* Implement the "insert" breakpoint_ops method for vfork
7816    catchpoints.  */
7817
7818 static int
7819 insert_catch_vfork (struct bp_location *bl)
7820 {
7821   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7822 }
7823
7824 /* Implement the "remove" breakpoint_ops method for vfork
7825    catchpoints.  */
7826
7827 static int
7828 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
7829 {
7830   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7831 }
7832
7833 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7834    catchpoints.  */
7835
7836 static int
7837 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7838                             const address_space *aspace, CORE_ADDR bp_addr,
7839                             const struct target_waitstatus *ws)
7840 {
7841   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7842
7843   if (ws->kind != TARGET_WAITKIND_VFORKED)
7844     return 0;
7845
7846   c->forked_inferior_pid = ws->value.related_pid;
7847   return 1;
7848 }
7849
7850 /* Implement the "print_it" breakpoint_ops method for vfork
7851    catchpoints.  */
7852
7853 static enum print_stop_action
7854 print_it_catch_vfork (bpstat bs)
7855 {
7856   struct ui_out *uiout = current_uiout;
7857   struct breakpoint *b = bs->breakpoint_at;
7858   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7859
7860   annotate_catchpoint (b->number);
7861   maybe_print_thread_hit_breakpoint (uiout);
7862   if (b->disposition == disp_del)
7863     uiout->text ("Temporary catchpoint ");
7864   else
7865     uiout->text ("Catchpoint ");
7866   if (uiout->is_mi_like_p ())
7867     {
7868       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
7869       uiout->field_string ("disp", bpdisp_text (b->disposition));
7870     }
7871   uiout->field_int ("bkptno", b->number);
7872   uiout->text (" (vforked process ");
7873   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
7874   uiout->text ("), ");
7875   return PRINT_SRC_AND_LOC;
7876 }
7877
7878 /* Implement the "print_one" breakpoint_ops method for vfork
7879    catchpoints.  */
7880
7881 static void
7882 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7883 {
7884   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7885   struct value_print_options opts;
7886   struct ui_out *uiout = current_uiout;
7887
7888   get_user_print_options (&opts);
7889   /* Field 4, the address, is omitted (which makes the columns not
7890      line up too nicely with the headers, but the effect is relatively
7891      readable).  */
7892   if (opts.addressprint)
7893     uiout->field_skip ("addr");
7894   annotate_field (5);
7895   uiout->text ("vfork");
7896   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7897     {
7898       uiout->text (", process ");
7899       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
7900       uiout->spaces (1);
7901     }
7902
7903   if (uiout->is_mi_like_p ())
7904     uiout->field_string ("catch-type", "vfork");
7905 }
7906
7907 /* Implement the "print_mention" breakpoint_ops method for vfork
7908    catchpoints.  */
7909
7910 static void
7911 print_mention_catch_vfork (struct breakpoint *b)
7912 {
7913   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7914 }
7915
7916 /* Implement the "print_recreate" breakpoint_ops method for vfork
7917    catchpoints.  */
7918
7919 static void
7920 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7921 {
7922   fprintf_unfiltered (fp, "catch vfork");
7923   print_recreate_thread (b, fp);
7924 }
7925
7926 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7927
7928 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7929
7930 /* An instance of this type is used to represent an solib catchpoint.
7931    A breakpoint is really of this type iff its ops pointer points to
7932    CATCH_SOLIB_BREAKPOINT_OPS.  */
7933
7934 struct solib_catchpoint : public breakpoint
7935 {
7936   ~solib_catchpoint () override;
7937
7938   /* True for "catch load", false for "catch unload".  */
7939   unsigned char is_load;
7940
7941   /* Regular expression to match, if any.  COMPILED is only valid when
7942      REGEX is non-NULL.  */
7943   char *regex;
7944   std::unique_ptr<compiled_regex> compiled;
7945 };
7946
7947 solib_catchpoint::~solib_catchpoint ()
7948 {
7949   xfree (this->regex);
7950 }
7951
7952 static int
7953 insert_catch_solib (struct bp_location *ignore)
7954 {
7955   return 0;
7956 }
7957
7958 static int
7959 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
7960 {
7961   return 0;
7962 }
7963
7964 static int
7965 breakpoint_hit_catch_solib (const struct bp_location *bl,
7966                             const address_space *aspace,
7967                             CORE_ADDR bp_addr,
7968                             const struct target_waitstatus *ws)
7969 {
7970   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7971   struct breakpoint *other;
7972
7973   if (ws->kind == TARGET_WAITKIND_LOADED)
7974     return 1;
7975
7976   ALL_BREAKPOINTS (other)
7977   {
7978     struct bp_location *other_bl;
7979
7980     if (other == bl->owner)
7981       continue;
7982
7983     if (other->type != bp_shlib_event)
7984       continue;
7985
7986     if (self->pspace != NULL && other->pspace != self->pspace)
7987       continue;
7988
7989     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7990       {
7991         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7992           return 1;
7993       }
7994   }
7995
7996   return 0;
7997 }
7998
7999 static void
8000 check_status_catch_solib (struct bpstats *bs)
8001 {
8002   struct solib_catchpoint *self
8003     = (struct solib_catchpoint *) bs->breakpoint_at;
8004
8005   if (self->is_load)
8006     {
8007       for (so_list *iter : current_program_space->added_solibs)
8008         {
8009           if (!self->regex
8010               || self->compiled->exec (iter->so_name, 0, NULL, 0) == 0)
8011             return;
8012         }
8013     }
8014   else
8015     {
8016       for (const std::string &iter : current_program_space->deleted_solibs)
8017         {
8018           if (!self->regex
8019               || self->compiled->exec (iter.c_str (), 0, NULL, 0) == 0)
8020             return;
8021         }
8022     }
8023
8024   bs->stop = 0;
8025   bs->print_it = print_it_noop;
8026 }
8027
8028 static enum print_stop_action
8029 print_it_catch_solib (bpstat bs)
8030 {
8031   struct breakpoint *b = bs->breakpoint_at;
8032   struct ui_out *uiout = current_uiout;
8033
8034   annotate_catchpoint (b->number);
8035   maybe_print_thread_hit_breakpoint (uiout);
8036   if (b->disposition == disp_del)
8037     uiout->text ("Temporary catchpoint ");
8038   else
8039     uiout->text ("Catchpoint ");
8040   uiout->field_int ("bkptno", b->number);
8041   uiout->text ("\n");
8042   if (uiout->is_mi_like_p ())
8043     uiout->field_string ("disp", bpdisp_text (b->disposition));
8044   print_solib_event (1);
8045   return PRINT_SRC_AND_LOC;
8046 }
8047
8048 static void
8049 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8050 {
8051   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8052   struct value_print_options opts;
8053   struct ui_out *uiout = current_uiout;
8054   char *msg;
8055
8056   get_user_print_options (&opts);
8057   /* Field 4, the address, is omitted (which makes the columns not
8058      line up too nicely with the headers, but the effect is relatively
8059      readable).  */
8060   if (opts.addressprint)
8061     {
8062       annotate_field (4);
8063       uiout->field_skip ("addr");
8064     }
8065
8066   annotate_field (5);
8067   if (self->is_load)
8068     {
8069       if (self->regex)
8070         msg = xstrprintf (_("load of library matching %s"), self->regex);
8071       else
8072         msg = xstrdup (_("load of library"));
8073     }
8074   else
8075     {
8076       if (self->regex)
8077         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8078       else
8079         msg = xstrdup (_("unload of library"));
8080     }
8081   uiout->field_string ("what", msg);
8082   xfree (msg);
8083
8084   if (uiout->is_mi_like_p ())
8085     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8086 }
8087
8088 static void
8089 print_mention_catch_solib (struct breakpoint *b)
8090 {
8091   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8092
8093   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8094                    self->is_load ? "load" : "unload");
8095 }
8096
8097 static void
8098 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8099 {
8100   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8101
8102   fprintf_unfiltered (fp, "%s %s",
8103                       b->disposition == disp_del ? "tcatch" : "catch",
8104                       self->is_load ? "load" : "unload");
8105   if (self->regex)
8106     fprintf_unfiltered (fp, " %s", self->regex);
8107   fprintf_unfiltered (fp, "\n");
8108 }
8109
8110 static struct breakpoint_ops catch_solib_breakpoint_ops;
8111
8112 /* Shared helper function (MI and CLI) for creating and installing
8113    a shared object event catchpoint.  If IS_LOAD is non-zero then
8114    the events to be caught are load events, otherwise they are
8115    unload events.  If IS_TEMP is non-zero the catchpoint is a
8116    temporary one.  If ENABLED is non-zero the catchpoint is
8117    created in an enabled state.  */
8118
8119 void
8120 add_solib_catchpoint (const char *arg, int is_load, int is_temp, int enabled)
8121 {
8122   struct gdbarch *gdbarch = get_current_arch ();
8123
8124   if (!arg)
8125     arg = "";
8126   arg = skip_spaces (arg);
8127
8128   std::unique_ptr<solib_catchpoint> c (new solib_catchpoint ());
8129
8130   if (*arg != '\0')
8131     {
8132       c->compiled.reset (new compiled_regex (arg, REG_NOSUB,
8133                                              _("Invalid regexp")));
8134       c->regex = xstrdup (arg);
8135     }
8136
8137   c->is_load = is_load;
8138   init_catchpoint (c.get (), gdbarch, is_temp, NULL,
8139                    &catch_solib_breakpoint_ops);
8140
8141   c->enable_state = enabled ? bp_enabled : bp_disabled;
8142
8143   install_breakpoint (0, std::move (c), 1);
8144 }
8145
8146 /* A helper function that does all the work for "catch load" and
8147    "catch unload".  */
8148
8149 static void
8150 catch_load_or_unload (const char *arg, int from_tty, int is_load,
8151                       struct cmd_list_element *command)
8152 {
8153   int tempflag;
8154   const int enabled = 1;
8155
8156   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8157
8158   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8159 }
8160
8161 static void
8162 catch_load_command_1 (const char *arg, int from_tty,
8163                       struct cmd_list_element *command)
8164 {
8165   catch_load_or_unload (arg, from_tty, 1, command);
8166 }
8167
8168 static void
8169 catch_unload_command_1 (const char *arg, int from_tty,
8170                         struct cmd_list_element *command)
8171 {
8172   catch_load_or_unload (arg, from_tty, 0, command);
8173 }
8174
8175 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8176    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8177    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8178    the breakpoint_ops structure associated to the catchpoint.  */
8179
8180 void
8181 init_catchpoint (struct breakpoint *b,
8182                  struct gdbarch *gdbarch, int tempflag,
8183                  const char *cond_string,
8184                  const struct breakpoint_ops *ops)
8185 {
8186   symtab_and_line sal;
8187   sal.pspace = current_program_space;
8188
8189   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8190
8191   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8192   b->disposition = tempflag ? disp_del : disp_donttouch;
8193 }
8194
8195 void
8196 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8197 {
8198   breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8199   set_breakpoint_number (internal, b);
8200   if (is_tracepoint (b))
8201     set_tracepoint_count (breakpoint_count);
8202   if (!internal)
8203     mention (b);
8204   gdb::observers::breakpoint_created.notify (b);
8205
8206   if (update_gll)
8207     update_global_location_list (UGLL_MAY_INSERT);
8208 }
8209
8210 static void
8211 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8212                                     int tempflag, const char *cond_string,
8213                                     const struct breakpoint_ops *ops)
8214 {
8215   std::unique_ptr<fork_catchpoint> c (new fork_catchpoint ());
8216
8217   init_catchpoint (c.get (), gdbarch, tempflag, cond_string, ops);
8218
8219   c->forked_inferior_pid = null_ptid;
8220
8221   install_breakpoint (0, std::move (c), 1);
8222 }
8223
8224 /* Exec catchpoints.  */
8225
8226 /* An instance of this type is used to represent an exec catchpoint.
8227    A breakpoint is really of this type iff its ops pointer points to
8228    CATCH_EXEC_BREAKPOINT_OPS.  */
8229
8230 struct exec_catchpoint : public breakpoint
8231 {
8232   ~exec_catchpoint () override;
8233
8234   /* Filename of a program whose exec triggered this catchpoint.
8235      This field is only valid immediately after this catchpoint has
8236      triggered.  */
8237   char *exec_pathname;
8238 };
8239
8240 /* Exec catchpoint destructor.  */
8241
8242 exec_catchpoint::~exec_catchpoint ()
8243 {
8244   xfree (this->exec_pathname);
8245 }
8246
8247 static int
8248 insert_catch_exec (struct bp_location *bl)
8249 {
8250   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8251 }
8252
8253 static int
8254 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8255 {
8256   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8257 }
8258
8259 static int
8260 breakpoint_hit_catch_exec (const struct bp_location *bl,
8261                            const address_space *aspace, CORE_ADDR bp_addr,
8262                            const struct target_waitstatus *ws)
8263 {
8264   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8265
8266   if (ws->kind != TARGET_WAITKIND_EXECD)
8267     return 0;
8268
8269   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8270   return 1;
8271 }
8272
8273 static enum print_stop_action
8274 print_it_catch_exec (bpstat bs)
8275 {
8276   struct ui_out *uiout = current_uiout;
8277   struct breakpoint *b = bs->breakpoint_at;
8278   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8279
8280   annotate_catchpoint (b->number);
8281   maybe_print_thread_hit_breakpoint (uiout);
8282   if (b->disposition == disp_del)
8283     uiout->text ("Temporary catchpoint ");
8284   else
8285     uiout->text ("Catchpoint ");
8286   if (uiout->is_mi_like_p ())
8287     {
8288       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8289       uiout->field_string ("disp", bpdisp_text (b->disposition));
8290     }
8291   uiout->field_int ("bkptno", b->number);
8292   uiout->text (" (exec'd ");
8293   uiout->field_string ("new-exec", c->exec_pathname);
8294   uiout->text ("), ");
8295
8296   return PRINT_SRC_AND_LOC;
8297 }
8298
8299 static void
8300 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8301 {
8302   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8303   struct value_print_options opts;
8304   struct ui_out *uiout = current_uiout;
8305
8306   get_user_print_options (&opts);
8307
8308   /* Field 4, the address, is omitted (which makes the columns
8309      not line up too nicely with the headers, but the effect
8310      is relatively readable).  */
8311   if (opts.addressprint)
8312     uiout->field_skip ("addr");
8313   annotate_field (5);
8314   uiout->text ("exec");
8315   if (c->exec_pathname != NULL)
8316     {
8317       uiout->text (", program \"");
8318       uiout->field_string ("what", c->exec_pathname);
8319       uiout->text ("\" ");
8320     }
8321
8322   if (uiout->is_mi_like_p ())
8323     uiout->field_string ("catch-type", "exec");
8324 }
8325
8326 static void
8327 print_mention_catch_exec (struct breakpoint *b)
8328 {
8329   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8330 }
8331
8332 /* Implement the "print_recreate" breakpoint_ops method for exec
8333    catchpoints.  */
8334
8335 static void
8336 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8337 {
8338   fprintf_unfiltered (fp, "catch exec");
8339   print_recreate_thread (b, fp);
8340 }
8341
8342 static struct breakpoint_ops catch_exec_breakpoint_ops;
8343
8344 static int
8345 hw_breakpoint_used_count (void)
8346 {
8347   int i = 0;
8348   struct breakpoint *b;
8349   struct bp_location *bl;
8350
8351   ALL_BREAKPOINTS (b)
8352   {
8353     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8354       for (bl = b->loc; bl; bl = bl->next)
8355         {
8356           /* Special types of hardware breakpoints may use more than
8357              one register.  */
8358           i += b->ops->resources_needed (bl);
8359         }
8360   }
8361
8362   return i;
8363 }
8364
8365 /* Returns the resources B would use if it were a hardware
8366    watchpoint.  */
8367
8368 static int
8369 hw_watchpoint_use_count (struct breakpoint *b)
8370 {
8371   int i = 0;
8372   struct bp_location *bl;
8373
8374   if (!breakpoint_enabled (b))
8375     return 0;
8376
8377   for (bl = b->loc; bl; bl = bl->next)
8378     {
8379       /* Special types of hardware watchpoints may use more than
8380          one register.  */
8381       i += b->ops->resources_needed (bl);
8382     }
8383
8384   return i;
8385 }
8386
8387 /* Returns the sum the used resources of all hardware watchpoints of
8388    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8389    the sum of the used resources of all hardware watchpoints of other
8390    types _not_ TYPE.  */
8391
8392 static int
8393 hw_watchpoint_used_count_others (struct breakpoint *except,
8394                                  enum bptype type, int *other_type_used)
8395 {
8396   int i = 0;
8397   struct breakpoint *b;
8398
8399   *other_type_used = 0;
8400   ALL_BREAKPOINTS (b)
8401     {
8402       if (b == except)
8403         continue;
8404       if (!breakpoint_enabled (b))
8405         continue;
8406
8407       if (b->type == type)
8408         i += hw_watchpoint_use_count (b);
8409       else if (is_hardware_watchpoint (b))
8410         *other_type_used = 1;
8411     }
8412
8413   return i;
8414 }
8415
8416 void
8417 disable_watchpoints_before_interactive_call_start (void)
8418 {
8419   struct breakpoint *b;
8420
8421   ALL_BREAKPOINTS (b)
8422   {
8423     if (is_watchpoint (b) && breakpoint_enabled (b))
8424       {
8425         b->enable_state = bp_call_disabled;
8426         update_global_location_list (UGLL_DONT_INSERT);
8427       }
8428   }
8429 }
8430
8431 void
8432 enable_watchpoints_after_interactive_call_stop (void)
8433 {
8434   struct breakpoint *b;
8435
8436   ALL_BREAKPOINTS (b)
8437   {
8438     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8439       {
8440         b->enable_state = bp_enabled;
8441         update_global_location_list (UGLL_MAY_INSERT);
8442       }
8443   }
8444 }
8445
8446 void
8447 disable_breakpoints_before_startup (void)
8448 {
8449   current_program_space->executing_startup = 1;
8450   update_global_location_list (UGLL_DONT_INSERT);
8451 }
8452
8453 void
8454 enable_breakpoints_after_startup (void)
8455 {
8456   current_program_space->executing_startup = 0;
8457   breakpoint_re_set ();
8458 }
8459
8460 /* Create a new single-step breakpoint for thread THREAD, with no
8461    locations.  */
8462
8463 static struct breakpoint *
8464 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8465 {
8466   std::unique_ptr<breakpoint> b (new breakpoint ());
8467
8468   init_raw_breakpoint_without_location (b.get (), gdbarch, bp_single_step,
8469                                         &momentary_breakpoint_ops);
8470
8471   b->disposition = disp_donttouch;
8472   b->frame_id = null_frame_id;
8473
8474   b->thread = thread;
8475   gdb_assert (b->thread != 0);
8476
8477   return add_to_breakpoint_chain (std::move (b));
8478 }
8479
8480 /* Set a momentary breakpoint of type TYPE at address specified by
8481    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8482    frame.  */
8483
8484 breakpoint_up
8485 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8486                           struct frame_id frame_id, enum bptype type)
8487 {
8488   struct breakpoint *b;
8489
8490   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8491      tail-called one.  */
8492   gdb_assert (!frame_id_artificial_p (frame_id));
8493
8494   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8495   b->enable_state = bp_enabled;
8496   b->disposition = disp_donttouch;
8497   b->frame_id = frame_id;
8498
8499   /* If we're debugging a multi-threaded program, then we want
8500      momentary breakpoints to be active in only a single thread of
8501      control.  */
8502   if (in_thread_list (inferior_ptid))
8503     b->thread = ptid_to_global_thread_id (inferior_ptid);
8504
8505   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8506
8507   return breakpoint_up (b);
8508 }
8509
8510 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8511    The new breakpoint will have type TYPE, use OPS as its
8512    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8513
8514 static struct breakpoint *
8515 momentary_breakpoint_from_master (struct breakpoint *orig,
8516                                   enum bptype type,
8517                                   const struct breakpoint_ops *ops,
8518                                   int loc_enabled)
8519 {
8520   struct breakpoint *copy;
8521
8522   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8523   copy->loc = allocate_bp_location (copy);
8524   set_breakpoint_location_function (copy->loc, 1);
8525
8526   copy->loc->gdbarch = orig->loc->gdbarch;
8527   copy->loc->requested_address = orig->loc->requested_address;
8528   copy->loc->address = orig->loc->address;
8529   copy->loc->section = orig->loc->section;
8530   copy->loc->pspace = orig->loc->pspace;
8531   copy->loc->probe = orig->loc->probe;
8532   copy->loc->line_number = orig->loc->line_number;
8533   copy->loc->symtab = orig->loc->symtab;
8534   copy->loc->enabled = loc_enabled;
8535   copy->frame_id = orig->frame_id;
8536   copy->thread = orig->thread;
8537   copy->pspace = orig->pspace;
8538
8539   copy->enable_state = bp_enabled;
8540   copy->disposition = disp_donttouch;
8541   copy->number = internal_breakpoint_number--;
8542
8543   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8544   return copy;
8545 }
8546
8547 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8548    ORIG is NULL.  */
8549
8550 struct breakpoint *
8551 clone_momentary_breakpoint (struct breakpoint *orig)
8552 {
8553   /* If there's nothing to clone, then return nothing.  */
8554   if (orig == NULL)
8555     return NULL;
8556
8557   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8558 }
8559
8560 breakpoint_up
8561 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8562                                 enum bptype type)
8563 {
8564   struct symtab_and_line sal;
8565
8566   sal = find_pc_line (pc, 0);
8567   sal.pc = pc;
8568   sal.section = find_pc_overlay (pc);
8569   sal.explicit_pc = 1;
8570
8571   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8572 }
8573 \f
8574
8575 /* Tell the user we have just set a breakpoint B.  */
8576
8577 static void
8578 mention (struct breakpoint *b)
8579 {
8580   b->ops->print_mention (b);
8581   current_uiout->text ("\n");
8582 }
8583 \f
8584
8585 static int bp_loc_is_permanent (struct bp_location *loc);
8586
8587 static struct bp_location *
8588 add_location_to_breakpoint (struct breakpoint *b,
8589                             const struct symtab_and_line *sal)
8590 {
8591   struct bp_location *loc, **tmp;
8592   CORE_ADDR adjusted_address;
8593   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8594
8595   if (loc_gdbarch == NULL)
8596     loc_gdbarch = b->gdbarch;
8597
8598   /* Adjust the breakpoint's address prior to allocating a location.
8599      Once we call allocate_bp_location(), that mostly uninitialized
8600      location will be placed on the location chain.  Adjustment of the
8601      breakpoint may cause target_read_memory() to be called and we do
8602      not want its scan of the location chain to find a breakpoint and
8603      location that's only been partially initialized.  */
8604   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8605                                                 sal->pc, b->type);
8606
8607   /* Sort the locations by their ADDRESS.  */
8608   loc = allocate_bp_location (b);
8609   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8610        tmp = &((*tmp)->next))
8611     ;
8612   loc->next = *tmp;
8613   *tmp = loc;
8614
8615   loc->requested_address = sal->pc;
8616   loc->address = adjusted_address;
8617   loc->pspace = sal->pspace;
8618   loc->probe.prob = sal->prob;
8619   loc->probe.objfile = sal->objfile;
8620   gdb_assert (loc->pspace != NULL);
8621   loc->section = sal->section;
8622   loc->gdbarch = loc_gdbarch;
8623   loc->line_number = sal->line;
8624   loc->symtab = sal->symtab;
8625   loc->symbol = sal->symbol;
8626   loc->msymbol = sal->msymbol;
8627   loc->objfile = sal->objfile;
8628
8629   set_breakpoint_location_function (loc,
8630                                     sal->explicit_pc || sal->explicit_line);
8631
8632   /* While by definition, permanent breakpoints are already present in the
8633      code, we don't mark the location as inserted.  Normally one would expect
8634      that GDB could rely on that breakpoint instruction to stop the program,
8635      thus removing the need to insert its own breakpoint, except that executing
8636      the breakpoint instruction can kill the target instead of reporting a
8637      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8638      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8639      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8640      breakpoint be inserted normally results in QEMU knowing about the GDB
8641      breakpoint, and thus trap before the breakpoint instruction is executed.
8642      (If GDB later needs to continue execution past the permanent breakpoint,
8643      it manually increments the PC, thus avoiding executing the breakpoint
8644      instruction.)  */
8645   if (bp_loc_is_permanent (loc))
8646     loc->permanent = 1;
8647
8648   return loc;
8649 }
8650 \f
8651
8652 /* See breakpoint.h.  */
8653
8654 int
8655 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
8656 {
8657   int len;
8658   CORE_ADDR addr;
8659   const gdb_byte *bpoint;
8660   gdb_byte *target_mem;
8661
8662   addr = address;
8663   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
8664
8665   /* Software breakpoints unsupported?  */
8666   if (bpoint == NULL)
8667     return 0;
8668
8669   target_mem = (gdb_byte *) alloca (len);
8670
8671   /* Enable the automatic memory restoration from breakpoints while
8672      we read the memory.  Otherwise we could say about our temporary
8673      breakpoints they are permanent.  */
8674   scoped_restore restore_memory
8675     = make_scoped_restore_show_memory_breakpoints (0);
8676
8677   if (target_read_memory (address, target_mem, len) == 0
8678       && memcmp (target_mem, bpoint, len) == 0)
8679     return 1;
8680
8681   return 0;
8682 }
8683
8684 /* Return 1 if LOC is pointing to a permanent breakpoint,
8685    return 0 otherwise.  */
8686
8687 static int
8688 bp_loc_is_permanent (struct bp_location *loc)
8689 {
8690   gdb_assert (loc != NULL);
8691
8692   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
8693      attempt to read from the addresses the locations of these breakpoint types
8694      point to.  program_breakpoint_here_p, below, will attempt to read
8695      memory.  */
8696   if (!breakpoint_address_is_meaningful (loc->owner))
8697     return 0;
8698
8699   scoped_restore_current_pspace_and_thread restore_pspace_thread;
8700   switch_to_program_space_and_thread (loc->pspace);
8701   return program_breakpoint_here_p (loc->gdbarch, loc->address);
8702 }
8703
8704 /* Build a command list for the dprintf corresponding to the current
8705    settings of the dprintf style options.  */
8706
8707 static void
8708 update_dprintf_command_list (struct breakpoint *b)
8709 {
8710   char *dprintf_args = b->extra_string;
8711   char *printf_line = NULL;
8712
8713   if (!dprintf_args)
8714     return;
8715
8716   dprintf_args = skip_spaces (dprintf_args);
8717
8718   /* Allow a comma, as it may have terminated a location, but don't
8719      insist on it.  */
8720   if (*dprintf_args == ',')
8721     ++dprintf_args;
8722   dprintf_args = skip_spaces (dprintf_args);
8723
8724   if (*dprintf_args != '"')
8725     error (_("Bad format string, missing '\"'."));
8726
8727   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8728     printf_line = xstrprintf ("printf %s", dprintf_args);
8729   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8730     {
8731       if (!dprintf_function)
8732         error (_("No function supplied for dprintf call"));
8733
8734       if (dprintf_channel && strlen (dprintf_channel) > 0)
8735         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8736                                   dprintf_function,
8737                                   dprintf_channel,
8738                                   dprintf_args);
8739       else
8740         printf_line = xstrprintf ("call (void) %s (%s)",
8741                                   dprintf_function,
8742                                   dprintf_args);
8743     }
8744   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8745     {
8746       if (target_can_run_breakpoint_commands ())
8747         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8748       else
8749         {
8750           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8751           printf_line = xstrprintf ("printf %s", dprintf_args);
8752         }
8753     }
8754   else
8755     internal_error (__FILE__, __LINE__,
8756                     _("Invalid dprintf style."));
8757
8758   gdb_assert (printf_line != NULL);
8759
8760   /* Manufacture a printf sequence.  */
8761   struct command_line *printf_cmd_line
8762     = new struct command_line (simple_control, printf_line);
8763   breakpoint_set_commands (b, counted_command_line (printf_cmd_line,
8764                                                     command_lines_deleter ()));
8765 }
8766
8767 /* Update all dprintf commands, making their command lists reflect
8768    current style settings.  */
8769
8770 static void
8771 update_dprintf_commands (const char *args, int from_tty,
8772                          struct cmd_list_element *c)
8773 {
8774   struct breakpoint *b;
8775
8776   ALL_BREAKPOINTS (b)
8777     {
8778       if (b->type == bp_dprintf)
8779         update_dprintf_command_list (b);
8780     }
8781 }
8782
8783 /* Create a breakpoint with SAL as location.  Use LOCATION
8784    as a description of the location, and COND_STRING
8785    as condition expression.  If LOCATION is NULL then create an
8786    "address location" from the address in the SAL.  */
8787
8788 static void
8789 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8790                      gdb::array_view<const symtab_and_line> sals,
8791                      event_location_up &&location,
8792                      gdb::unique_xmalloc_ptr<char> filter,
8793                      gdb::unique_xmalloc_ptr<char> cond_string,
8794                      gdb::unique_xmalloc_ptr<char> extra_string,
8795                      enum bptype type, enum bpdisp disposition,
8796                      int thread, int task, int ignore_count,
8797                      const struct breakpoint_ops *ops, int from_tty,
8798                      int enabled, int internal, unsigned flags,
8799                      int display_canonical)
8800 {
8801   int i;
8802
8803   if (type == bp_hardware_breakpoint)
8804     {
8805       int target_resources_ok;
8806
8807       i = hw_breakpoint_used_count ();
8808       target_resources_ok =
8809         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8810                                             i + 1, 0);
8811       if (target_resources_ok == 0)
8812         error (_("No hardware breakpoint support in the target."));
8813       else if (target_resources_ok < 0)
8814         error (_("Hardware breakpoints used exceeds limit."));
8815     }
8816
8817   gdb_assert (!sals.empty ());
8818
8819   for (const auto &sal : sals)
8820     {
8821       struct bp_location *loc;
8822
8823       if (from_tty)
8824         {
8825           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8826           if (!loc_gdbarch)
8827             loc_gdbarch = gdbarch;
8828
8829           describe_other_breakpoints (loc_gdbarch,
8830                                       sal.pspace, sal.pc, sal.section, thread);
8831         }
8832
8833       if (&sal == &sals[0])
8834         {
8835           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8836           b->thread = thread;
8837           b->task = task;
8838
8839           b->cond_string = cond_string.release ();
8840           b->extra_string = extra_string.release ();
8841           b->ignore_count = ignore_count;
8842           b->enable_state = enabled ? bp_enabled : bp_disabled;
8843           b->disposition = disposition;
8844
8845           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8846             b->loc->inserted = 1;
8847
8848           if (type == bp_static_tracepoint)
8849             {
8850               struct tracepoint *t = (struct tracepoint *) b;
8851               struct static_tracepoint_marker marker;
8852
8853               if (strace_marker_p (b))
8854                 {
8855                   /* We already know the marker exists, otherwise, we
8856                      wouldn't see a sal for it.  */
8857                   const char *p
8858                     = &event_location_to_string (b->location.get ())[3];
8859                   const char *endp;
8860
8861                   p = skip_spaces (p);
8862
8863                   endp = skip_to_space (p);
8864
8865                   t->static_trace_marker_id.assign (p, endp - p);
8866
8867                   printf_filtered (_("Probed static tracepoint "
8868                                      "marker \"%s\"\n"),
8869                                    t->static_trace_marker_id.c_str ());
8870                 }
8871               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8872                 {
8873                   t->static_trace_marker_id = std::move (marker.str_id);
8874
8875                   printf_filtered (_("Probed static tracepoint "
8876                                      "marker \"%s\"\n"),
8877                                    t->static_trace_marker_id.c_str ());
8878                 }
8879               else
8880                 warning (_("Couldn't determine the static "
8881                            "tracepoint marker to probe"));
8882             }
8883
8884           loc = b->loc;
8885         }
8886       else
8887         {
8888           loc = add_location_to_breakpoint (b, &sal);
8889           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8890             loc->inserted = 1;
8891         }
8892
8893       if (b->cond_string)
8894         {
8895           const char *arg = b->cond_string;
8896
8897           loc->cond = parse_exp_1 (&arg, loc->address,
8898                                    block_for_pc (loc->address), 0);
8899           if (*arg)
8900               error (_("Garbage '%s' follows condition"), arg);
8901         }
8902
8903       /* Dynamic printf requires and uses additional arguments on the
8904          command line, otherwise it's an error.  */
8905       if (type == bp_dprintf)
8906         {
8907           if (b->extra_string)
8908             update_dprintf_command_list (b);
8909           else
8910             error (_("Format string required"));
8911         }
8912       else if (b->extra_string)
8913         error (_("Garbage '%s' at end of command"), b->extra_string);
8914     }
8915
8916   b->display_canonical = display_canonical;
8917   if (location != NULL)
8918     b->location = std::move (location);
8919   else
8920     b->location = new_address_location (b->loc->address, NULL, 0);
8921   b->filter = filter.release ();
8922 }
8923
8924 static void
8925 create_breakpoint_sal (struct gdbarch *gdbarch,
8926                        gdb::array_view<const symtab_and_line> sals,
8927                        event_location_up &&location,
8928                        gdb::unique_xmalloc_ptr<char> filter,
8929                        gdb::unique_xmalloc_ptr<char> cond_string,
8930                        gdb::unique_xmalloc_ptr<char> extra_string,
8931                        enum bptype type, enum bpdisp disposition,
8932                        int thread, int task, int ignore_count,
8933                        const struct breakpoint_ops *ops, int from_tty,
8934                        int enabled, int internal, unsigned flags,
8935                        int display_canonical)
8936 {
8937   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (type);
8938
8939   init_breakpoint_sal (b.get (), gdbarch,
8940                        sals, std::move (location),
8941                        std::move (filter),
8942                        std::move (cond_string),
8943                        std::move (extra_string),
8944                        type, disposition,
8945                        thread, task, ignore_count,
8946                        ops, from_tty,
8947                        enabled, internal, flags,
8948                        display_canonical);
8949
8950   install_breakpoint (internal, std::move (b), 0);
8951 }
8952
8953 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
8954    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8955    value.  COND_STRING, if not NULL, specified the condition to be
8956    used for all breakpoints.  Essentially the only case where
8957    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8958    function.  In that case, it's still not possible to specify
8959    separate conditions for different overloaded functions, so
8960    we take just a single condition string.
8961    
8962    NOTE: If the function succeeds, the caller is expected to cleanup
8963    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8964    array contents).  If the function fails (error() is called), the
8965    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8966    COND and SALS arrays and each of those arrays contents.  */
8967
8968 static void
8969 create_breakpoints_sal (struct gdbarch *gdbarch,
8970                         struct linespec_result *canonical,
8971                         gdb::unique_xmalloc_ptr<char> cond_string,
8972                         gdb::unique_xmalloc_ptr<char> extra_string,
8973                         enum bptype type, enum bpdisp disposition,
8974                         int thread, int task, int ignore_count,
8975                         const struct breakpoint_ops *ops, int from_tty,
8976                         int enabled, int internal, unsigned flags)
8977 {
8978   if (canonical->pre_expanded)
8979     gdb_assert (canonical->lsals.size () == 1);
8980
8981   for (const auto &lsal : canonical->lsals)
8982     {
8983       /* Note that 'location' can be NULL in the case of a plain
8984          'break', without arguments.  */
8985       event_location_up location
8986         = (canonical->location != NULL
8987            ? copy_event_location (canonical->location.get ()) : NULL);
8988       gdb::unique_xmalloc_ptr<char> filter_string
8989         (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
8990
8991       create_breakpoint_sal (gdbarch, lsal.sals,
8992                              std::move (location),
8993                              std::move (filter_string),
8994                              std::move (cond_string),
8995                              std::move (extra_string),
8996                              type, disposition,
8997                              thread, task, ignore_count, ops,
8998                              from_tty, enabled, internal, flags,
8999                              canonical->special_display);
9000     }
9001 }
9002
9003 /* Parse LOCATION which is assumed to be a SAL specification possibly
9004    followed by conditionals.  On return, SALS contains an array of SAL
9005    addresses found.  LOCATION points to the end of the SAL (for
9006    linespec locations).
9007
9008    The array and the line spec strings are allocated on the heap, it is
9009    the caller's responsibility to free them.  */
9010
9011 static void
9012 parse_breakpoint_sals (const struct event_location *location,
9013                        struct linespec_result *canonical)
9014 {
9015   struct symtab_and_line cursal;
9016
9017   if (event_location_type (location) == LINESPEC_LOCATION)
9018     {
9019       const char *spec = get_linespec_location (location)->spec_string;
9020
9021       if (spec == NULL)
9022         {
9023           /* The last displayed codepoint, if it's valid, is our default
9024              breakpoint address.  */
9025           if (last_displayed_sal_is_valid ())
9026             {
9027               /* Set sal's pspace, pc, symtab, and line to the values
9028                  corresponding to the last call to print_frame_info.
9029                  Be sure to reinitialize LINE with NOTCURRENT == 0
9030                  as the breakpoint line number is inappropriate otherwise.
9031                  find_pc_line would adjust PC, re-set it back.  */
9032               symtab_and_line sal = get_last_displayed_sal ();
9033               CORE_ADDR pc = sal.pc;
9034
9035               sal = find_pc_line (pc, 0);
9036
9037               /* "break" without arguments is equivalent to "break *PC"
9038                  where PC is the last displayed codepoint's address.  So
9039                  make sure to set sal.explicit_pc to prevent GDB from
9040                  trying to expand the list of sals to include all other
9041                  instances with the same symtab and line.  */
9042               sal.pc = pc;
9043               sal.explicit_pc = 1;
9044
9045               struct linespec_sals lsal;
9046               lsal.sals = {sal};
9047               lsal.canonical = NULL;
9048
9049               canonical->lsals.push_back (std::move (lsal));
9050               return;
9051             }
9052           else
9053             error (_("No default breakpoint address now."));
9054         }
9055     }
9056
9057   /* Force almost all breakpoints to be in terms of the
9058      current_source_symtab (which is decode_line_1's default).
9059      This should produce the results we want almost all of the
9060      time while leaving default_breakpoint_* alone.
9061
9062      ObjC: However, don't match an Objective-C method name which
9063      may have a '+' or '-' succeeded by a '['.  */
9064   cursal = get_current_source_symtab_and_line ();
9065   if (last_displayed_sal_is_valid ())
9066     {
9067       const char *spec = NULL;
9068
9069       if (event_location_type (location) == LINESPEC_LOCATION)
9070         spec = get_linespec_location (location)->spec_string;
9071
9072       if (!cursal.symtab
9073           || (spec != NULL
9074               && strchr ("+-", spec[0]) != NULL
9075               && spec[1] != '['))
9076         {
9077           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9078                             get_last_displayed_symtab (),
9079                             get_last_displayed_line (),
9080                             canonical, NULL, NULL);
9081           return;
9082         }
9083     }
9084
9085   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9086                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9087 }
9088
9089
9090 /* Convert each SAL into a real PC.  Verify that the PC can be
9091    inserted as a breakpoint.  If it can't throw an error.  */
9092
9093 static void
9094 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
9095 {    
9096   for (auto &sal : sals)
9097     resolve_sal_pc (&sal);
9098 }
9099
9100 /* Fast tracepoints may have restrictions on valid locations.  For
9101    instance, a fast tracepoint using a jump instead of a trap will
9102    likely have to overwrite more bytes than a trap would, and so can
9103    only be placed where the instruction is longer than the jump, or a
9104    multi-instruction sequence does not have a jump into the middle of
9105    it, etc.  */
9106
9107 static void
9108 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9109                             gdb::array_view<const symtab_and_line> sals)
9110 {
9111   for (const auto &sal : sals)
9112     {
9113       struct gdbarch *sarch;
9114
9115       sarch = get_sal_arch (sal);
9116       /* We fall back to GDBARCH if there is no architecture
9117          associated with SAL.  */
9118       if (sarch == NULL)
9119         sarch = gdbarch;
9120       std::string msg;
9121       if (!gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg))
9122         error (_("May not have a fast tracepoint at %s%s"),
9123                paddress (sarch, sal.pc), msg.c_str ());
9124     }
9125 }
9126
9127 /* Given TOK, a string specification of condition and thread, as
9128    accepted by the 'break' command, extract the condition
9129    string and thread number and set *COND_STRING and *THREAD.
9130    PC identifies the context at which the condition should be parsed.
9131    If no condition is found, *COND_STRING is set to NULL.
9132    If no thread is found, *THREAD is set to -1.  */
9133
9134 static void
9135 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9136                            char **cond_string, int *thread, int *task,
9137                            char **rest)
9138 {
9139   *cond_string = NULL;
9140   *thread = -1;
9141   *task = 0;
9142   *rest = NULL;
9143
9144   while (tok && *tok)
9145     {
9146       const char *end_tok;
9147       int toklen;
9148       const char *cond_start = NULL;
9149       const char *cond_end = NULL;
9150
9151       tok = skip_spaces (tok);
9152
9153       if ((*tok == '"' || *tok == ',') && rest)
9154         {
9155           *rest = savestring (tok, strlen (tok));
9156           return;
9157         }
9158
9159       end_tok = skip_to_space (tok);
9160
9161       toklen = end_tok - tok;
9162
9163       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9164         {
9165           tok = cond_start = end_tok + 1;
9166           parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9167           cond_end = tok;
9168           *cond_string = savestring (cond_start, cond_end - cond_start);
9169         }
9170       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9171         {
9172           const char *tmptok;
9173           struct thread_info *thr;
9174
9175           tok = end_tok + 1;
9176           thr = parse_thread_id (tok, &tmptok);
9177           if (tok == tmptok)
9178             error (_("Junk after thread keyword."));
9179           *thread = thr->global_num;
9180           tok = tmptok;
9181         }
9182       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9183         {
9184           char *tmptok;
9185
9186           tok = end_tok + 1;
9187           *task = strtol (tok, &tmptok, 0);
9188           if (tok == tmptok)
9189             error (_("Junk after task keyword."));
9190           if (!valid_task_id (*task))
9191             error (_("Unknown task %d."), *task);
9192           tok = tmptok;
9193         }
9194       else if (rest)
9195         {
9196           *rest = savestring (tok, strlen (tok));
9197           return;
9198         }
9199       else
9200         error (_("Junk at end of arguments."));
9201     }
9202 }
9203
9204 /* Decode a static tracepoint marker spec.  */
9205
9206 static std::vector<symtab_and_line>
9207 decode_static_tracepoint_spec (const char **arg_p)
9208 {
9209   const char *p = &(*arg_p)[3];
9210   const char *endp;
9211
9212   p = skip_spaces (p);
9213
9214   endp = skip_to_space (p);
9215
9216   std::string marker_str (p, endp - p);
9217
9218   std::vector<static_tracepoint_marker> markers
9219     = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
9220   if (markers.empty ())
9221     error (_("No known static tracepoint marker named %s"),
9222            marker_str.c_str ());
9223
9224   std::vector<symtab_and_line> sals;
9225   sals.reserve (markers.size ());
9226
9227   for (const static_tracepoint_marker &marker : markers)
9228     {
9229       symtab_and_line sal = find_pc_line (marker.address, 0);
9230       sal.pc = marker.address;
9231       sals.push_back (sal);
9232    }
9233
9234   *arg_p = endp;
9235   return sals;
9236 }
9237
9238 /* See breakpoint.h.  */
9239
9240 int
9241 create_breakpoint (struct gdbarch *gdbarch,
9242                    const struct event_location *location,
9243                    const char *cond_string,
9244                    int thread, const char *extra_string,
9245                    int parse_extra,
9246                    int tempflag, enum bptype type_wanted,
9247                    int ignore_count,
9248                    enum auto_boolean pending_break_support,
9249                    const struct breakpoint_ops *ops,
9250                    int from_tty, int enabled, int internal,
9251                    unsigned flags)
9252 {
9253   struct linespec_result canonical;
9254   struct cleanup *bkpt_chain = NULL;
9255   int pending = 0;
9256   int task = 0;
9257   int prev_bkpt_count = breakpoint_count;
9258
9259   gdb_assert (ops != NULL);
9260
9261   /* If extra_string isn't useful, set it to NULL.  */
9262   if (extra_string != NULL && *extra_string == '\0')
9263     extra_string = NULL;
9264
9265   TRY
9266     {
9267       ops->create_sals_from_location (location, &canonical, type_wanted);
9268     }
9269   CATCH (e, RETURN_MASK_ERROR)
9270     {
9271       /* If caller is interested in rc value from parse, set
9272          value.  */
9273       if (e.error == NOT_FOUND_ERROR)
9274         {
9275           /* If pending breakpoint support is turned off, throw
9276              error.  */
9277
9278           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9279             throw_exception (e);
9280
9281           exception_print (gdb_stderr, e);
9282
9283           /* If pending breakpoint support is auto query and the user
9284              selects no, then simply return the error code.  */
9285           if (pending_break_support == AUTO_BOOLEAN_AUTO
9286               && !nquery (_("Make %s pending on future shared library load? "),
9287                           bptype_string (type_wanted)))
9288             return 0;
9289
9290           /* At this point, either the user was queried about setting
9291              a pending breakpoint and selected yes, or pending
9292              breakpoint behavior is on and thus a pending breakpoint
9293              is defaulted on behalf of the user.  */
9294           pending = 1;
9295         }
9296       else
9297         throw_exception (e);
9298     }
9299   END_CATCH
9300
9301   if (!pending && canonical.lsals.empty ())
9302     return 0;
9303
9304   /* ----------------------------- SNIP -----------------------------
9305      Anything added to the cleanup chain beyond this point is assumed
9306      to be part of a breakpoint.  If the breakpoint create succeeds
9307      then the memory is not reclaimed.  */
9308   bkpt_chain = make_cleanup (null_cleanup, 0);
9309
9310   /* Resolve all line numbers to PC's and verify that the addresses
9311      are ok for the target.  */
9312   if (!pending)
9313     {
9314       for (auto &lsal : canonical.lsals)
9315         breakpoint_sals_to_pc (lsal.sals);
9316     }
9317
9318   /* Fast tracepoints may have additional restrictions on location.  */
9319   if (!pending && type_wanted == bp_fast_tracepoint)
9320     {
9321       for (const auto &lsal : canonical.lsals)
9322         check_fast_tracepoint_sals (gdbarch, lsal.sals);
9323     }
9324
9325   /* Verify that condition can be parsed, before setting any
9326      breakpoints.  Allocate a separate condition expression for each
9327      breakpoint.  */
9328   if (!pending)
9329     {
9330       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9331       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9332
9333       if (parse_extra)
9334         {
9335           char *rest;
9336           char *cond;
9337
9338           const linespec_sals &lsal = canonical.lsals[0];
9339
9340           /* Here we only parse 'arg' to separate condition
9341              from thread number, so parsing in context of first
9342              sal is OK.  When setting the breakpoint we'll
9343              re-parse it in context of each sal.  */
9344
9345           find_condition_and_thread (extra_string, lsal.sals[0].pc,
9346                                      &cond, &thread, &task, &rest);
9347           cond_string_copy.reset (cond);
9348           extra_string_copy.reset (rest);
9349         }
9350       else
9351         {
9352           if (type_wanted != bp_dprintf
9353               && extra_string != NULL && *extra_string != '\0')
9354                 error (_("Garbage '%s' at end of location"), extra_string);
9355
9356           /* Create a private copy of condition string.  */
9357           if (cond_string)
9358             cond_string_copy.reset (xstrdup (cond_string));
9359           /* Create a private copy of any extra string.  */
9360           if (extra_string)
9361             extra_string_copy.reset (xstrdup (extra_string));
9362         }
9363
9364       ops->create_breakpoints_sal (gdbarch, &canonical,
9365                                    std::move (cond_string_copy),
9366                                    std::move (extra_string_copy),
9367                                    type_wanted,
9368                                    tempflag ? disp_del : disp_donttouch,
9369                                    thread, task, ignore_count, ops,
9370                                    from_tty, enabled, internal, flags);
9371     }
9372   else
9373     {
9374       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (type_wanted);
9375
9376       init_raw_breakpoint_without_location (b.get (), gdbarch, type_wanted, ops);
9377       b->location = copy_event_location (location);
9378
9379       if (parse_extra)
9380         b->cond_string = NULL;
9381       else
9382         {
9383           /* Create a private copy of condition string.  */
9384           b->cond_string = cond_string != NULL ? xstrdup (cond_string) : NULL;
9385           b->thread = thread;
9386         }
9387
9388       /* Create a private copy of any extra string.  */
9389       b->extra_string = extra_string != NULL ? xstrdup (extra_string) : NULL;
9390       b->ignore_count = ignore_count;
9391       b->disposition = tempflag ? disp_del : disp_donttouch;
9392       b->condition_not_parsed = 1;
9393       b->enable_state = enabled ? bp_enabled : bp_disabled;
9394       if ((type_wanted != bp_breakpoint
9395            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9396         b->pspace = current_program_space;
9397
9398       install_breakpoint (internal, std::move (b), 0);
9399     }
9400   
9401   if (canonical.lsals.size () > 1)
9402     {
9403       warning (_("Multiple breakpoints were set.\nUse the "
9404                  "\"delete\" command to delete unwanted breakpoints."));
9405       prev_breakpoint_count = prev_bkpt_count;
9406     }
9407
9408   /* That's it.  Discard the cleanups for data inserted into the
9409      breakpoint.  */
9410   discard_cleanups (bkpt_chain);
9411
9412   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9413   update_global_location_list (UGLL_MAY_INSERT);
9414
9415   return 1;
9416 }
9417
9418 /* Set a breakpoint.
9419    ARG is a string describing breakpoint address,
9420    condition, and thread.
9421    FLAG specifies if a breakpoint is hardware on,
9422    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9423    and BP_TEMPFLAG.  */
9424
9425 static void
9426 break_command_1 (const char *arg, int flag, int from_tty)
9427 {
9428   int tempflag = flag & BP_TEMPFLAG;
9429   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9430                              ? bp_hardware_breakpoint
9431                              : bp_breakpoint);
9432   struct breakpoint_ops *ops;
9433
9434   event_location_up location = string_to_event_location (&arg, current_language);
9435
9436   /* Matching breakpoints on probes.  */
9437   if (location != NULL
9438       && event_location_type (location.get ()) == PROBE_LOCATION)
9439     ops = &bkpt_probe_breakpoint_ops;
9440   else
9441     ops = &bkpt_breakpoint_ops;
9442
9443   create_breakpoint (get_current_arch (),
9444                      location.get (),
9445                      NULL, 0, arg, 1 /* parse arg */,
9446                      tempflag, type_wanted,
9447                      0 /* Ignore count */,
9448                      pending_break_support,
9449                      ops,
9450                      from_tty,
9451                      1 /* enabled */,
9452                      0 /* internal */,
9453                      0);
9454 }
9455
9456 /* Helper function for break_command_1 and disassemble_command.  */
9457
9458 void
9459 resolve_sal_pc (struct symtab_and_line *sal)
9460 {
9461   CORE_ADDR pc;
9462
9463   if (sal->pc == 0 && sal->symtab != NULL)
9464     {
9465       if (!find_line_pc (sal->symtab, sal->line, &pc))
9466         error (_("No line %d in file \"%s\"."),
9467                sal->line, symtab_to_filename_for_display (sal->symtab));
9468       sal->pc = pc;
9469
9470       /* If this SAL corresponds to a breakpoint inserted using a line
9471          number, then skip the function prologue if necessary.  */
9472       if (sal->explicit_line)
9473         skip_prologue_sal (sal);
9474     }
9475
9476   if (sal->section == 0 && sal->symtab != NULL)
9477     {
9478       const struct blockvector *bv;
9479       const struct block *b;
9480       struct symbol *sym;
9481
9482       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9483                                     SYMTAB_COMPUNIT (sal->symtab));
9484       if (bv != NULL)
9485         {
9486           sym = block_linkage_function (b);
9487           if (sym != NULL)
9488             {
9489               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9490               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9491                                                  sym);
9492             }
9493           else
9494             {
9495               /* It really is worthwhile to have the section, so we'll
9496                  just have to look harder. This case can be executed
9497                  if we have line numbers but no functions (as can
9498                  happen in assembly source).  */
9499
9500               scoped_restore_current_pspace_and_thread restore_pspace_thread;
9501               switch_to_program_space_and_thread (sal->pspace);
9502
9503               bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9504               if (msym.minsym)
9505                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9506             }
9507         }
9508     }
9509 }
9510
9511 void
9512 break_command (const char *arg, int from_tty)
9513 {
9514   break_command_1 (arg, 0, from_tty);
9515 }
9516
9517 void
9518 tbreak_command (const char *arg, int from_tty)
9519 {
9520   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9521 }
9522
9523 static void
9524 hbreak_command (const char *arg, int from_tty)
9525 {
9526   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9527 }
9528
9529 static void
9530 thbreak_command (const char *arg, int from_tty)
9531 {
9532   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9533 }
9534
9535 static void
9536 stop_command (const char *arg, int from_tty)
9537 {
9538   printf_filtered (_("Specify the type of breakpoint to set.\n\
9539 Usage: stop in <function | address>\n\
9540        stop at <line>\n"));
9541 }
9542
9543 static void
9544 stopin_command (const char *arg, int from_tty)
9545 {
9546   int badInput = 0;
9547
9548   if (arg == (char *) NULL)
9549     badInput = 1;
9550   else if (*arg != '*')
9551     {
9552       const char *argptr = arg;
9553       int hasColon = 0;
9554
9555       /* Look for a ':'.  If this is a line number specification, then
9556          say it is bad, otherwise, it should be an address or
9557          function/method name.  */
9558       while (*argptr && !hasColon)
9559         {
9560           hasColon = (*argptr == ':');
9561           argptr++;
9562         }
9563
9564       if (hasColon)
9565         badInput = (*argptr != ':');    /* Not a class::method */
9566       else
9567         badInput = isdigit (*arg);      /* a simple line number */
9568     }
9569
9570   if (badInput)
9571     printf_filtered (_("Usage: stop in <function | address>\n"));
9572   else
9573     break_command_1 (arg, 0, from_tty);
9574 }
9575
9576 static void
9577 stopat_command (const char *arg, int from_tty)
9578 {
9579   int badInput = 0;
9580
9581   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9582     badInput = 1;
9583   else
9584     {
9585       const char *argptr = arg;
9586       int hasColon = 0;
9587
9588       /* Look for a ':'.  If there is a '::' then get out, otherwise
9589          it is probably a line number.  */
9590       while (*argptr && !hasColon)
9591         {
9592           hasColon = (*argptr == ':');
9593           argptr++;
9594         }
9595
9596       if (hasColon)
9597         badInput = (*argptr == ':');    /* we have class::method */
9598       else
9599         badInput = !isdigit (*arg);     /* not a line number */
9600     }
9601
9602   if (badInput)
9603     printf_filtered (_("Usage: stop at <line>\n"));
9604   else
9605     break_command_1 (arg, 0, from_tty);
9606 }
9607
9608 /* The dynamic printf command is mostly like a regular breakpoint, but
9609    with a prewired command list consisting of a single output command,
9610    built from extra arguments supplied on the dprintf command
9611    line.  */
9612
9613 static void
9614 dprintf_command (const char *arg, int from_tty)
9615 {
9616   event_location_up location = string_to_event_location (&arg, current_language);
9617
9618   /* If non-NULL, ARG should have been advanced past the location;
9619      the next character must be ','.  */
9620   if (arg != NULL)
9621     {
9622       if (arg[0] != ',' || arg[1] == '\0')
9623         error (_("Format string required"));
9624       else
9625         {
9626           /* Skip the comma.  */
9627           ++arg;
9628         }
9629     }
9630
9631   create_breakpoint (get_current_arch (),
9632                      location.get (),
9633                      NULL, 0, arg, 1 /* parse arg */,
9634                      0, bp_dprintf,
9635                      0 /* Ignore count */,
9636                      pending_break_support,
9637                      &dprintf_breakpoint_ops,
9638                      from_tty,
9639                      1 /* enabled */,
9640                      0 /* internal */,
9641                      0);
9642 }
9643
9644 static void
9645 agent_printf_command (const char *arg, int from_tty)
9646 {
9647   error (_("May only run agent-printf on the target"));
9648 }
9649
9650 /* Implement the "breakpoint_hit" breakpoint_ops method for
9651    ranged breakpoints.  */
9652
9653 static int
9654 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9655                                   const address_space *aspace,
9656                                   CORE_ADDR bp_addr,
9657                                   const struct target_waitstatus *ws)
9658 {
9659   if (ws->kind != TARGET_WAITKIND_STOPPED
9660       || ws->value.sig != GDB_SIGNAL_TRAP)
9661     return 0;
9662
9663   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9664                                          bl->length, aspace, bp_addr);
9665 }
9666
9667 /* Implement the "resources_needed" breakpoint_ops method for
9668    ranged breakpoints.  */
9669
9670 static int
9671 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9672 {
9673   return target_ranged_break_num_registers ();
9674 }
9675
9676 /* Implement the "print_it" breakpoint_ops method for
9677    ranged breakpoints.  */
9678
9679 static enum print_stop_action
9680 print_it_ranged_breakpoint (bpstat bs)
9681 {
9682   struct breakpoint *b = bs->breakpoint_at;
9683   struct bp_location *bl = b->loc;
9684   struct ui_out *uiout = current_uiout;
9685
9686   gdb_assert (b->type == bp_hardware_breakpoint);
9687
9688   /* Ranged breakpoints have only one location.  */
9689   gdb_assert (bl && bl->next == NULL);
9690
9691   annotate_breakpoint (b->number);
9692
9693   maybe_print_thread_hit_breakpoint (uiout);
9694
9695   if (b->disposition == disp_del)
9696     uiout->text ("Temporary ranged breakpoint ");
9697   else
9698     uiout->text ("Ranged breakpoint ");
9699   if (uiout->is_mi_like_p ())
9700     {
9701       uiout->field_string ("reason",
9702                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9703       uiout->field_string ("disp", bpdisp_text (b->disposition));
9704     }
9705   uiout->field_int ("bkptno", b->number);
9706   uiout->text (", ");
9707
9708   return PRINT_SRC_AND_LOC;
9709 }
9710
9711 /* Implement the "print_one" breakpoint_ops method for
9712    ranged breakpoints.  */
9713
9714 static void
9715 print_one_ranged_breakpoint (struct breakpoint *b,
9716                              struct bp_location **last_loc)
9717 {
9718   struct bp_location *bl = b->loc;
9719   struct value_print_options opts;
9720   struct ui_out *uiout = current_uiout;
9721
9722   /* Ranged breakpoints have only one location.  */
9723   gdb_assert (bl && bl->next == NULL);
9724
9725   get_user_print_options (&opts);
9726
9727   if (opts.addressprint)
9728     /* We don't print the address range here, it will be printed later
9729        by print_one_detail_ranged_breakpoint.  */
9730     uiout->field_skip ("addr");
9731   annotate_field (5);
9732   print_breakpoint_location (b, bl);
9733   *last_loc = bl;
9734 }
9735
9736 /* Implement the "print_one_detail" breakpoint_ops method for
9737    ranged breakpoints.  */
9738
9739 static void
9740 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9741                                     struct ui_out *uiout)
9742 {
9743   CORE_ADDR address_start, address_end;
9744   struct bp_location *bl = b->loc;
9745   string_file stb;
9746
9747   gdb_assert (bl);
9748
9749   address_start = bl->address;
9750   address_end = address_start + bl->length - 1;
9751
9752   uiout->text ("\taddress range: ");
9753   stb.printf ("[%s, %s]",
9754               print_core_address (bl->gdbarch, address_start),
9755               print_core_address (bl->gdbarch, address_end));
9756   uiout->field_stream ("addr", stb);
9757   uiout->text ("\n");
9758 }
9759
9760 /* Implement the "print_mention" breakpoint_ops method for
9761    ranged breakpoints.  */
9762
9763 static void
9764 print_mention_ranged_breakpoint (struct breakpoint *b)
9765 {
9766   struct bp_location *bl = b->loc;
9767   struct ui_out *uiout = current_uiout;
9768
9769   gdb_assert (bl);
9770   gdb_assert (b->type == bp_hardware_breakpoint);
9771
9772   uiout->message (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9773                   b->number, paddress (bl->gdbarch, bl->address),
9774                   paddress (bl->gdbarch, bl->address + bl->length - 1));
9775 }
9776
9777 /* Implement the "print_recreate" breakpoint_ops method for
9778    ranged breakpoints.  */
9779
9780 static void
9781 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9782 {
9783   fprintf_unfiltered (fp, "break-range %s, %s",
9784                       event_location_to_string (b->location.get ()),
9785                       event_location_to_string (b->location_range_end.get ()));
9786   print_recreate_thread (b, fp);
9787 }
9788
9789 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9790
9791 static struct breakpoint_ops ranged_breakpoint_ops;
9792
9793 /* Find the address where the end of the breakpoint range should be
9794    placed, given the SAL of the end of the range.  This is so that if
9795    the user provides a line number, the end of the range is set to the
9796    last instruction of the given line.  */
9797
9798 static CORE_ADDR
9799 find_breakpoint_range_end (struct symtab_and_line sal)
9800 {
9801   CORE_ADDR end;
9802
9803   /* If the user provided a PC value, use it.  Otherwise,
9804      find the address of the end of the given location.  */
9805   if (sal.explicit_pc)
9806     end = sal.pc;
9807   else
9808     {
9809       int ret;
9810       CORE_ADDR start;
9811
9812       ret = find_line_pc_range (sal, &start, &end);
9813       if (!ret)
9814         error (_("Could not find location of the end of the range."));
9815
9816       /* find_line_pc_range returns the start of the next line.  */
9817       end--;
9818     }
9819
9820   return end;
9821 }
9822
9823 /* Implement the "break-range" CLI command.  */
9824
9825 static void
9826 break_range_command (const char *arg, int from_tty)
9827 {
9828   const char *arg_start;
9829   struct linespec_result canonical_start, canonical_end;
9830   int bp_count, can_use_bp, length;
9831   CORE_ADDR end;
9832   struct breakpoint *b;
9833
9834   /* We don't support software ranged breakpoints.  */
9835   if (target_ranged_break_num_registers () < 0)
9836     error (_("This target does not support hardware ranged breakpoints."));
9837
9838   bp_count = hw_breakpoint_used_count ();
9839   bp_count += target_ranged_break_num_registers ();
9840   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9841                                                    bp_count, 0);
9842   if (can_use_bp < 0)
9843     error (_("Hardware breakpoints used exceeds limit."));
9844
9845   arg = skip_spaces (arg);
9846   if (arg == NULL || arg[0] == '\0')
9847     error(_("No address range specified."));
9848
9849   arg_start = arg;
9850   event_location_up start_location = string_to_event_location (&arg,
9851                                                                current_language);
9852   parse_breakpoint_sals (start_location.get (), &canonical_start);
9853
9854   if (arg[0] != ',')
9855     error (_("Too few arguments."));
9856   else if (canonical_start.lsals.empty ())
9857     error (_("Could not find location of the beginning of the range."));
9858
9859   const linespec_sals &lsal_start = canonical_start.lsals[0];
9860
9861   if (canonical_start.lsals.size () > 1
9862       || lsal_start.sals.size () != 1)
9863     error (_("Cannot create a ranged breakpoint with multiple locations."));
9864
9865   const symtab_and_line &sal_start = lsal_start.sals[0];
9866   std::string addr_string_start (arg_start, arg - arg_start);
9867
9868   arg++;        /* Skip the comma.  */
9869   arg = skip_spaces (arg);
9870
9871   /* Parse the end location.  */
9872
9873   arg_start = arg;
9874
9875   /* We call decode_line_full directly here instead of using
9876      parse_breakpoint_sals because we need to specify the start location's
9877      symtab and line as the default symtab and line for the end of the
9878      range.  This makes it possible to have ranges like "foo.c:27, +14",
9879      where +14 means 14 lines from the start location.  */
9880   event_location_up end_location = string_to_event_location (&arg,
9881                                                              current_language);
9882   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
9883                     sal_start.symtab, sal_start.line,
9884                     &canonical_end, NULL, NULL);
9885
9886   if (canonical_end.lsals.empty ())
9887     error (_("Could not find location of the end of the range."));
9888
9889   const linespec_sals &lsal_end = canonical_end.lsals[0];
9890   if (canonical_end.lsals.size () > 1
9891       || lsal_end.sals.size () != 1)
9892     error (_("Cannot create a ranged breakpoint with multiple locations."));
9893
9894   const symtab_and_line &sal_end = lsal_end.sals[0];
9895
9896   end = find_breakpoint_range_end (sal_end);
9897   if (sal_start.pc > end)
9898     error (_("Invalid address range, end precedes start."));
9899
9900   length = end - sal_start.pc + 1;
9901   if (length < 0)
9902     /* Length overflowed.  */
9903     error (_("Address range too large."));
9904   else if (length == 1)
9905     {
9906       /* This range is simple enough to be handled by
9907          the `hbreak' command.  */
9908       hbreak_command (&addr_string_start[0], 1);
9909
9910       return;
9911     }
9912
9913   /* Now set up the breakpoint.  */
9914   b = set_raw_breakpoint (get_current_arch (), sal_start,
9915                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
9916   set_breakpoint_count (breakpoint_count + 1);
9917   b->number = breakpoint_count;
9918   b->disposition = disp_donttouch;
9919   b->location = std::move (start_location);
9920   b->location_range_end = std::move (end_location);
9921   b->loc->length = length;
9922
9923   mention (b);
9924   gdb::observers::breakpoint_created.notify (b);
9925   update_global_location_list (UGLL_MAY_INSERT);
9926 }
9927
9928 /*  Return non-zero if EXP is verified as constant.  Returned zero
9929     means EXP is variable.  Also the constant detection may fail for
9930     some constant expressions and in such case still falsely return
9931     zero.  */
9932
9933 static int
9934 watchpoint_exp_is_const (const struct expression *exp)
9935 {
9936   int i = exp->nelts;
9937
9938   while (i > 0)
9939     {
9940       int oplenp, argsp;
9941
9942       /* We are only interested in the descriptor of each element.  */
9943       operator_length (exp, i, &oplenp, &argsp);
9944       i -= oplenp;
9945
9946       switch (exp->elts[i].opcode)
9947         {
9948         case BINOP_ADD:
9949         case BINOP_SUB:
9950         case BINOP_MUL:
9951         case BINOP_DIV:
9952         case BINOP_REM:
9953         case BINOP_MOD:
9954         case BINOP_LSH:
9955         case BINOP_RSH:
9956         case BINOP_LOGICAL_AND:
9957         case BINOP_LOGICAL_OR:
9958         case BINOP_BITWISE_AND:
9959         case BINOP_BITWISE_IOR:
9960         case BINOP_BITWISE_XOR:
9961         case BINOP_EQUAL:
9962         case BINOP_NOTEQUAL:
9963         case BINOP_LESS:
9964         case BINOP_GTR:
9965         case BINOP_LEQ:
9966         case BINOP_GEQ:
9967         case BINOP_REPEAT:
9968         case BINOP_COMMA:
9969         case BINOP_EXP:
9970         case BINOP_MIN:
9971         case BINOP_MAX:
9972         case BINOP_INTDIV:
9973         case BINOP_CONCAT:
9974         case TERNOP_COND:
9975         case TERNOP_SLICE:
9976
9977         case OP_LONG:
9978         case OP_FLOAT:
9979         case OP_LAST:
9980         case OP_COMPLEX:
9981         case OP_STRING:
9982         case OP_ARRAY:
9983         case OP_TYPE:
9984         case OP_TYPEOF:
9985         case OP_DECLTYPE:
9986         case OP_TYPEID:
9987         case OP_NAME:
9988         case OP_OBJC_NSSTRING:
9989
9990         case UNOP_NEG:
9991         case UNOP_LOGICAL_NOT:
9992         case UNOP_COMPLEMENT:
9993         case UNOP_ADDR:
9994         case UNOP_HIGH:
9995         case UNOP_CAST:
9996
9997         case UNOP_CAST_TYPE:
9998         case UNOP_REINTERPRET_CAST:
9999         case UNOP_DYNAMIC_CAST:
10000           /* Unary, binary and ternary operators: We have to check
10001              their operands.  If they are constant, then so is the
10002              result of that operation.  For instance, if A and B are
10003              determined to be constants, then so is "A + B".
10004
10005              UNOP_IND is one exception to the rule above, because the
10006              value of *ADDR is not necessarily a constant, even when
10007              ADDR is.  */
10008           break;
10009
10010         case OP_VAR_VALUE:
10011           /* Check whether the associated symbol is a constant.
10012
10013              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10014              possible that a buggy compiler could mark a variable as
10015              constant even when it is not, and TYPE_CONST would return
10016              true in this case, while SYMBOL_CLASS wouldn't.
10017
10018              We also have to check for function symbols because they
10019              are always constant.  */
10020           {
10021             struct symbol *s = exp->elts[i + 2].symbol;
10022
10023             if (SYMBOL_CLASS (s) != LOC_BLOCK
10024                 && SYMBOL_CLASS (s) != LOC_CONST
10025                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10026               return 0;
10027             break;
10028           }
10029
10030         /* The default action is to return 0 because we are using
10031            the optimistic approach here: If we don't know something,
10032            then it is not a constant.  */
10033         default:
10034           return 0;
10035         }
10036     }
10037
10038   return 1;
10039 }
10040
10041 /* Watchpoint destructor.  */
10042
10043 watchpoint::~watchpoint ()
10044 {
10045   xfree (this->exp_string);
10046   xfree (this->exp_string_reparse);
10047 }
10048
10049 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10050
10051 static void
10052 re_set_watchpoint (struct breakpoint *b)
10053 {
10054   struct watchpoint *w = (struct watchpoint *) b;
10055
10056   /* Watchpoint can be either on expression using entirely global
10057      variables, or it can be on local variables.
10058
10059      Watchpoints of the first kind are never auto-deleted, and even
10060      persist across program restarts.  Since they can use variables
10061      from shared libraries, we need to reparse expression as libraries
10062      are loaded and unloaded.
10063
10064      Watchpoints on local variables can also change meaning as result
10065      of solib event.  For example, if a watchpoint uses both a local
10066      and a global variables in expression, it's a local watchpoint,
10067      but unloading of a shared library will make the expression
10068      invalid.  This is not a very common use case, but we still
10069      re-evaluate expression, to avoid surprises to the user.
10070
10071      Note that for local watchpoints, we re-evaluate it only if
10072      watchpoints frame id is still valid.  If it's not, it means the
10073      watchpoint is out of scope and will be deleted soon.  In fact,
10074      I'm not sure we'll ever be called in this case.
10075
10076      If a local watchpoint's frame id is still valid, then
10077      w->exp_valid_block is likewise valid, and we can safely use it.
10078
10079      Don't do anything about disabled watchpoints, since they will be
10080      reevaluated again when enabled.  */
10081   update_watchpoint (w, 1 /* reparse */);
10082 }
10083
10084 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10085
10086 static int
10087 insert_watchpoint (struct bp_location *bl)
10088 {
10089   struct watchpoint *w = (struct watchpoint *) bl->owner;
10090   int length = w->exact ? 1 : bl->length;
10091
10092   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10093                                    w->cond_exp.get ());
10094 }
10095
10096 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10097
10098 static int
10099 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10100 {
10101   struct watchpoint *w = (struct watchpoint *) bl->owner;
10102   int length = w->exact ? 1 : bl->length;
10103
10104   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10105                                    w->cond_exp.get ());
10106 }
10107
10108 static int
10109 breakpoint_hit_watchpoint (const struct bp_location *bl,
10110                            const address_space *aspace, CORE_ADDR bp_addr,
10111                            const struct target_waitstatus *ws)
10112 {
10113   struct breakpoint *b = bl->owner;
10114   struct watchpoint *w = (struct watchpoint *) b;
10115
10116   /* Continuable hardware watchpoints are treated as non-existent if the
10117      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10118      some data address).  Otherwise gdb won't stop on a break instruction
10119      in the code (not from a breakpoint) when a hardware watchpoint has
10120      been defined.  Also skip watchpoints which we know did not trigger
10121      (did not match the data address).  */
10122   if (is_hardware_watchpoint (b)
10123       && w->watchpoint_triggered == watch_triggered_no)
10124     return 0;
10125
10126   return 1;
10127 }
10128
10129 static void
10130 check_status_watchpoint (bpstat bs)
10131 {
10132   gdb_assert (is_watchpoint (bs->breakpoint_at));
10133
10134   bpstat_check_watchpoint (bs);
10135 }
10136
10137 /* Implement the "resources_needed" breakpoint_ops method for
10138    hardware watchpoints.  */
10139
10140 static int
10141 resources_needed_watchpoint (const struct bp_location *bl)
10142 {
10143   struct watchpoint *w = (struct watchpoint *) bl->owner;
10144   int length = w->exact? 1 : bl->length;
10145
10146   return target_region_ok_for_hw_watchpoint (bl->address, length);
10147 }
10148
10149 /* Implement the "works_in_software_mode" breakpoint_ops method for
10150    hardware watchpoints.  */
10151
10152 static int
10153 works_in_software_mode_watchpoint (const struct breakpoint *b)
10154 {
10155   /* Read and access watchpoints only work with hardware support.  */
10156   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10157 }
10158
10159 static enum print_stop_action
10160 print_it_watchpoint (bpstat bs)
10161 {
10162   struct breakpoint *b;
10163   enum print_stop_action result;
10164   struct watchpoint *w;
10165   struct ui_out *uiout = current_uiout;
10166
10167   gdb_assert (bs->bp_location_at != NULL);
10168
10169   b = bs->breakpoint_at;
10170   w = (struct watchpoint *) b;
10171
10172   annotate_watchpoint (b->number);
10173   maybe_print_thread_hit_breakpoint (uiout);
10174
10175   string_file stb;
10176
10177   gdb::optional<ui_out_emit_tuple> tuple_emitter;
10178   switch (b->type)
10179     {
10180     case bp_watchpoint:
10181     case bp_hardware_watchpoint:
10182       if (uiout->is_mi_like_p ())
10183         uiout->field_string
10184           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10185       mention (b);
10186       tuple_emitter.emplace (uiout, "value");
10187       uiout->text ("\nOld value = ");
10188       watchpoint_value_print (bs->old_val.get (), &stb);
10189       uiout->field_stream ("old", stb);
10190       uiout->text ("\nNew value = ");
10191       watchpoint_value_print (w->val.get (), &stb);
10192       uiout->field_stream ("new", stb);
10193       uiout->text ("\n");
10194       /* More than one watchpoint may have been triggered.  */
10195       result = PRINT_UNKNOWN;
10196       break;
10197
10198     case bp_read_watchpoint:
10199       if (uiout->is_mi_like_p ())
10200         uiout->field_string
10201           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10202       mention (b);
10203       tuple_emitter.emplace (uiout, "value");
10204       uiout->text ("\nValue = ");
10205       watchpoint_value_print (w->val.get (), &stb);
10206       uiout->field_stream ("value", stb);
10207       uiout->text ("\n");
10208       result = PRINT_UNKNOWN;
10209       break;
10210
10211     case bp_access_watchpoint:
10212       if (bs->old_val != NULL)
10213         {
10214           if (uiout->is_mi_like_p ())
10215             uiout->field_string
10216               ("reason",
10217                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10218           mention (b);
10219           tuple_emitter.emplace (uiout, "value");
10220           uiout->text ("\nOld value = ");
10221           watchpoint_value_print (bs->old_val.get (), &stb);
10222           uiout->field_stream ("old", stb);
10223           uiout->text ("\nNew value = ");
10224         }
10225       else
10226         {
10227           mention (b);
10228           if (uiout->is_mi_like_p ())
10229             uiout->field_string
10230               ("reason",
10231                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10232           tuple_emitter.emplace (uiout, "value");
10233           uiout->text ("\nValue = ");
10234         }
10235       watchpoint_value_print (w->val.get (), &stb);
10236       uiout->field_stream ("new", stb);
10237       uiout->text ("\n");
10238       result = PRINT_UNKNOWN;
10239       break;
10240     default:
10241       result = PRINT_UNKNOWN;
10242     }
10243
10244   return result;
10245 }
10246
10247 /* Implement the "print_mention" breakpoint_ops method for hardware
10248    watchpoints.  */
10249
10250 static void
10251 print_mention_watchpoint (struct breakpoint *b)
10252 {
10253   struct watchpoint *w = (struct watchpoint *) b;
10254   struct ui_out *uiout = current_uiout;
10255   const char *tuple_name;
10256
10257   switch (b->type)
10258     {
10259     case bp_watchpoint:
10260       uiout->text ("Watchpoint ");
10261       tuple_name = "wpt";
10262       break;
10263     case bp_hardware_watchpoint:
10264       uiout->text ("Hardware watchpoint ");
10265       tuple_name = "wpt";
10266       break;
10267     case bp_read_watchpoint:
10268       uiout->text ("Hardware read watchpoint ");
10269       tuple_name = "hw-rwpt";
10270       break;
10271     case bp_access_watchpoint:
10272       uiout->text ("Hardware access (read/write) watchpoint ");
10273       tuple_name = "hw-awpt";
10274       break;
10275     default:
10276       internal_error (__FILE__, __LINE__,
10277                       _("Invalid hardware watchpoint type."));
10278     }
10279
10280   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10281   uiout->field_int ("number", b->number);
10282   uiout->text (": ");
10283   uiout->field_string ("exp", w->exp_string);
10284 }
10285
10286 /* Implement the "print_recreate" breakpoint_ops method for
10287    watchpoints.  */
10288
10289 static void
10290 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10291 {
10292   struct watchpoint *w = (struct watchpoint *) b;
10293
10294   switch (b->type)
10295     {
10296     case bp_watchpoint:
10297     case bp_hardware_watchpoint:
10298       fprintf_unfiltered (fp, "watch");
10299       break;
10300     case bp_read_watchpoint:
10301       fprintf_unfiltered (fp, "rwatch");
10302       break;
10303     case bp_access_watchpoint:
10304       fprintf_unfiltered (fp, "awatch");
10305       break;
10306     default:
10307       internal_error (__FILE__, __LINE__,
10308                       _("Invalid watchpoint type."));
10309     }
10310
10311   fprintf_unfiltered (fp, " %s", w->exp_string);
10312   print_recreate_thread (b, fp);
10313 }
10314
10315 /* Implement the "explains_signal" breakpoint_ops method for
10316    watchpoints.  */
10317
10318 static int
10319 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10320 {
10321   /* A software watchpoint cannot cause a signal other than
10322      GDB_SIGNAL_TRAP.  */
10323   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10324     return 0;
10325
10326   return 1;
10327 }
10328
10329 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10330
10331 static struct breakpoint_ops watchpoint_breakpoint_ops;
10332
10333 /* Implement the "insert" breakpoint_ops method for
10334    masked hardware watchpoints.  */
10335
10336 static int
10337 insert_masked_watchpoint (struct bp_location *bl)
10338 {
10339   struct watchpoint *w = (struct watchpoint *) bl->owner;
10340
10341   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10342                                         bl->watchpoint_type);
10343 }
10344
10345 /* Implement the "remove" breakpoint_ops method for
10346    masked hardware watchpoints.  */
10347
10348 static int
10349 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10350 {
10351   struct watchpoint *w = (struct watchpoint *) bl->owner;
10352
10353   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10354                                         bl->watchpoint_type);
10355 }
10356
10357 /* Implement the "resources_needed" breakpoint_ops method for
10358    masked hardware watchpoints.  */
10359
10360 static int
10361 resources_needed_masked_watchpoint (const struct bp_location *bl)
10362 {
10363   struct watchpoint *w = (struct watchpoint *) bl->owner;
10364
10365   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10366 }
10367
10368 /* Implement the "works_in_software_mode" breakpoint_ops method for
10369    masked hardware watchpoints.  */
10370
10371 static int
10372 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10373 {
10374   return 0;
10375 }
10376
10377 /* Implement the "print_it" breakpoint_ops method for
10378    masked hardware watchpoints.  */
10379
10380 static enum print_stop_action
10381 print_it_masked_watchpoint (bpstat bs)
10382 {
10383   struct breakpoint *b = bs->breakpoint_at;
10384   struct ui_out *uiout = current_uiout;
10385
10386   /* Masked watchpoints have only one location.  */
10387   gdb_assert (b->loc && b->loc->next == NULL);
10388
10389   annotate_watchpoint (b->number);
10390   maybe_print_thread_hit_breakpoint (uiout);
10391
10392   switch (b->type)
10393     {
10394     case bp_hardware_watchpoint:
10395       if (uiout->is_mi_like_p ())
10396         uiout->field_string
10397           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10398       break;
10399
10400     case bp_read_watchpoint:
10401       if (uiout->is_mi_like_p ())
10402         uiout->field_string
10403           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10404       break;
10405
10406     case bp_access_watchpoint:
10407       if (uiout->is_mi_like_p ())
10408         uiout->field_string
10409           ("reason",
10410            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10411       break;
10412     default:
10413       internal_error (__FILE__, __LINE__,
10414                       _("Invalid hardware watchpoint type."));
10415     }
10416
10417   mention (b);
10418   uiout->text (_("\n\
10419 Check the underlying instruction at PC for the memory\n\
10420 address and value which triggered this watchpoint.\n"));
10421   uiout->text ("\n");
10422
10423   /* More than one watchpoint may have been triggered.  */
10424   return PRINT_UNKNOWN;
10425 }
10426
10427 /* Implement the "print_one_detail" breakpoint_ops method for
10428    masked hardware watchpoints.  */
10429
10430 static void
10431 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10432                                     struct ui_out *uiout)
10433 {
10434   struct watchpoint *w = (struct watchpoint *) b;
10435
10436   /* Masked watchpoints have only one location.  */
10437   gdb_assert (b->loc && b->loc->next == NULL);
10438
10439   uiout->text ("\tmask ");
10440   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10441   uiout->text ("\n");
10442 }
10443
10444 /* Implement the "print_mention" breakpoint_ops method for
10445    masked hardware watchpoints.  */
10446
10447 static void
10448 print_mention_masked_watchpoint (struct breakpoint *b)
10449 {
10450   struct watchpoint *w = (struct watchpoint *) b;
10451   struct ui_out *uiout = current_uiout;
10452   const char *tuple_name;
10453
10454   switch (b->type)
10455     {
10456     case bp_hardware_watchpoint:
10457       uiout->text ("Masked hardware watchpoint ");
10458       tuple_name = "wpt";
10459       break;
10460     case bp_read_watchpoint:
10461       uiout->text ("Masked hardware read watchpoint ");
10462       tuple_name = "hw-rwpt";
10463       break;
10464     case bp_access_watchpoint:
10465       uiout->text ("Masked hardware access (read/write) watchpoint ");
10466       tuple_name = "hw-awpt";
10467       break;
10468     default:
10469       internal_error (__FILE__, __LINE__,
10470                       _("Invalid hardware watchpoint type."));
10471     }
10472
10473   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10474   uiout->field_int ("number", b->number);
10475   uiout->text (": ");
10476   uiout->field_string ("exp", w->exp_string);
10477 }
10478
10479 /* Implement the "print_recreate" breakpoint_ops method for
10480    masked hardware watchpoints.  */
10481
10482 static void
10483 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10484 {
10485   struct watchpoint *w = (struct watchpoint *) b;
10486   char tmp[40];
10487
10488   switch (b->type)
10489     {
10490     case bp_hardware_watchpoint:
10491       fprintf_unfiltered (fp, "watch");
10492       break;
10493     case bp_read_watchpoint:
10494       fprintf_unfiltered (fp, "rwatch");
10495       break;
10496     case bp_access_watchpoint:
10497       fprintf_unfiltered (fp, "awatch");
10498       break;
10499     default:
10500       internal_error (__FILE__, __LINE__,
10501                       _("Invalid hardware watchpoint type."));
10502     }
10503
10504   sprintf_vma (tmp, w->hw_wp_mask);
10505   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10506   print_recreate_thread (b, fp);
10507 }
10508
10509 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10510
10511 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10512
10513 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10514
10515 static int
10516 is_masked_watchpoint (const struct breakpoint *b)
10517 {
10518   return b->ops == &masked_watchpoint_breakpoint_ops;
10519 }
10520
10521 /* accessflag:  hw_write:  watch write, 
10522                 hw_read:   watch read, 
10523                 hw_access: watch access (read or write) */
10524 static void
10525 watch_command_1 (const char *arg, int accessflag, int from_tty,
10526                  int just_location, int internal)
10527 {
10528   struct breakpoint *scope_breakpoint = NULL;
10529   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10530   struct value *mark, *result;
10531   int saved_bitpos = 0, saved_bitsize = 0;
10532   const char *exp_start = NULL;
10533   const char *exp_end = NULL;
10534   const char *tok, *end_tok;
10535   int toklen = -1;
10536   const char *cond_start = NULL;
10537   const char *cond_end = NULL;
10538   enum bptype bp_type;
10539   int thread = -1;
10540   int pc = 0;
10541   /* Flag to indicate whether we are going to use masks for
10542      the hardware watchpoint.  */
10543   int use_mask = 0;
10544   CORE_ADDR mask = 0;
10545
10546   /* Make sure that we actually have parameters to parse.  */
10547   if (arg != NULL && arg[0] != '\0')
10548     {
10549       const char *value_start;
10550
10551       exp_end = arg + strlen (arg);
10552
10553       /* Look for "parameter value" pairs at the end
10554          of the arguments string.  */
10555       for (tok = exp_end - 1; tok > arg; tok--)
10556         {
10557           /* Skip whitespace at the end of the argument list.  */
10558           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10559             tok--;
10560
10561           /* Find the beginning of the last token.
10562              This is the value of the parameter.  */
10563           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10564             tok--;
10565           value_start = tok + 1;
10566
10567           /* Skip whitespace.  */
10568           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10569             tok--;
10570
10571           end_tok = tok;
10572
10573           /* Find the beginning of the second to last token.
10574              This is the parameter itself.  */
10575           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10576             tok--;
10577           tok++;
10578           toklen = end_tok - tok + 1;
10579
10580           if (toklen == 6 && startswith (tok, "thread"))
10581             {
10582               struct thread_info *thr;
10583               /* At this point we've found a "thread" token, which means
10584                  the user is trying to set a watchpoint that triggers
10585                  only in a specific thread.  */
10586               const char *endp;
10587
10588               if (thread != -1)
10589                 error(_("You can specify only one thread."));
10590
10591               /* Extract the thread ID from the next token.  */
10592               thr = parse_thread_id (value_start, &endp);
10593
10594               /* Check if the user provided a valid thread ID.  */
10595               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10596                 invalid_thread_id_error (value_start);
10597
10598               thread = thr->global_num;
10599             }
10600           else if (toklen == 4 && startswith (tok, "mask"))
10601             {
10602               /* We've found a "mask" token, which means the user wants to
10603                  create a hardware watchpoint that is going to have the mask
10604                  facility.  */
10605               struct value *mask_value, *mark;
10606
10607               if (use_mask)
10608                 error(_("You can specify only one mask."));
10609
10610               use_mask = just_location = 1;
10611
10612               mark = value_mark ();
10613               mask_value = parse_to_comma_and_eval (&value_start);
10614               mask = value_as_address (mask_value);
10615               value_free_to_mark (mark);
10616             }
10617           else
10618             /* We didn't recognize what we found.  We should stop here.  */
10619             break;
10620
10621           /* Truncate the string and get rid of the "parameter value" pair before
10622              the arguments string is parsed by the parse_exp_1 function.  */
10623           exp_end = tok;
10624         }
10625     }
10626   else
10627     exp_end = arg;
10628
10629   /* Parse the rest of the arguments.  From here on out, everything
10630      is in terms of a newly allocated string instead of the original
10631      ARG.  */
10632   innermost_block.reset ();
10633   std::string expression (arg, exp_end - arg);
10634   exp_start = arg = expression.c_str ();
10635   expression_up exp = parse_exp_1 (&arg, 0, 0, 0);
10636   exp_end = arg;
10637   /* Remove trailing whitespace from the expression before saving it.
10638      This makes the eventual display of the expression string a bit
10639      prettier.  */
10640   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10641     --exp_end;
10642
10643   /* Checking if the expression is not constant.  */
10644   if (watchpoint_exp_is_const (exp.get ()))
10645     {
10646       int len;
10647
10648       len = exp_end - exp_start;
10649       while (len > 0 && isspace (exp_start[len - 1]))
10650         len--;
10651       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10652     }
10653
10654   exp_valid_block = innermost_block.block ();
10655   mark = value_mark ();
10656   struct value *val_as_value = nullptr;
10657   fetch_subexp_value (exp.get (), &pc, &val_as_value, &result, NULL,
10658                       just_location);
10659
10660   if (val_as_value != NULL && just_location)
10661     {
10662       saved_bitpos = value_bitpos (val_as_value);
10663       saved_bitsize = value_bitsize (val_as_value);
10664     }
10665
10666   value_ref_ptr val;
10667   if (just_location)
10668     {
10669       int ret;
10670
10671       exp_valid_block = NULL;
10672       val = release_value (value_addr (result));
10673       value_free_to_mark (mark);
10674
10675       if (use_mask)
10676         {
10677           ret = target_masked_watch_num_registers (value_as_address (val.get ()),
10678                                                    mask);
10679           if (ret == -1)
10680             error (_("This target does not support masked watchpoints."));
10681           else if (ret == -2)
10682             error (_("Invalid mask or memory region."));
10683         }
10684     }
10685   else if (val_as_value != NULL)
10686     val = release_value (val_as_value);
10687
10688   tok = skip_spaces (arg);
10689   end_tok = skip_to_space (tok);
10690
10691   toklen = end_tok - tok;
10692   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10693     {
10694       innermost_block.reset ();
10695       tok = cond_start = end_tok + 1;
10696       parse_exp_1 (&tok, 0, 0, 0);
10697
10698       /* The watchpoint expression may not be local, but the condition
10699          may still be.  E.g.: `watch global if local > 0'.  */
10700       cond_exp_valid_block = innermost_block.block ();
10701
10702       cond_end = tok;
10703     }
10704   if (*tok)
10705     error (_("Junk at end of command."));
10706
10707   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
10708
10709   /* Save this because create_internal_breakpoint below invalidates
10710      'wp_frame'.  */
10711   frame_id watchpoint_frame = get_frame_id (wp_frame);
10712
10713   /* If the expression is "local", then set up a "watchpoint scope"
10714      breakpoint at the point where we've left the scope of the watchpoint
10715      expression.  Create the scope breakpoint before the watchpoint, so
10716      that we will encounter it first in bpstat_stop_status.  */
10717   if (exp_valid_block != NULL && wp_frame != NULL)
10718     {
10719       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10720
10721       if (frame_id_p (caller_frame_id))
10722         {
10723           gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10724           CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10725
10726           scope_breakpoint
10727             = create_internal_breakpoint (caller_arch, caller_pc,
10728                                           bp_watchpoint_scope,
10729                                           &momentary_breakpoint_ops);
10730
10731           /* create_internal_breakpoint could invalidate WP_FRAME.  */
10732           wp_frame = NULL;
10733
10734           scope_breakpoint->enable_state = bp_enabled;
10735
10736           /* Automatically delete the breakpoint when it hits.  */
10737           scope_breakpoint->disposition = disp_del;
10738
10739           /* Only break in the proper frame (help with recursion).  */
10740           scope_breakpoint->frame_id = caller_frame_id;
10741
10742           /* Set the address at which we will stop.  */
10743           scope_breakpoint->loc->gdbarch = caller_arch;
10744           scope_breakpoint->loc->requested_address = caller_pc;
10745           scope_breakpoint->loc->address
10746             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10747                                          scope_breakpoint->loc->requested_address,
10748                                          scope_breakpoint->type);
10749         }
10750     }
10751
10752   /* Now set up the breakpoint.  We create all watchpoints as hardware
10753      watchpoints here even if hardware watchpoints are turned off, a call
10754      to update_watchpoint later in this function will cause the type to
10755      drop back to bp_watchpoint (software watchpoint) if required.  */
10756
10757   if (accessflag == hw_read)
10758     bp_type = bp_read_watchpoint;
10759   else if (accessflag == hw_access)
10760     bp_type = bp_access_watchpoint;
10761   else
10762     bp_type = bp_hardware_watchpoint;
10763
10764   std::unique_ptr<watchpoint> w (new watchpoint ());
10765
10766   if (use_mask)
10767     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10768                                           &masked_watchpoint_breakpoint_ops);
10769   else
10770     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10771                                           &watchpoint_breakpoint_ops);
10772   w->thread = thread;
10773   w->disposition = disp_donttouch;
10774   w->pspace = current_program_space;
10775   w->exp = std::move (exp);
10776   w->exp_valid_block = exp_valid_block;
10777   w->cond_exp_valid_block = cond_exp_valid_block;
10778   if (just_location)
10779     {
10780       struct type *t = value_type (val.get ());
10781       CORE_ADDR addr = value_as_address (val.get ());
10782
10783       w->exp_string_reparse
10784         = current_language->la_watch_location_expression (t, addr).release ();
10785
10786       w->exp_string = xstrprintf ("-location %.*s",
10787                                   (int) (exp_end - exp_start), exp_start);
10788     }
10789   else
10790     w->exp_string = savestring (exp_start, exp_end - exp_start);
10791
10792   if (use_mask)
10793     {
10794       w->hw_wp_mask = mask;
10795     }
10796   else
10797     {
10798       w->val = val;
10799       w->val_bitpos = saved_bitpos;
10800       w->val_bitsize = saved_bitsize;
10801       w->val_valid = 1;
10802     }
10803
10804   if (cond_start)
10805     w->cond_string = savestring (cond_start, cond_end - cond_start);
10806   else
10807     w->cond_string = 0;
10808
10809   if (frame_id_p (watchpoint_frame))
10810     {
10811       w->watchpoint_frame = watchpoint_frame;
10812       w->watchpoint_thread = inferior_ptid;
10813     }
10814   else
10815     {
10816       w->watchpoint_frame = null_frame_id;
10817       w->watchpoint_thread = null_ptid;
10818     }
10819
10820   if (scope_breakpoint != NULL)
10821     {
10822       /* The scope breakpoint is related to the watchpoint.  We will
10823          need to act on them together.  */
10824       w->related_breakpoint = scope_breakpoint;
10825       scope_breakpoint->related_breakpoint = w.get ();
10826     }
10827
10828   if (!just_location)
10829     value_free_to_mark (mark);
10830
10831   /* Finally update the new watchpoint.  This creates the locations
10832      that should be inserted.  */
10833   update_watchpoint (w.get (), 1);
10834
10835   install_breakpoint (internal, std::move (w), 1);
10836 }
10837
10838 /* Return count of debug registers needed to watch the given expression.
10839    If the watchpoint cannot be handled in hardware return zero.  */
10840
10841 static int
10842 can_use_hardware_watchpoint (const std::vector<value_ref_ptr> &vals)
10843 {
10844   int found_memory_cnt = 0;
10845
10846   /* Did the user specifically forbid us to use hardware watchpoints? */
10847   if (!can_use_hw_watchpoints)
10848     return 0;
10849
10850   gdb_assert (!vals.empty ());
10851   struct value *head = vals[0].get ();
10852
10853   /* Make sure that the value of the expression depends only upon
10854      memory contents, and values computed from them within GDB.  If we
10855      find any register references or function calls, we can't use a
10856      hardware watchpoint.
10857
10858      The idea here is that evaluating an expression generates a series
10859      of values, one holding the value of every subexpression.  (The
10860      expression a*b+c has five subexpressions: a, b, a*b, c, and
10861      a*b+c.)  GDB's values hold almost enough information to establish
10862      the criteria given above --- they identify memory lvalues,
10863      register lvalues, computed values, etcetera.  So we can evaluate
10864      the expression, and then scan the chain of values that leaves
10865      behind to decide whether we can detect any possible change to the
10866      expression's final value using only hardware watchpoints.
10867
10868      However, I don't think that the values returned by inferior
10869      function calls are special in any way.  So this function may not
10870      notice that an expression involving an inferior function call
10871      can't be watched with hardware watchpoints.  FIXME.  */
10872   for (const value_ref_ptr &iter : vals)
10873     {
10874       struct value *v = iter.get ();
10875
10876       if (VALUE_LVAL (v) == lval_memory)
10877         {
10878           if (v != head && value_lazy (v))
10879             /* A lazy memory lvalue in the chain is one that GDB never
10880                needed to fetch; we either just used its address (e.g.,
10881                `a' in `a.b') or we never needed it at all (e.g., `a'
10882                in `a,b').  This doesn't apply to HEAD; if that is
10883                lazy then it was not readable, but watch it anyway.  */
10884             ;
10885           else
10886             {
10887               /* Ahh, memory we actually used!  Check if we can cover
10888                  it with hardware watchpoints.  */
10889               struct type *vtype = check_typedef (value_type (v));
10890
10891               /* We only watch structs and arrays if user asked for it
10892                  explicitly, never if they just happen to appear in a
10893                  middle of some value chain.  */
10894               if (v == head
10895                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
10896                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
10897                 {
10898                   CORE_ADDR vaddr = value_address (v);
10899                   int len;
10900                   int num_regs;
10901
10902                   len = (target_exact_watchpoints
10903                          && is_scalar_type_recursive (vtype))?
10904                     1 : TYPE_LENGTH (value_type (v));
10905
10906                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10907                   if (!num_regs)
10908                     return 0;
10909                   else
10910                     found_memory_cnt += num_regs;
10911                 }
10912             }
10913         }
10914       else if (VALUE_LVAL (v) != not_lval
10915                && deprecated_value_modifiable (v) == 0)
10916         return 0;       /* These are values from the history (e.g., $1).  */
10917       else if (VALUE_LVAL (v) == lval_register)
10918         return 0;       /* Cannot watch a register with a HW watchpoint.  */
10919     }
10920
10921   /* The expression itself looks suitable for using a hardware
10922      watchpoint, but give the target machine a chance to reject it.  */
10923   return found_memory_cnt;
10924 }
10925
10926 void
10927 watch_command_wrapper (const char *arg, int from_tty, int internal)
10928 {
10929   watch_command_1 (arg, hw_write, from_tty, 0, internal);
10930 }
10931
10932 /* A helper function that looks for the "-location" argument and then
10933    calls watch_command_1.  */
10934
10935 static void
10936 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
10937 {
10938   int just_location = 0;
10939
10940   if (arg
10941       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
10942           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
10943     {
10944       arg = skip_spaces (arg);
10945       just_location = 1;
10946     }
10947
10948   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
10949 }
10950
10951 static void
10952 watch_command (const char *arg, int from_tty)
10953 {
10954   watch_maybe_just_location (arg, hw_write, from_tty);
10955 }
10956
10957 void
10958 rwatch_command_wrapper (const char *arg, int from_tty, int internal)
10959 {
10960   watch_command_1 (arg, hw_read, from_tty, 0, internal);
10961 }
10962
10963 static void
10964 rwatch_command (const char *arg, int from_tty)
10965 {
10966   watch_maybe_just_location (arg, hw_read, from_tty);
10967 }
10968
10969 void
10970 awatch_command_wrapper (const char *arg, int from_tty, int internal)
10971 {
10972   watch_command_1 (arg, hw_access, from_tty, 0, internal);
10973 }
10974
10975 static void
10976 awatch_command (const char *arg, int from_tty)
10977 {
10978   watch_maybe_just_location (arg, hw_access, from_tty);
10979 }
10980 \f
10981
10982 /* Data for the FSM that manages the until(location)/advance commands
10983    in infcmd.c.  Here because it uses the mechanisms of
10984    breakpoints.  */
10985
10986 struct until_break_fsm
10987 {
10988   /* The base class.  */
10989   struct thread_fsm thread_fsm;
10990
10991   /* The thread that as current when the command was executed.  */
10992   int thread;
10993
10994   /* The breakpoint set at the destination location.  */
10995   struct breakpoint *location_breakpoint;
10996
10997   /* Breakpoint set at the return address in the caller frame.  May be
10998      NULL.  */
10999   struct breakpoint *caller_breakpoint;
11000 };
11001
11002 static void until_break_fsm_clean_up (struct thread_fsm *self,
11003                                       struct thread_info *thread);
11004 static int until_break_fsm_should_stop (struct thread_fsm *self,
11005                                         struct thread_info *thread);
11006 static enum async_reply_reason
11007   until_break_fsm_async_reply_reason (struct thread_fsm *self);
11008
11009 /* until_break_fsm's vtable.  */
11010
11011 static struct thread_fsm_ops until_break_fsm_ops =
11012 {
11013   NULL, /* dtor */
11014   until_break_fsm_clean_up,
11015   until_break_fsm_should_stop,
11016   NULL, /* return_value */
11017   until_break_fsm_async_reply_reason,
11018 };
11019
11020 /* Allocate a new until_break_command_fsm.  */
11021
11022 static struct until_break_fsm *
11023 new_until_break_fsm (struct interp *cmd_interp, int thread,
11024                      breakpoint_up &&location_breakpoint,
11025                      breakpoint_up &&caller_breakpoint)
11026 {
11027   struct until_break_fsm *sm;
11028
11029   sm = XCNEW (struct until_break_fsm);
11030   thread_fsm_ctor (&sm->thread_fsm, &until_break_fsm_ops, cmd_interp);
11031
11032   sm->thread = thread;
11033   sm->location_breakpoint = location_breakpoint.release ();
11034   sm->caller_breakpoint = caller_breakpoint.release ();
11035
11036   return sm;
11037 }
11038
11039 /* Implementation of the 'should_stop' FSM method for the
11040    until(location)/advance commands.  */
11041
11042 static int
11043 until_break_fsm_should_stop (struct thread_fsm *self,
11044                              struct thread_info *tp)
11045 {
11046   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11047
11048   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11049                               sm->location_breakpoint) != NULL
11050       || (sm->caller_breakpoint != NULL
11051           && bpstat_find_breakpoint (tp->control.stop_bpstat,
11052                                      sm->caller_breakpoint) != NULL))
11053     thread_fsm_set_finished (self);
11054
11055   return 1;
11056 }
11057
11058 /* Implementation of the 'clean_up' FSM method for the
11059    until(location)/advance commands.  */
11060
11061 static void
11062 until_break_fsm_clean_up (struct thread_fsm *self,
11063                           struct thread_info *thread)
11064 {
11065   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11066
11067   /* Clean up our temporary breakpoints.  */
11068   if (sm->location_breakpoint != NULL)
11069     {
11070       delete_breakpoint (sm->location_breakpoint);
11071       sm->location_breakpoint = NULL;
11072     }
11073   if (sm->caller_breakpoint != NULL)
11074     {
11075       delete_breakpoint (sm->caller_breakpoint);
11076       sm->caller_breakpoint = NULL;
11077     }
11078   delete_longjmp_breakpoint (sm->thread);
11079 }
11080
11081 /* Implementation of the 'async_reply_reason' FSM method for the
11082    until(location)/advance commands.  */
11083
11084 static enum async_reply_reason
11085 until_break_fsm_async_reply_reason (struct thread_fsm *self)
11086 {
11087   return EXEC_ASYNC_LOCATION_REACHED;
11088 }
11089
11090 void
11091 until_break_command (const char *arg, int from_tty, int anywhere)
11092 {
11093   struct frame_info *frame;
11094   struct gdbarch *frame_gdbarch;
11095   struct frame_id stack_frame_id;
11096   struct frame_id caller_frame_id;
11097   struct cleanup *old_chain;
11098   int thread;
11099   struct thread_info *tp;
11100   struct until_break_fsm *sm;
11101
11102   clear_proceed_status (0);
11103
11104   /* Set a breakpoint where the user wants it and at return from
11105      this function.  */
11106
11107   event_location_up location = string_to_event_location (&arg, current_language);
11108
11109   std::vector<symtab_and_line> sals
11110     = (last_displayed_sal_is_valid ()
11111        ? decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
11112                         get_last_displayed_symtab (),
11113                         get_last_displayed_line ())
11114        : decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
11115                         NULL, (struct symtab *) NULL, 0));
11116
11117   if (sals.size () != 1)
11118     error (_("Couldn't get information on specified line."));
11119
11120   symtab_and_line &sal = sals[0];
11121
11122   if (*arg)
11123     error (_("Junk at end of arguments."));
11124
11125   resolve_sal_pc (&sal);
11126
11127   tp = inferior_thread ();
11128   thread = tp->global_num;
11129
11130   old_chain = make_cleanup (null_cleanup, NULL);
11131
11132   /* Note linespec handling above invalidates the frame chain.
11133      Installing a breakpoint also invalidates the frame chain (as it
11134      may need to switch threads), so do any frame handling before
11135      that.  */
11136
11137   frame = get_selected_frame (NULL);
11138   frame_gdbarch = get_frame_arch (frame);
11139   stack_frame_id = get_stack_frame_id (frame);
11140   caller_frame_id = frame_unwind_caller_id (frame);
11141
11142   /* Keep within the current frame, or in frames called by the current
11143      one.  */
11144
11145   breakpoint_up caller_breakpoint;
11146   if (frame_id_p (caller_frame_id))
11147     {
11148       struct symtab_and_line sal2;
11149       struct gdbarch *caller_gdbarch;
11150
11151       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11152       sal2.pc = frame_unwind_caller_pc (frame);
11153       caller_gdbarch = frame_unwind_caller_arch (frame);
11154       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11155                                                     sal2,
11156                                                     caller_frame_id,
11157                                                     bp_until);
11158
11159       set_longjmp_breakpoint (tp, caller_frame_id);
11160       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11161     }
11162
11163   /* set_momentary_breakpoint could invalidate FRAME.  */
11164   frame = NULL;
11165
11166   breakpoint_up location_breakpoint;
11167   if (anywhere)
11168     /* If the user told us to continue until a specified location,
11169        we don't specify a frame at which we need to stop.  */
11170     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11171                                                     null_frame_id, bp_until);
11172   else
11173     /* Otherwise, specify the selected frame, because we want to stop
11174        only at the very same frame.  */
11175     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11176                                                     stack_frame_id, bp_until);
11177
11178   sm = new_until_break_fsm (command_interp (), tp->global_num,
11179                             std::move (location_breakpoint),
11180                             std::move (caller_breakpoint));
11181   tp->thread_fsm = &sm->thread_fsm;
11182
11183   discard_cleanups (old_chain);
11184
11185   proceed (-1, GDB_SIGNAL_DEFAULT);
11186 }
11187
11188 /* This function attempts to parse an optional "if <cond>" clause
11189    from the arg string.  If one is not found, it returns NULL.
11190
11191    Else, it returns a pointer to the condition string.  (It does not
11192    attempt to evaluate the string against a particular block.)  And,
11193    it updates arg to point to the first character following the parsed
11194    if clause in the arg string.  */
11195
11196 const char *
11197 ep_parse_optional_if_clause (const char **arg)
11198 {
11199   const char *cond_string;
11200
11201   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11202     return NULL;
11203
11204   /* Skip the "if" keyword.  */
11205   (*arg) += 2;
11206
11207   /* Skip any extra leading whitespace, and record the start of the
11208      condition string.  */
11209   *arg = skip_spaces (*arg);
11210   cond_string = *arg;
11211
11212   /* Assume that the condition occupies the remainder of the arg
11213      string.  */
11214   (*arg) += strlen (cond_string);
11215
11216   return cond_string;
11217 }
11218
11219 /* Commands to deal with catching events, such as signals, exceptions,
11220    process start/exit, etc.  */
11221
11222 typedef enum
11223 {
11224   catch_fork_temporary, catch_vfork_temporary,
11225   catch_fork_permanent, catch_vfork_permanent
11226 }
11227 catch_fork_kind;
11228
11229 static void
11230 catch_fork_command_1 (const char *arg, int from_tty,
11231                       struct cmd_list_element *command)
11232 {
11233   struct gdbarch *gdbarch = get_current_arch ();
11234   const char *cond_string = NULL;
11235   catch_fork_kind fork_kind;
11236   int tempflag;
11237
11238   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11239   tempflag = (fork_kind == catch_fork_temporary
11240               || fork_kind == catch_vfork_temporary);
11241
11242   if (!arg)
11243     arg = "";
11244   arg = skip_spaces (arg);
11245
11246   /* The allowed syntax is:
11247      catch [v]fork
11248      catch [v]fork if <cond>
11249
11250      First, check if there's an if clause.  */
11251   cond_string = ep_parse_optional_if_clause (&arg);
11252
11253   if ((*arg != '\0') && !isspace (*arg))
11254     error (_("Junk at end of arguments."));
11255
11256   /* If this target supports it, create a fork or vfork catchpoint
11257      and enable reporting of such events.  */
11258   switch (fork_kind)
11259     {
11260     case catch_fork_temporary:
11261     case catch_fork_permanent:
11262       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11263                                           &catch_fork_breakpoint_ops);
11264       break;
11265     case catch_vfork_temporary:
11266     case catch_vfork_permanent:
11267       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11268                                           &catch_vfork_breakpoint_ops);
11269       break;
11270     default:
11271       error (_("unsupported or unknown fork kind; cannot catch it"));
11272       break;
11273     }
11274 }
11275
11276 static void
11277 catch_exec_command_1 (const char *arg, int from_tty,
11278                       struct cmd_list_element *command)
11279 {
11280   struct gdbarch *gdbarch = get_current_arch ();
11281   int tempflag;
11282   const char *cond_string = NULL;
11283
11284   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11285
11286   if (!arg)
11287     arg = "";
11288   arg = skip_spaces (arg);
11289
11290   /* The allowed syntax is:
11291      catch exec
11292      catch exec if <cond>
11293
11294      First, check if there's an if clause.  */
11295   cond_string = ep_parse_optional_if_clause (&arg);
11296
11297   if ((*arg != '\0') && !isspace (*arg))
11298     error (_("Junk at end of arguments."));
11299
11300   std::unique_ptr<exec_catchpoint> c (new exec_catchpoint ());
11301   init_catchpoint (c.get (), gdbarch, tempflag, cond_string,
11302                    &catch_exec_breakpoint_ops);
11303   c->exec_pathname = NULL;
11304
11305   install_breakpoint (0, std::move (c), 1);
11306 }
11307
11308 void
11309 init_ada_exception_breakpoint (struct breakpoint *b,
11310                                struct gdbarch *gdbarch,
11311                                struct symtab_and_line sal,
11312                                const char *addr_string,
11313                                const struct breakpoint_ops *ops,
11314                                int tempflag,
11315                                int enabled,
11316                                int from_tty)
11317 {
11318   if (from_tty)
11319     {
11320       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11321       if (!loc_gdbarch)
11322         loc_gdbarch = gdbarch;
11323
11324       describe_other_breakpoints (loc_gdbarch,
11325                                   sal.pspace, sal.pc, sal.section, -1);
11326       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11327          version for exception catchpoints, because two catchpoints
11328          used for different exception names will use the same address.
11329          In this case, a "breakpoint ... also set at..." warning is
11330          unproductive.  Besides, the warning phrasing is also a bit
11331          inappropriate, we should use the word catchpoint, and tell
11332          the user what type of catchpoint it is.  The above is good
11333          enough for now, though.  */
11334     }
11335
11336   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11337
11338   b->enable_state = enabled ? bp_enabled : bp_disabled;
11339   b->disposition = tempflag ? disp_del : disp_donttouch;
11340   b->location = string_to_event_location (&addr_string,
11341                                           language_def (language_ada));
11342   b->language = language_ada;
11343 }
11344
11345 static void
11346 catch_command (const char *arg, int from_tty)
11347 {
11348   error (_("Catch requires an event name."));
11349 }
11350 \f
11351
11352 static void
11353 tcatch_command (const char *arg, int from_tty)
11354 {
11355   error (_("Catch requires an event name."));
11356 }
11357
11358 /* Compare two breakpoints and return a strcmp-like result.  */
11359
11360 static int
11361 compare_breakpoints (const breakpoint *a, const breakpoint *b)
11362 {
11363   uintptr_t ua = (uintptr_t) a;
11364   uintptr_t ub = (uintptr_t) b;
11365
11366   if (a->number < b->number)
11367     return -1;
11368   else if (a->number > b->number)
11369     return 1;
11370
11371   /* Now sort by address, in case we see, e..g, two breakpoints with
11372      the number 0.  */
11373   if (ua < ub)
11374     return -1;
11375   return ua > ub ? 1 : 0;
11376 }
11377
11378 /* Delete breakpoints by address or line.  */
11379
11380 static void
11381 clear_command (const char *arg, int from_tty)
11382 {
11383   struct breakpoint *b;
11384   int default_match;
11385
11386   std::vector<symtab_and_line> decoded_sals;
11387   symtab_and_line last_sal;
11388   gdb::array_view<symtab_and_line> sals;
11389   if (arg)
11390     {
11391       decoded_sals
11392         = decode_line_with_current_source (arg,
11393                                            (DECODE_LINE_FUNFIRSTLINE
11394                                             | DECODE_LINE_LIST_MODE));
11395       default_match = 0;
11396       sals = decoded_sals;
11397     }
11398   else
11399     {
11400       /* Set sal's line, symtab, pc, and pspace to the values
11401          corresponding to the last call to print_frame_info.  If the
11402          codepoint is not valid, this will set all the fields to 0.  */
11403       last_sal = get_last_displayed_sal ();
11404       if (last_sal.symtab == 0)
11405         error (_("No source file specified."));
11406
11407       default_match = 1;
11408       sals = last_sal;
11409     }
11410
11411   /* We don't call resolve_sal_pc here.  That's not as bad as it
11412      seems, because all existing breakpoints typically have both
11413      file/line and pc set.  So, if clear is given file/line, we can
11414      match this to existing breakpoint without obtaining pc at all.
11415
11416      We only support clearing given the address explicitly 
11417      present in breakpoint table.  Say, we've set breakpoint 
11418      at file:line.  There were several PC values for that file:line,
11419      due to optimization, all in one block.
11420
11421      We've picked one PC value.  If "clear" is issued with another
11422      PC corresponding to the same file:line, the breakpoint won't
11423      be cleared.  We probably can still clear the breakpoint, but 
11424      since the other PC value is never presented to user, user
11425      can only find it by guessing, and it does not seem important
11426      to support that.  */
11427
11428   /* For each line spec given, delete bps which correspond to it.  Do
11429      it in two passes, solely to preserve the current behavior that
11430      from_tty is forced true if we delete more than one
11431      breakpoint.  */
11432
11433   std::vector<struct breakpoint *> found;
11434   for (const auto &sal : sals)
11435     {
11436       const char *sal_fullname;
11437
11438       /* If exact pc given, clear bpts at that pc.
11439          If line given (pc == 0), clear all bpts on specified line.
11440          If defaulting, clear all bpts on default line
11441          or at default pc.
11442
11443          defaulting    sal.pc != 0    tests to do
11444
11445          0              1             pc
11446          1              1             pc _and_ line
11447          0              0             line
11448          1              0             <can't happen> */
11449
11450       sal_fullname = (sal.symtab == NULL
11451                       ? NULL : symtab_to_fullname (sal.symtab));
11452
11453       /* Find all matching breakpoints and add them to 'found'.  */
11454       ALL_BREAKPOINTS (b)
11455         {
11456           int match = 0;
11457           /* Are we going to delete b?  */
11458           if (b->type != bp_none && !is_watchpoint (b))
11459             {
11460               struct bp_location *loc = b->loc;
11461               for (; loc; loc = loc->next)
11462                 {
11463                   /* If the user specified file:line, don't allow a PC
11464                      match.  This matches historical gdb behavior.  */
11465                   int pc_match = (!sal.explicit_line
11466                                   && sal.pc
11467                                   && (loc->pspace == sal.pspace)
11468                                   && (loc->address == sal.pc)
11469                                   && (!section_is_overlay (loc->section)
11470                                       || loc->section == sal.section));
11471                   int line_match = 0;
11472
11473                   if ((default_match || sal.explicit_line)
11474                       && loc->symtab != NULL
11475                       && sal_fullname != NULL
11476                       && sal.pspace == loc->pspace
11477                       && loc->line_number == sal.line
11478                       && filename_cmp (symtab_to_fullname (loc->symtab),
11479                                        sal_fullname) == 0)
11480                     line_match = 1;
11481
11482                   if (pc_match || line_match)
11483                     {
11484                       match = 1;
11485                       break;
11486                     }
11487                 }
11488             }
11489
11490           if (match)
11491             found.push_back (b);
11492         }
11493     }
11494
11495   /* Now go thru the 'found' chain and delete them.  */
11496   if (found.empty ())
11497     {
11498       if (arg)
11499         error (_("No breakpoint at %s."), arg);
11500       else
11501         error (_("No breakpoint at this line."));
11502     }
11503
11504   /* Remove duplicates from the vec.  */
11505   std::sort (found.begin (), found.end (),
11506              [] (const breakpoint *a, const breakpoint *b)
11507              {
11508                return compare_breakpoints (a, b) < 0;
11509              });
11510   found.erase (std::unique (found.begin (), found.end (),
11511                             [] (const breakpoint *a, const breakpoint *b)
11512                             {
11513                               return compare_breakpoints (a, b) == 0;
11514                             }),
11515                found.end ());
11516
11517   if (found.size () > 1)
11518     from_tty = 1;       /* Always report if deleted more than one.  */
11519   if (from_tty)
11520     {
11521       if (found.size () == 1)
11522         printf_unfiltered (_("Deleted breakpoint "));
11523       else
11524         printf_unfiltered (_("Deleted breakpoints "));
11525     }
11526
11527   for (breakpoint *iter : found)
11528     {
11529       if (from_tty)
11530         printf_unfiltered ("%d ", iter->number);
11531       delete_breakpoint (iter);
11532     }
11533   if (from_tty)
11534     putchar_unfiltered ('\n');
11535 }
11536 \f
11537 /* Delete breakpoint in BS if they are `delete' breakpoints and
11538    all breakpoints that are marked for deletion, whether hit or not.
11539    This is called after any breakpoint is hit, or after errors.  */
11540
11541 void
11542 breakpoint_auto_delete (bpstat bs)
11543 {
11544   struct breakpoint *b, *b_tmp;
11545
11546   for (; bs; bs = bs->next)
11547     if (bs->breakpoint_at
11548         && bs->breakpoint_at->disposition == disp_del
11549         && bs->stop)
11550       delete_breakpoint (bs->breakpoint_at);
11551
11552   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11553   {
11554     if (b->disposition == disp_del_at_next_stop)
11555       delete_breakpoint (b);
11556   }
11557 }
11558
11559 /* A comparison function for bp_location AP and BP being interfaced to
11560    qsort.  Sort elements primarily by their ADDRESS (no matter what
11561    does breakpoint_address_is_meaningful say for its OWNER),
11562    secondarily by ordering first permanent elements and
11563    terciarily just ensuring the array is sorted stable way despite
11564    qsort being an unstable algorithm.  */
11565
11566 static int
11567 bp_locations_compare (const void *ap, const void *bp)
11568 {
11569   const struct bp_location *a = *(const struct bp_location **) ap;
11570   const struct bp_location *b = *(const struct bp_location **) bp;
11571
11572   if (a->address != b->address)
11573     return (a->address > b->address) - (a->address < b->address);
11574
11575   /* Sort locations at the same address by their pspace number, keeping
11576      locations of the same inferior (in a multi-inferior environment)
11577      grouped.  */
11578
11579   if (a->pspace->num != b->pspace->num)
11580     return ((a->pspace->num > b->pspace->num)
11581             - (a->pspace->num < b->pspace->num));
11582
11583   /* Sort permanent breakpoints first.  */
11584   if (a->permanent != b->permanent)
11585     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
11586
11587   /* Make the internal GDB representation stable across GDB runs
11588      where A and B memory inside GDB can differ.  Breakpoint locations of
11589      the same type at the same address can be sorted in arbitrary order.  */
11590
11591   if (a->owner->number != b->owner->number)
11592     return ((a->owner->number > b->owner->number)
11593             - (a->owner->number < b->owner->number));
11594
11595   return (a > b) - (a < b);
11596 }
11597
11598 /* Set bp_locations_placed_address_before_address_max and
11599    bp_locations_shadow_len_after_address_max according to the current
11600    content of the bp_locations array.  */
11601
11602 static void
11603 bp_locations_target_extensions_update (void)
11604 {
11605   struct bp_location *bl, **blp_tmp;
11606
11607   bp_locations_placed_address_before_address_max = 0;
11608   bp_locations_shadow_len_after_address_max = 0;
11609
11610   ALL_BP_LOCATIONS (bl, blp_tmp)
11611     {
11612       CORE_ADDR start, end, addr;
11613
11614       if (!bp_location_has_shadow (bl))
11615         continue;
11616
11617       start = bl->target_info.placed_address;
11618       end = start + bl->target_info.shadow_len;
11619
11620       gdb_assert (bl->address >= start);
11621       addr = bl->address - start;
11622       if (addr > bp_locations_placed_address_before_address_max)
11623         bp_locations_placed_address_before_address_max = addr;
11624
11625       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11626
11627       gdb_assert (bl->address < end);
11628       addr = end - bl->address;
11629       if (addr > bp_locations_shadow_len_after_address_max)
11630         bp_locations_shadow_len_after_address_max = addr;
11631     }
11632 }
11633
11634 /* Download tracepoint locations if they haven't been.  */
11635
11636 static void
11637 download_tracepoint_locations (void)
11638 {
11639   struct breakpoint *b;
11640   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11641
11642   scoped_restore_current_pspace_and_thread restore_pspace_thread;
11643
11644   ALL_TRACEPOINTS (b)
11645     {
11646       struct bp_location *bl;
11647       struct tracepoint *t;
11648       int bp_location_downloaded = 0;
11649
11650       if ((b->type == bp_fast_tracepoint
11651            ? !may_insert_fast_tracepoints
11652            : !may_insert_tracepoints))
11653         continue;
11654
11655       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11656         {
11657           if (target_can_download_tracepoint ())
11658             can_download_tracepoint = TRIBOOL_TRUE;
11659           else
11660             can_download_tracepoint = TRIBOOL_FALSE;
11661         }
11662
11663       if (can_download_tracepoint == TRIBOOL_FALSE)
11664         break;
11665
11666       for (bl = b->loc; bl; bl = bl->next)
11667         {
11668           /* In tracepoint, locations are _never_ duplicated, so
11669              should_be_inserted is equivalent to
11670              unduplicated_should_be_inserted.  */
11671           if (!should_be_inserted (bl) || bl->inserted)
11672             continue;
11673
11674           switch_to_program_space_and_thread (bl->pspace);
11675
11676           target_download_tracepoint (bl);
11677
11678           bl->inserted = 1;
11679           bp_location_downloaded = 1;
11680         }
11681       t = (struct tracepoint *) b;
11682       t->number_on_target = b->number;
11683       if (bp_location_downloaded)
11684         gdb::observers::breakpoint_modified.notify (b);
11685     }
11686 }
11687
11688 /* Swap the insertion/duplication state between two locations.  */
11689
11690 static void
11691 swap_insertion (struct bp_location *left, struct bp_location *right)
11692 {
11693   const int left_inserted = left->inserted;
11694   const int left_duplicate = left->duplicate;
11695   const int left_needs_update = left->needs_update;
11696   const struct bp_target_info left_target_info = left->target_info;
11697
11698   /* Locations of tracepoints can never be duplicated.  */
11699   if (is_tracepoint (left->owner))
11700     gdb_assert (!left->duplicate);
11701   if (is_tracepoint (right->owner))
11702     gdb_assert (!right->duplicate);
11703
11704   left->inserted = right->inserted;
11705   left->duplicate = right->duplicate;
11706   left->needs_update = right->needs_update;
11707   left->target_info = right->target_info;
11708   right->inserted = left_inserted;
11709   right->duplicate = left_duplicate;
11710   right->needs_update = left_needs_update;
11711   right->target_info = left_target_info;
11712 }
11713
11714 /* Force the re-insertion of the locations at ADDRESS.  This is called
11715    once a new/deleted/modified duplicate location is found and we are evaluating
11716    conditions on the target's side.  Such conditions need to be updated on
11717    the target.  */
11718
11719 static void
11720 force_breakpoint_reinsertion (struct bp_location *bl)
11721 {
11722   struct bp_location **locp = NULL, **loc2p;
11723   struct bp_location *loc;
11724   CORE_ADDR address = 0;
11725   int pspace_num;
11726
11727   address = bl->address;
11728   pspace_num = bl->pspace->num;
11729
11730   /* This is only meaningful if the target is
11731      evaluating conditions and if the user has
11732      opted for condition evaluation on the target's
11733      side.  */
11734   if (gdb_evaluates_breakpoint_condition_p ()
11735       || !target_supports_evaluation_of_breakpoint_conditions ())
11736     return;
11737
11738   /* Flag all breakpoint locations with this address and
11739      the same program space as the location
11740      as "its condition has changed".  We need to
11741      update the conditions on the target's side.  */
11742   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11743     {
11744       loc = *loc2p;
11745
11746       if (!is_breakpoint (loc->owner)
11747           || pspace_num != loc->pspace->num)
11748         continue;
11749
11750       /* Flag the location appropriately.  We use a different state to
11751          let everyone know that we already updated the set of locations
11752          with addr bl->address and program space bl->pspace.  This is so
11753          we don't have to keep calling these functions just to mark locations
11754          that have already been marked.  */
11755       loc->condition_changed = condition_updated;
11756
11757       /* Free the agent expression bytecode as well.  We will compute
11758          it later on.  */
11759       loc->cond_bytecode.reset ();
11760     }
11761 }
11762 /* Called whether new breakpoints are created, or existing breakpoints
11763    deleted, to update the global location list and recompute which
11764    locations are duplicate of which.
11765
11766    The INSERT_MODE flag determines whether locations may not, may, or
11767    shall be inserted now.  See 'enum ugll_insert_mode' for more
11768    info.  */
11769
11770 static void
11771 update_global_location_list (enum ugll_insert_mode insert_mode)
11772 {
11773   struct breakpoint *b;
11774   struct bp_location **locp, *loc;
11775   /* Last breakpoint location address that was marked for update.  */
11776   CORE_ADDR last_addr = 0;
11777   /* Last breakpoint location program space that was marked for update.  */
11778   int last_pspace_num = -1;
11779
11780   /* Used in the duplicates detection below.  When iterating over all
11781      bp_locations, points to the first bp_location of a given address.
11782      Breakpoints and watchpoints of different types are never
11783      duplicates of each other.  Keep one pointer for each type of
11784      breakpoint/watchpoint, so we only need to loop over all locations
11785      once.  */
11786   struct bp_location *bp_loc_first;  /* breakpoint */
11787   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11788   struct bp_location *awp_loc_first; /* access watchpoint */
11789   struct bp_location *rwp_loc_first; /* read watchpoint */
11790
11791   /* Saved former bp_locations array which we compare against the newly
11792      built bp_locations from the current state of ALL_BREAKPOINTS.  */
11793   struct bp_location **old_locp;
11794   unsigned old_locations_count;
11795   gdb::unique_xmalloc_ptr<struct bp_location *> old_locations (bp_locations);
11796
11797   old_locations_count = bp_locations_count;
11798   bp_locations = NULL;
11799   bp_locations_count = 0;
11800
11801   ALL_BREAKPOINTS (b)
11802     for (loc = b->loc; loc; loc = loc->next)
11803       bp_locations_count++;
11804
11805   bp_locations = XNEWVEC (struct bp_location *, bp_locations_count);
11806   locp = bp_locations;
11807   ALL_BREAKPOINTS (b)
11808     for (loc = b->loc; loc; loc = loc->next)
11809       *locp++ = loc;
11810   qsort (bp_locations, bp_locations_count, sizeof (*bp_locations),
11811          bp_locations_compare);
11812
11813   bp_locations_target_extensions_update ();
11814
11815   /* Identify bp_location instances that are no longer present in the
11816      new list, and therefore should be freed.  Note that it's not
11817      necessary that those locations should be removed from inferior --
11818      if there's another location at the same address (previously
11819      marked as duplicate), we don't need to remove/insert the
11820      location.
11821      
11822      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11823      and former bp_location array state respectively.  */
11824
11825   locp = bp_locations;
11826   for (old_locp = old_locations.get ();
11827        old_locp < old_locations.get () + old_locations_count;
11828        old_locp++)
11829     {
11830       struct bp_location *old_loc = *old_locp;
11831       struct bp_location **loc2p;
11832
11833       /* Tells if 'old_loc' is found among the new locations.  If
11834          not, we have to free it.  */
11835       int found_object = 0;
11836       /* Tells if the location should remain inserted in the target.  */
11837       int keep_in_target = 0;
11838       int removed = 0;
11839
11840       /* Skip LOCP entries which will definitely never be needed.
11841          Stop either at or being the one matching OLD_LOC.  */
11842       while (locp < bp_locations + bp_locations_count
11843              && (*locp)->address < old_loc->address)
11844         locp++;
11845
11846       for (loc2p = locp;
11847            (loc2p < bp_locations + bp_locations_count
11848             && (*loc2p)->address == old_loc->address);
11849            loc2p++)
11850         {
11851           /* Check if this is a new/duplicated location or a duplicated
11852              location that had its condition modified.  If so, we want to send
11853              its condition to the target if evaluation of conditions is taking
11854              place there.  */
11855           if ((*loc2p)->condition_changed == condition_modified
11856               && (last_addr != old_loc->address
11857                   || last_pspace_num != old_loc->pspace->num))
11858             {
11859               force_breakpoint_reinsertion (*loc2p);
11860               last_pspace_num = old_loc->pspace->num;
11861             }
11862
11863           if (*loc2p == old_loc)
11864             found_object = 1;
11865         }
11866
11867       /* We have already handled this address, update it so that we don't
11868          have to go through updates again.  */
11869       last_addr = old_loc->address;
11870
11871       /* Target-side condition evaluation: Handle deleted locations.  */
11872       if (!found_object)
11873         force_breakpoint_reinsertion (old_loc);
11874
11875       /* If this location is no longer present, and inserted, look if
11876          there's maybe a new location at the same address.  If so,
11877          mark that one inserted, and don't remove this one.  This is
11878          needed so that we don't have a time window where a breakpoint
11879          at certain location is not inserted.  */
11880
11881       if (old_loc->inserted)
11882         {
11883           /* If the location is inserted now, we might have to remove
11884              it.  */
11885
11886           if (found_object && should_be_inserted (old_loc))
11887             {
11888               /* The location is still present in the location list,
11889                  and still should be inserted.  Don't do anything.  */
11890               keep_in_target = 1;
11891             }
11892           else
11893             {
11894               /* This location still exists, but it won't be kept in the
11895                  target since it may have been disabled.  We proceed to
11896                  remove its target-side condition.  */
11897
11898               /* The location is either no longer present, or got
11899                  disabled.  See if there's another location at the
11900                  same address, in which case we don't need to remove
11901                  this one from the target.  */
11902
11903               /* OLD_LOC comes from existing struct breakpoint.  */
11904               if (breakpoint_address_is_meaningful (old_loc->owner))
11905                 {
11906                   for (loc2p = locp;
11907                        (loc2p < bp_locations + bp_locations_count
11908                         && (*loc2p)->address == old_loc->address);
11909                        loc2p++)
11910                     {
11911                       struct bp_location *loc2 = *loc2p;
11912
11913                       if (breakpoint_locations_match (loc2, old_loc))
11914                         {
11915                           /* Read watchpoint locations are switched to
11916                              access watchpoints, if the former are not
11917                              supported, but the latter are.  */
11918                           if (is_hardware_watchpoint (old_loc->owner))
11919                             {
11920                               gdb_assert (is_hardware_watchpoint (loc2->owner));
11921                               loc2->watchpoint_type = old_loc->watchpoint_type;
11922                             }
11923
11924                           /* loc2 is a duplicated location. We need to check
11925                              if it should be inserted in case it will be
11926                              unduplicated.  */
11927                           if (loc2 != old_loc
11928                               && unduplicated_should_be_inserted (loc2))
11929                             {
11930                               swap_insertion (old_loc, loc2);
11931                               keep_in_target = 1;
11932                               break;
11933                             }
11934                         }
11935                     }
11936                 }
11937             }
11938
11939           if (!keep_in_target)
11940             {
11941               if (remove_breakpoint (old_loc))
11942                 {
11943                   /* This is just about all we can do.  We could keep
11944                      this location on the global list, and try to
11945                      remove it next time, but there's no particular
11946                      reason why we will succeed next time.
11947                      
11948                      Note that at this point, old_loc->owner is still
11949                      valid, as delete_breakpoint frees the breakpoint
11950                      only after calling us.  */
11951                   printf_filtered (_("warning: Error removing "
11952                                      "breakpoint %d\n"), 
11953                                    old_loc->owner->number);
11954                 }
11955               removed = 1;
11956             }
11957         }
11958
11959       if (!found_object)
11960         {
11961           if (removed && target_is_non_stop_p ()
11962               && need_moribund_for_location_type (old_loc))
11963             {
11964               /* This location was removed from the target.  In
11965                  non-stop mode, a race condition is possible where
11966                  we've removed a breakpoint, but stop events for that
11967                  breakpoint are already queued and will arrive later.
11968                  We apply an heuristic to be able to distinguish such
11969                  SIGTRAPs from other random SIGTRAPs: we keep this
11970                  breakpoint location for a bit, and will retire it
11971                  after we see some number of events.  The theory here
11972                  is that reporting of events should, "on the average",
11973                  be fair, so after a while we'll see events from all
11974                  threads that have anything of interest, and no longer
11975                  need to keep this breakpoint location around.  We
11976                  don't hold locations forever so to reduce chances of
11977                  mistaking a non-breakpoint SIGTRAP for a breakpoint
11978                  SIGTRAP.
11979
11980                  The heuristic failing can be disastrous on
11981                  decr_pc_after_break targets.
11982
11983                  On decr_pc_after_break targets, like e.g., x86-linux,
11984                  if we fail to recognize a late breakpoint SIGTRAP,
11985                  because events_till_retirement has reached 0 too
11986                  soon, we'll fail to do the PC adjustment, and report
11987                  a random SIGTRAP to the user.  When the user resumes
11988                  the inferior, it will most likely immediately crash
11989                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
11990                  corrupted, because of being resumed e.g., in the
11991                  middle of a multi-byte instruction, or skipped a
11992                  one-byte instruction.  This was actually seen happen
11993                  on native x86-linux, and should be less rare on
11994                  targets that do not support new thread events, like
11995                  remote, due to the heuristic depending on
11996                  thread_count.
11997
11998                  Mistaking a random SIGTRAP for a breakpoint trap
11999                  causes similar symptoms (PC adjustment applied when
12000                  it shouldn't), but then again, playing with SIGTRAPs
12001                  behind the debugger's back is asking for trouble.
12002
12003                  Since hardware watchpoint traps are always
12004                  distinguishable from other traps, so we don't need to
12005                  apply keep hardware watchpoint moribund locations
12006                  around.  We simply always ignore hardware watchpoint
12007                  traps we can no longer explain.  */
12008
12009               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12010               old_loc->owner = NULL;
12011
12012               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12013             }
12014           else
12015             {
12016               old_loc->owner = NULL;
12017               decref_bp_location (&old_loc);
12018             }
12019         }
12020     }
12021
12022   /* Rescan breakpoints at the same address and section, marking the
12023      first one as "first" and any others as "duplicates".  This is so
12024      that the bpt instruction is only inserted once.  If we have a
12025      permanent breakpoint at the same place as BPT, make that one the
12026      official one, and the rest as duplicates.  Permanent breakpoints
12027      are sorted first for the same address.
12028
12029      Do the same for hardware watchpoints, but also considering the
12030      watchpoint's type (regular/access/read) and length.  */
12031
12032   bp_loc_first = NULL;
12033   wp_loc_first = NULL;
12034   awp_loc_first = NULL;
12035   rwp_loc_first = NULL;
12036   ALL_BP_LOCATIONS (loc, locp)
12037     {
12038       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12039          non-NULL.  */
12040       struct bp_location **loc_first_p;
12041       b = loc->owner;
12042
12043       if (!unduplicated_should_be_inserted (loc)
12044           || !breakpoint_address_is_meaningful (b)
12045           /* Don't detect duplicate for tracepoint locations because they are
12046            never duplicated.  See the comments in field `duplicate' of
12047            `struct bp_location'.  */
12048           || is_tracepoint (b))
12049         {
12050           /* Clear the condition modification flag.  */
12051           loc->condition_changed = condition_unchanged;
12052           continue;
12053         }
12054
12055       if (b->type == bp_hardware_watchpoint)
12056         loc_first_p = &wp_loc_first;
12057       else if (b->type == bp_read_watchpoint)
12058         loc_first_p = &rwp_loc_first;
12059       else if (b->type == bp_access_watchpoint)
12060         loc_first_p = &awp_loc_first;
12061       else
12062         loc_first_p = &bp_loc_first;
12063
12064       if (*loc_first_p == NULL
12065           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12066           || !breakpoint_locations_match (loc, *loc_first_p))
12067         {
12068           *loc_first_p = loc;
12069           loc->duplicate = 0;
12070
12071           if (is_breakpoint (loc->owner) && loc->condition_changed)
12072             {
12073               loc->needs_update = 1;
12074               /* Clear the condition modification flag.  */
12075               loc->condition_changed = condition_unchanged;
12076             }
12077           continue;
12078         }
12079
12080
12081       /* This and the above ensure the invariant that the first location
12082          is not duplicated, and is the inserted one.
12083          All following are marked as duplicated, and are not inserted.  */
12084       if (loc->inserted)
12085         swap_insertion (loc, *loc_first_p);
12086       loc->duplicate = 1;
12087
12088       /* Clear the condition modification flag.  */
12089       loc->condition_changed = condition_unchanged;
12090     }
12091
12092   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12093     {
12094       if (insert_mode != UGLL_DONT_INSERT)
12095         insert_breakpoint_locations ();
12096       else
12097         {
12098           /* Even though the caller told us to not insert new
12099              locations, we may still need to update conditions on the
12100              target's side of breakpoints that were already inserted
12101              if the target is evaluating breakpoint conditions.  We
12102              only update conditions for locations that are marked
12103              "needs_update".  */
12104           update_inserted_breakpoint_locations ();
12105         }
12106     }
12107
12108   if (insert_mode != UGLL_DONT_INSERT)
12109     download_tracepoint_locations ();
12110 }
12111
12112 void
12113 breakpoint_retire_moribund (void)
12114 {
12115   struct bp_location *loc;
12116   int ix;
12117
12118   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12119     if (--(loc->events_till_retirement) == 0)
12120       {
12121         decref_bp_location (&loc);
12122         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12123         --ix;
12124       }
12125 }
12126
12127 static void
12128 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12129 {
12130
12131   TRY
12132     {
12133       update_global_location_list (insert_mode);
12134     }
12135   CATCH (e, RETURN_MASK_ERROR)
12136     {
12137     }
12138   END_CATCH
12139 }
12140
12141 /* Clear BKP from a BPS.  */
12142
12143 static void
12144 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12145 {
12146   bpstat bs;
12147
12148   for (bs = bps; bs; bs = bs->next)
12149     if (bs->breakpoint_at == bpt)
12150       {
12151         bs->breakpoint_at = NULL;
12152         bs->old_val = NULL;
12153         /* bs->commands will be freed later.  */
12154       }
12155 }
12156
12157 /* Callback for iterate_over_threads.  */
12158 static int
12159 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12160 {
12161   struct breakpoint *bpt = (struct breakpoint *) data;
12162
12163   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12164   return 0;
12165 }
12166
12167 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12168    callbacks.  */
12169
12170 static void
12171 say_where (struct breakpoint *b)
12172 {
12173   struct value_print_options opts;
12174
12175   get_user_print_options (&opts);
12176
12177   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12178      single string.  */
12179   if (b->loc == NULL)
12180     {
12181       /* For pending locations, the output differs slightly based
12182          on b->extra_string.  If this is non-NULL, it contains either
12183          a condition or dprintf arguments.  */
12184       if (b->extra_string == NULL)
12185         {
12186           printf_filtered (_(" (%s) pending."),
12187                            event_location_to_string (b->location.get ()));
12188         }
12189       else if (b->type == bp_dprintf)
12190         {
12191           printf_filtered (_(" (%s,%s) pending."),
12192                            event_location_to_string (b->location.get ()),
12193                            b->extra_string);
12194         }
12195       else
12196         {
12197           printf_filtered (_(" (%s %s) pending."),
12198                            event_location_to_string (b->location.get ()),
12199                            b->extra_string);
12200         }
12201     }
12202   else
12203     {
12204       if (opts.addressprint || b->loc->symtab == NULL)
12205         {
12206           printf_filtered (" at ");
12207           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12208                           gdb_stdout);
12209         }
12210       if (b->loc->symtab != NULL)
12211         {
12212           /* If there is a single location, we can print the location
12213              more nicely.  */
12214           if (b->loc->next == NULL)
12215             printf_filtered (": file %s, line %d.",
12216                              symtab_to_filename_for_display (b->loc->symtab),
12217                              b->loc->line_number);
12218           else
12219             /* This is not ideal, but each location may have a
12220                different file name, and this at least reflects the
12221                real situation somewhat.  */
12222             printf_filtered (": %s.",
12223                              event_location_to_string (b->location.get ()));
12224         }
12225
12226       if (b->loc->next)
12227         {
12228           struct bp_location *loc = b->loc;
12229           int n = 0;
12230           for (; loc; loc = loc->next)
12231             ++n;
12232           printf_filtered (" (%d locations)", n);
12233         }
12234     }
12235 }
12236
12237 /* Default bp_location_ops methods.  */
12238
12239 static void
12240 bp_location_dtor (struct bp_location *self)
12241 {
12242   xfree (self->function_name);
12243 }
12244
12245 static const struct bp_location_ops bp_location_ops =
12246 {
12247   bp_location_dtor
12248 };
12249
12250 /* Destructor for the breakpoint base class.  */
12251
12252 breakpoint::~breakpoint ()
12253 {
12254   xfree (this->cond_string);
12255   xfree (this->extra_string);
12256   xfree (this->filter);
12257 }
12258
12259 static struct bp_location *
12260 base_breakpoint_allocate_location (struct breakpoint *self)
12261 {
12262   return new bp_location (&bp_location_ops, self);
12263 }
12264
12265 static void
12266 base_breakpoint_re_set (struct breakpoint *b)
12267 {
12268   /* Nothing to re-set. */
12269 }
12270
12271 #define internal_error_pure_virtual_called() \
12272   gdb_assert_not_reached ("pure virtual function called")
12273
12274 static int
12275 base_breakpoint_insert_location (struct bp_location *bl)
12276 {
12277   internal_error_pure_virtual_called ();
12278 }
12279
12280 static int
12281 base_breakpoint_remove_location (struct bp_location *bl,
12282                                  enum remove_bp_reason reason)
12283 {
12284   internal_error_pure_virtual_called ();
12285 }
12286
12287 static int
12288 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12289                                 const address_space *aspace,
12290                                 CORE_ADDR bp_addr,
12291                                 const struct target_waitstatus *ws)
12292 {
12293   internal_error_pure_virtual_called ();
12294 }
12295
12296 static void
12297 base_breakpoint_check_status (bpstat bs)
12298 {
12299   /* Always stop.   */
12300 }
12301
12302 /* A "works_in_software_mode" breakpoint_ops method that just internal
12303    errors.  */
12304
12305 static int
12306 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12307 {
12308   internal_error_pure_virtual_called ();
12309 }
12310
12311 /* A "resources_needed" breakpoint_ops method that just internal
12312    errors.  */
12313
12314 static int
12315 base_breakpoint_resources_needed (const struct bp_location *bl)
12316 {
12317   internal_error_pure_virtual_called ();
12318 }
12319
12320 static enum print_stop_action
12321 base_breakpoint_print_it (bpstat bs)
12322 {
12323   internal_error_pure_virtual_called ();
12324 }
12325
12326 static void
12327 base_breakpoint_print_one_detail (const struct breakpoint *self,
12328                                   struct ui_out *uiout)
12329 {
12330   /* nothing */
12331 }
12332
12333 static void
12334 base_breakpoint_print_mention (struct breakpoint *b)
12335 {
12336   internal_error_pure_virtual_called ();
12337 }
12338
12339 static void
12340 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12341 {
12342   internal_error_pure_virtual_called ();
12343 }
12344
12345 static void
12346 base_breakpoint_create_sals_from_location
12347   (const struct event_location *location,
12348    struct linespec_result *canonical,
12349    enum bptype type_wanted)
12350 {
12351   internal_error_pure_virtual_called ();
12352 }
12353
12354 static void
12355 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12356                                         struct linespec_result *c,
12357                                         gdb::unique_xmalloc_ptr<char> cond_string,
12358                                         gdb::unique_xmalloc_ptr<char> extra_string,
12359                                         enum bptype type_wanted,
12360                                         enum bpdisp disposition,
12361                                         int thread,
12362                                         int task, int ignore_count,
12363                                         const struct breakpoint_ops *o,
12364                                         int from_tty, int enabled,
12365                                         int internal, unsigned flags)
12366 {
12367   internal_error_pure_virtual_called ();
12368 }
12369
12370 static std::vector<symtab_and_line>
12371 base_breakpoint_decode_location (struct breakpoint *b,
12372                                  const struct event_location *location,
12373                                  struct program_space *search_pspace)
12374 {
12375   internal_error_pure_virtual_called ();
12376 }
12377
12378 /* The default 'explains_signal' method.  */
12379
12380 static int
12381 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12382 {
12383   return 1;
12384 }
12385
12386 /* The default "after_condition_true" method.  */
12387
12388 static void
12389 base_breakpoint_after_condition_true (struct bpstats *bs)
12390 {
12391   /* Nothing to do.   */
12392 }
12393
12394 struct breakpoint_ops base_breakpoint_ops =
12395 {
12396   base_breakpoint_allocate_location,
12397   base_breakpoint_re_set,
12398   base_breakpoint_insert_location,
12399   base_breakpoint_remove_location,
12400   base_breakpoint_breakpoint_hit,
12401   base_breakpoint_check_status,
12402   base_breakpoint_resources_needed,
12403   base_breakpoint_works_in_software_mode,
12404   base_breakpoint_print_it,
12405   NULL,
12406   base_breakpoint_print_one_detail,
12407   base_breakpoint_print_mention,
12408   base_breakpoint_print_recreate,
12409   base_breakpoint_create_sals_from_location,
12410   base_breakpoint_create_breakpoints_sal,
12411   base_breakpoint_decode_location,
12412   base_breakpoint_explains_signal,
12413   base_breakpoint_after_condition_true,
12414 };
12415
12416 /* Default breakpoint_ops methods.  */
12417
12418 static void
12419 bkpt_re_set (struct breakpoint *b)
12420 {
12421   /* FIXME: is this still reachable?  */
12422   if (breakpoint_event_location_empty_p (b))
12423     {
12424       /* Anything without a location can't be re-set.  */
12425       delete_breakpoint (b);
12426       return;
12427     }
12428
12429   breakpoint_re_set_default (b);
12430 }
12431
12432 static int
12433 bkpt_insert_location (struct bp_location *bl)
12434 {
12435   CORE_ADDR addr = bl->target_info.reqstd_address;
12436
12437   bl->target_info.kind = breakpoint_kind (bl, &addr);
12438   bl->target_info.placed_address = addr;
12439
12440   if (bl->loc_type == bp_loc_hardware_breakpoint)
12441     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12442   else
12443     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12444 }
12445
12446 static int
12447 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
12448 {
12449   if (bl->loc_type == bp_loc_hardware_breakpoint)
12450     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12451   else
12452     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12453 }
12454
12455 static int
12456 bkpt_breakpoint_hit (const struct bp_location *bl,
12457                      const address_space *aspace, CORE_ADDR bp_addr,
12458                      const struct target_waitstatus *ws)
12459 {
12460   if (ws->kind != TARGET_WAITKIND_STOPPED
12461       || ws->value.sig != GDB_SIGNAL_TRAP)
12462     return 0;
12463
12464   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12465                                  aspace, bp_addr))
12466     return 0;
12467
12468   if (overlay_debugging         /* unmapped overlay section */
12469       && section_is_overlay (bl->section)
12470       && !section_is_mapped (bl->section))
12471     return 0;
12472
12473   return 1;
12474 }
12475
12476 static int
12477 dprintf_breakpoint_hit (const struct bp_location *bl,
12478                         const address_space *aspace, CORE_ADDR bp_addr,
12479                         const struct target_waitstatus *ws)
12480 {
12481   if (dprintf_style == dprintf_style_agent
12482       && target_can_run_breakpoint_commands ())
12483     {
12484       /* An agent-style dprintf never causes a stop.  If we see a trap
12485          for this address it must be for a breakpoint that happens to
12486          be set at the same address.  */
12487       return 0;
12488     }
12489
12490   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12491 }
12492
12493 static int
12494 bkpt_resources_needed (const struct bp_location *bl)
12495 {
12496   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12497
12498   return 1;
12499 }
12500
12501 static enum print_stop_action
12502 bkpt_print_it (bpstat bs)
12503 {
12504   struct breakpoint *b;
12505   const struct bp_location *bl;
12506   int bp_temp;
12507   struct ui_out *uiout = current_uiout;
12508
12509   gdb_assert (bs->bp_location_at != NULL);
12510
12511   bl = bs->bp_location_at;
12512   b = bs->breakpoint_at;
12513
12514   bp_temp = b->disposition == disp_del;
12515   if (bl->address != bl->requested_address)
12516     breakpoint_adjustment_warning (bl->requested_address,
12517                                    bl->address,
12518                                    b->number, 1);
12519   annotate_breakpoint (b->number);
12520   maybe_print_thread_hit_breakpoint (uiout);
12521
12522   if (bp_temp)
12523     uiout->text ("Temporary breakpoint ");
12524   else
12525     uiout->text ("Breakpoint ");
12526   if (uiout->is_mi_like_p ())
12527     {
12528       uiout->field_string ("reason",
12529                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12530       uiout->field_string ("disp", bpdisp_text (b->disposition));
12531     }
12532   uiout->field_int ("bkptno", b->number);
12533   uiout->text (", ");
12534
12535   return PRINT_SRC_AND_LOC;
12536 }
12537
12538 static void
12539 bkpt_print_mention (struct breakpoint *b)
12540 {
12541   if (current_uiout->is_mi_like_p ())
12542     return;
12543
12544   switch (b->type)
12545     {
12546     case bp_breakpoint:
12547     case bp_gnu_ifunc_resolver:
12548       if (b->disposition == disp_del)
12549         printf_filtered (_("Temporary breakpoint"));
12550       else
12551         printf_filtered (_("Breakpoint"));
12552       printf_filtered (_(" %d"), b->number);
12553       if (b->type == bp_gnu_ifunc_resolver)
12554         printf_filtered (_(" at gnu-indirect-function resolver"));
12555       break;
12556     case bp_hardware_breakpoint:
12557       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12558       break;
12559     case bp_dprintf:
12560       printf_filtered (_("Dprintf %d"), b->number);
12561       break;
12562     }
12563
12564   say_where (b);
12565 }
12566
12567 static void
12568 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12569 {
12570   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12571     fprintf_unfiltered (fp, "tbreak");
12572   else if (tp->type == bp_breakpoint)
12573     fprintf_unfiltered (fp, "break");
12574   else if (tp->type == bp_hardware_breakpoint
12575            && tp->disposition == disp_del)
12576     fprintf_unfiltered (fp, "thbreak");
12577   else if (tp->type == bp_hardware_breakpoint)
12578     fprintf_unfiltered (fp, "hbreak");
12579   else
12580     internal_error (__FILE__, __LINE__,
12581                     _("unhandled breakpoint type %d"), (int) tp->type);
12582
12583   fprintf_unfiltered (fp, " %s",
12584                       event_location_to_string (tp->location.get ()));
12585
12586   /* Print out extra_string if this breakpoint is pending.  It might
12587      contain, for example, conditions that were set by the user.  */
12588   if (tp->loc == NULL && tp->extra_string != NULL)
12589     fprintf_unfiltered (fp, " %s", tp->extra_string);
12590
12591   print_recreate_thread (tp, fp);
12592 }
12593
12594 static void
12595 bkpt_create_sals_from_location (const struct event_location *location,
12596                                 struct linespec_result *canonical,
12597                                 enum bptype type_wanted)
12598 {
12599   create_sals_from_location_default (location, canonical, type_wanted);
12600 }
12601
12602 static void
12603 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12604                              struct linespec_result *canonical,
12605                              gdb::unique_xmalloc_ptr<char> cond_string,
12606                              gdb::unique_xmalloc_ptr<char> extra_string,
12607                              enum bptype type_wanted,
12608                              enum bpdisp disposition,
12609                              int thread,
12610                              int task, int ignore_count,
12611                              const struct breakpoint_ops *ops,
12612                              int from_tty, int enabled,
12613                              int internal, unsigned flags)
12614 {
12615   create_breakpoints_sal_default (gdbarch, canonical,
12616                                   std::move (cond_string),
12617                                   std::move (extra_string),
12618                                   type_wanted,
12619                                   disposition, thread, task,
12620                                   ignore_count, ops, from_tty,
12621                                   enabled, internal, flags);
12622 }
12623
12624 static std::vector<symtab_and_line>
12625 bkpt_decode_location (struct breakpoint *b,
12626                       const struct event_location *location,
12627                       struct program_space *search_pspace)
12628 {
12629   return decode_location_default (b, location, search_pspace);
12630 }
12631
12632 /* Virtual table for internal breakpoints.  */
12633
12634 static void
12635 internal_bkpt_re_set (struct breakpoint *b)
12636 {
12637   switch (b->type)
12638     {
12639       /* Delete overlay event and longjmp master breakpoints; they
12640          will be reset later by breakpoint_re_set.  */
12641     case bp_overlay_event:
12642     case bp_longjmp_master:
12643     case bp_std_terminate_master:
12644     case bp_exception_master:
12645       delete_breakpoint (b);
12646       break;
12647
12648       /* This breakpoint is special, it's set up when the inferior
12649          starts and we really don't want to touch it.  */
12650     case bp_shlib_event:
12651
12652       /* Like bp_shlib_event, this breakpoint type is special.  Once
12653          it is set up, we do not want to touch it.  */
12654     case bp_thread_event:
12655       break;
12656     }
12657 }
12658
12659 static void
12660 internal_bkpt_check_status (bpstat bs)
12661 {
12662   if (bs->breakpoint_at->type == bp_shlib_event)
12663     {
12664       /* If requested, stop when the dynamic linker notifies GDB of
12665          events.  This allows the user to get control and place
12666          breakpoints in initializer routines for dynamically loaded
12667          objects (among other things).  */
12668       bs->stop = stop_on_solib_events;
12669       bs->print = stop_on_solib_events;
12670     }
12671   else
12672     bs->stop = 0;
12673 }
12674
12675 static enum print_stop_action
12676 internal_bkpt_print_it (bpstat bs)
12677 {
12678   struct breakpoint *b;
12679
12680   b = bs->breakpoint_at;
12681
12682   switch (b->type)
12683     {
12684     case bp_shlib_event:
12685       /* Did we stop because the user set the stop_on_solib_events
12686          variable?  (If so, we report this as a generic, "Stopped due
12687          to shlib event" message.) */
12688       print_solib_event (0);
12689       break;
12690
12691     case bp_thread_event:
12692       /* Not sure how we will get here.
12693          GDB should not stop for these breakpoints.  */
12694       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12695       break;
12696
12697     case bp_overlay_event:
12698       /* By analogy with the thread event, GDB should not stop for these.  */
12699       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12700       break;
12701
12702     case bp_longjmp_master:
12703       /* These should never be enabled.  */
12704       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12705       break;
12706
12707     case bp_std_terminate_master:
12708       /* These should never be enabled.  */
12709       printf_filtered (_("std::terminate Master Breakpoint: "
12710                          "gdb should not stop!\n"));
12711       break;
12712
12713     case bp_exception_master:
12714       /* These should never be enabled.  */
12715       printf_filtered (_("Exception Master Breakpoint: "
12716                          "gdb should not stop!\n"));
12717       break;
12718     }
12719
12720   return PRINT_NOTHING;
12721 }
12722
12723 static void
12724 internal_bkpt_print_mention (struct breakpoint *b)
12725 {
12726   /* Nothing to mention.  These breakpoints are internal.  */
12727 }
12728
12729 /* Virtual table for momentary breakpoints  */
12730
12731 static void
12732 momentary_bkpt_re_set (struct breakpoint *b)
12733 {
12734   /* Keep temporary breakpoints, which can be encountered when we step
12735      over a dlopen call and solib_add is resetting the breakpoints.
12736      Otherwise these should have been blown away via the cleanup chain
12737      or by breakpoint_init_inferior when we rerun the executable.  */
12738 }
12739
12740 static void
12741 momentary_bkpt_check_status (bpstat bs)
12742 {
12743   /* Nothing.  The point of these breakpoints is causing a stop.  */
12744 }
12745
12746 static enum print_stop_action
12747 momentary_bkpt_print_it (bpstat bs)
12748 {
12749   return PRINT_UNKNOWN;
12750 }
12751
12752 static void
12753 momentary_bkpt_print_mention (struct breakpoint *b)
12754 {
12755   /* Nothing to mention.  These breakpoints are internal.  */
12756 }
12757
12758 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12759
12760    It gets cleared already on the removal of the first one of such placed
12761    breakpoints.  This is OK as they get all removed altogether.  */
12762
12763 longjmp_breakpoint::~longjmp_breakpoint ()
12764 {
12765   thread_info *tp = find_thread_global_id (this->thread);
12766
12767   if (tp != NULL)
12768     tp->initiating_frame = null_frame_id;
12769 }
12770
12771 /* Specific methods for probe breakpoints.  */
12772
12773 static int
12774 bkpt_probe_insert_location (struct bp_location *bl)
12775 {
12776   int v = bkpt_insert_location (bl);
12777
12778   if (v == 0)
12779     {
12780       /* The insertion was successful, now let's set the probe's semaphore
12781          if needed.  */
12782       bl->probe.prob->set_semaphore (bl->probe.objfile, bl->gdbarch);
12783     }
12784
12785   return v;
12786 }
12787
12788 static int
12789 bkpt_probe_remove_location (struct bp_location *bl,
12790                             enum remove_bp_reason reason)
12791 {
12792   /* Let's clear the semaphore before removing the location.  */
12793   bl->probe.prob->clear_semaphore (bl->probe.objfile, bl->gdbarch);
12794
12795   return bkpt_remove_location (bl, reason);
12796 }
12797
12798 static void
12799 bkpt_probe_create_sals_from_location (const struct event_location *location,
12800                                       struct linespec_result *canonical,
12801                                       enum bptype type_wanted)
12802 {
12803   struct linespec_sals lsal;
12804
12805   lsal.sals = parse_probes (location, NULL, canonical);
12806   lsal.canonical
12807     = xstrdup (event_location_to_string (canonical->location.get ()));
12808   canonical->lsals.push_back (std::move (lsal));
12809 }
12810
12811 static std::vector<symtab_and_line>
12812 bkpt_probe_decode_location (struct breakpoint *b,
12813                             const struct event_location *location,
12814                             struct program_space *search_pspace)
12815 {
12816   std::vector<symtab_and_line> sals = parse_probes (location, search_pspace, NULL);
12817   if (sals.empty ())
12818     error (_("probe not found"));
12819   return sals;
12820 }
12821
12822 /* The breakpoint_ops structure to be used in tracepoints.  */
12823
12824 static void
12825 tracepoint_re_set (struct breakpoint *b)
12826 {
12827   breakpoint_re_set_default (b);
12828 }
12829
12830 static int
12831 tracepoint_breakpoint_hit (const struct bp_location *bl,
12832                            const address_space *aspace, CORE_ADDR bp_addr,
12833                            const struct target_waitstatus *ws)
12834 {
12835   /* By definition, the inferior does not report stops at
12836      tracepoints.  */
12837   return 0;
12838 }
12839
12840 static void
12841 tracepoint_print_one_detail (const struct breakpoint *self,
12842                              struct ui_out *uiout)
12843 {
12844   struct tracepoint *tp = (struct tracepoint *) self;
12845   if (!tp->static_trace_marker_id.empty ())
12846     {
12847       gdb_assert (self->type == bp_static_tracepoint);
12848
12849       uiout->text ("\tmarker id is ");
12850       uiout->field_string ("static-tracepoint-marker-string-id",
12851                            tp->static_trace_marker_id);
12852       uiout->text ("\n");
12853     }
12854 }
12855
12856 static void
12857 tracepoint_print_mention (struct breakpoint *b)
12858 {
12859   if (current_uiout->is_mi_like_p ())
12860     return;
12861
12862   switch (b->type)
12863     {
12864     case bp_tracepoint:
12865       printf_filtered (_("Tracepoint"));
12866       printf_filtered (_(" %d"), b->number);
12867       break;
12868     case bp_fast_tracepoint:
12869       printf_filtered (_("Fast tracepoint"));
12870       printf_filtered (_(" %d"), b->number);
12871       break;
12872     case bp_static_tracepoint:
12873       printf_filtered (_("Static tracepoint"));
12874       printf_filtered (_(" %d"), b->number);
12875       break;
12876     default:
12877       internal_error (__FILE__, __LINE__,
12878                       _("unhandled tracepoint type %d"), (int) b->type);
12879     }
12880
12881   say_where (b);
12882 }
12883
12884 static void
12885 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
12886 {
12887   struct tracepoint *tp = (struct tracepoint *) self;
12888
12889   if (self->type == bp_fast_tracepoint)
12890     fprintf_unfiltered (fp, "ftrace");
12891   else if (self->type == bp_static_tracepoint)
12892     fprintf_unfiltered (fp, "strace");
12893   else if (self->type == bp_tracepoint)
12894     fprintf_unfiltered (fp, "trace");
12895   else
12896     internal_error (__FILE__, __LINE__,
12897                     _("unhandled tracepoint type %d"), (int) self->type);
12898
12899   fprintf_unfiltered (fp, " %s",
12900                       event_location_to_string (self->location.get ()));
12901   print_recreate_thread (self, fp);
12902
12903   if (tp->pass_count)
12904     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
12905 }
12906
12907 static void
12908 tracepoint_create_sals_from_location (const struct event_location *location,
12909                                       struct linespec_result *canonical,
12910                                       enum bptype type_wanted)
12911 {
12912   create_sals_from_location_default (location, canonical, type_wanted);
12913 }
12914
12915 static void
12916 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12917                                    struct linespec_result *canonical,
12918                                    gdb::unique_xmalloc_ptr<char> cond_string,
12919                                    gdb::unique_xmalloc_ptr<char> extra_string,
12920                                    enum bptype type_wanted,
12921                                    enum bpdisp disposition,
12922                                    int thread,
12923                                    int task, int ignore_count,
12924                                    const struct breakpoint_ops *ops,
12925                                    int from_tty, int enabled,
12926                                    int internal, unsigned flags)
12927 {
12928   create_breakpoints_sal_default (gdbarch, canonical,
12929                                   std::move (cond_string),
12930                                   std::move (extra_string),
12931                                   type_wanted,
12932                                   disposition, thread, task,
12933                                   ignore_count, ops, from_tty,
12934                                   enabled, internal, flags);
12935 }
12936
12937 static std::vector<symtab_and_line>
12938 tracepoint_decode_location (struct breakpoint *b,
12939                             const struct event_location *location,
12940                             struct program_space *search_pspace)
12941 {
12942   return decode_location_default (b, location, search_pspace);
12943 }
12944
12945 struct breakpoint_ops tracepoint_breakpoint_ops;
12946
12947 /* The breakpoint_ops structure to be use on tracepoints placed in a
12948    static probe.  */
12949
12950 static void
12951 tracepoint_probe_create_sals_from_location
12952   (const struct event_location *location,
12953    struct linespec_result *canonical,
12954    enum bptype type_wanted)
12955 {
12956   /* We use the same method for breakpoint on probes.  */
12957   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
12958 }
12959
12960 static std::vector<symtab_and_line>
12961 tracepoint_probe_decode_location (struct breakpoint *b,
12962                                   const struct event_location *location,
12963                                   struct program_space *search_pspace)
12964 {
12965   /* We use the same method for breakpoint on probes.  */
12966   return bkpt_probe_decode_location (b, location, search_pspace);
12967 }
12968
12969 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
12970
12971 /* Dprintf breakpoint_ops methods.  */
12972
12973 static void
12974 dprintf_re_set (struct breakpoint *b)
12975 {
12976   breakpoint_re_set_default (b);
12977
12978   /* extra_string should never be non-NULL for dprintf.  */
12979   gdb_assert (b->extra_string != NULL);
12980
12981   /* 1 - connect to target 1, that can run breakpoint commands.
12982      2 - create a dprintf, which resolves fine.
12983      3 - disconnect from target 1
12984      4 - connect to target 2, that can NOT run breakpoint commands.
12985
12986      After steps #3/#4, you'll want the dprintf command list to
12987      be updated, because target 1 and 2 may well return different
12988      answers for target_can_run_breakpoint_commands().
12989      Given absence of finer grained resetting, we get to do
12990      it all the time.  */
12991   if (b->extra_string != NULL)
12992     update_dprintf_command_list (b);
12993 }
12994
12995 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
12996
12997 static void
12998 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12999 {
13000   fprintf_unfiltered (fp, "dprintf %s,%s",
13001                       event_location_to_string (tp->location.get ()),
13002                       tp->extra_string);
13003   print_recreate_thread (tp, fp);
13004 }
13005
13006 /* Implement the "after_condition_true" breakpoint_ops method for
13007    dprintf.
13008
13009    dprintf's are implemented with regular commands in their command
13010    list, but we run the commands here instead of before presenting the
13011    stop to the user, as dprintf's don't actually cause a stop.  This
13012    also makes it so that the commands of multiple dprintfs at the same
13013    address are all handled.  */
13014
13015 static void
13016 dprintf_after_condition_true (struct bpstats *bs)
13017 {
13018   struct bpstats tmp_bs;
13019   struct bpstats *tmp_bs_p = &tmp_bs;
13020
13021   /* dprintf's never cause a stop.  This wasn't set in the
13022      check_status hook instead because that would make the dprintf's
13023      condition not be evaluated.  */
13024   bs->stop = 0;
13025
13026   /* Run the command list here.  Take ownership of it instead of
13027      copying.  We never want these commands to run later in
13028      bpstat_do_actions, if a breakpoint that causes a stop happens to
13029      be set at same address as this dprintf, or even if running the
13030      commands here throws.  */
13031   tmp_bs.commands = bs->commands;
13032   bs->commands = NULL;
13033
13034   bpstat_do_actions_1 (&tmp_bs_p);
13035
13036   /* 'tmp_bs.commands' will usually be NULL by now, but
13037      bpstat_do_actions_1 may return early without processing the whole
13038      list.  */
13039 }
13040
13041 /* The breakpoint_ops structure to be used on static tracepoints with
13042    markers (`-m').  */
13043
13044 static void
13045 strace_marker_create_sals_from_location (const struct event_location *location,
13046                                          struct linespec_result *canonical,
13047                                          enum bptype type_wanted)
13048 {
13049   struct linespec_sals lsal;
13050   const char *arg_start, *arg;
13051
13052   arg = arg_start = get_linespec_location (location)->spec_string;
13053   lsal.sals = decode_static_tracepoint_spec (&arg);
13054
13055   std::string str (arg_start, arg - arg_start);
13056   const char *ptr = str.c_str ();
13057   canonical->location
13058     = new_linespec_location (&ptr, symbol_name_match_type::FULL);
13059
13060   lsal.canonical
13061     = xstrdup (event_location_to_string (canonical->location.get ()));
13062   canonical->lsals.push_back (std::move (lsal));
13063 }
13064
13065 static void
13066 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13067                                       struct linespec_result *canonical,
13068                                       gdb::unique_xmalloc_ptr<char> cond_string,
13069                                       gdb::unique_xmalloc_ptr<char> extra_string,
13070                                       enum bptype type_wanted,
13071                                       enum bpdisp disposition,
13072                                       int thread,
13073                                       int task, int ignore_count,
13074                                       const struct breakpoint_ops *ops,
13075                                       int from_tty, int enabled,
13076                                       int internal, unsigned flags)
13077 {
13078   const linespec_sals &lsal = canonical->lsals[0];
13079
13080   /* If the user is creating a static tracepoint by marker id
13081      (strace -m MARKER_ID), then store the sals index, so that
13082      breakpoint_re_set can try to match up which of the newly
13083      found markers corresponds to this one, and, don't try to
13084      expand multiple locations for each sal, given than SALS
13085      already should contain all sals for MARKER_ID.  */
13086
13087   for (size_t i = 0; i < lsal.sals.size (); i++)
13088     {
13089       event_location_up location
13090         = copy_event_location (canonical->location.get ());
13091
13092       std::unique_ptr<tracepoint> tp (new tracepoint ());
13093       init_breakpoint_sal (tp.get (), gdbarch, lsal.sals[i],
13094                            std::move (location), NULL,
13095                            std::move (cond_string),
13096                            std::move (extra_string),
13097                            type_wanted, disposition,
13098                            thread, task, ignore_count, ops,
13099                            from_tty, enabled, internal, flags,
13100                            canonical->special_display);
13101       /* Given that its possible to have multiple markers with
13102          the same string id, if the user is creating a static
13103          tracepoint by marker id ("strace -m MARKER_ID"), then
13104          store the sals index, so that breakpoint_re_set can
13105          try to match up which of the newly found markers
13106          corresponds to this one  */
13107       tp->static_trace_marker_id_idx = i;
13108
13109       install_breakpoint (internal, std::move (tp), 0);
13110     }
13111 }
13112
13113 static std::vector<symtab_and_line>
13114 strace_marker_decode_location (struct breakpoint *b,
13115                                const struct event_location *location,
13116                                struct program_space *search_pspace)
13117 {
13118   struct tracepoint *tp = (struct tracepoint *) b;
13119   const char *s = get_linespec_location (location)->spec_string;
13120
13121   std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
13122   if (sals.size () > tp->static_trace_marker_id_idx)
13123     {
13124       sals[0] = sals[tp->static_trace_marker_id_idx];
13125       sals.resize (1);
13126       return sals;
13127     }
13128   else
13129     error (_("marker %s not found"), tp->static_trace_marker_id.c_str ());
13130 }
13131
13132 static struct breakpoint_ops strace_marker_breakpoint_ops;
13133
13134 static int
13135 strace_marker_p (struct breakpoint *b)
13136 {
13137   return b->ops == &strace_marker_breakpoint_ops;
13138 }
13139
13140 /* Delete a breakpoint and clean up all traces of it in the data
13141    structures.  */
13142
13143 void
13144 delete_breakpoint (struct breakpoint *bpt)
13145 {
13146   struct breakpoint *b;
13147
13148   gdb_assert (bpt != NULL);
13149
13150   /* Has this bp already been deleted?  This can happen because
13151      multiple lists can hold pointers to bp's.  bpstat lists are
13152      especial culprits.
13153
13154      One example of this happening is a watchpoint's scope bp.  When
13155      the scope bp triggers, we notice that the watchpoint is out of
13156      scope, and delete it.  We also delete its scope bp.  But the
13157      scope bp is marked "auto-deleting", and is already on a bpstat.
13158      That bpstat is then checked for auto-deleting bp's, which are
13159      deleted.
13160
13161      A real solution to this problem might involve reference counts in
13162      bp's, and/or giving them pointers back to their referencing
13163      bpstat's, and teaching delete_breakpoint to only free a bp's
13164      storage when no more references were extent.  A cheaper bandaid
13165      was chosen.  */
13166   if (bpt->type == bp_none)
13167     return;
13168
13169   /* At least avoid this stale reference until the reference counting
13170      of breakpoints gets resolved.  */
13171   if (bpt->related_breakpoint != bpt)
13172     {
13173       struct breakpoint *related;
13174       struct watchpoint *w;
13175
13176       if (bpt->type == bp_watchpoint_scope)
13177         w = (struct watchpoint *) bpt->related_breakpoint;
13178       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13179         w = (struct watchpoint *) bpt;
13180       else
13181         w = NULL;
13182       if (w != NULL)
13183         watchpoint_del_at_next_stop (w);
13184
13185       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13186       for (related = bpt; related->related_breakpoint != bpt;
13187            related = related->related_breakpoint);
13188       related->related_breakpoint = bpt->related_breakpoint;
13189       bpt->related_breakpoint = bpt;
13190     }
13191
13192   /* watch_command_1 creates a watchpoint but only sets its number if
13193      update_watchpoint succeeds in creating its bp_locations.  If there's
13194      a problem in that process, we'll be asked to delete the half-created
13195      watchpoint.  In that case, don't announce the deletion.  */
13196   if (bpt->number)
13197     gdb::observers::breakpoint_deleted.notify (bpt);
13198
13199   if (breakpoint_chain == bpt)
13200     breakpoint_chain = bpt->next;
13201
13202   ALL_BREAKPOINTS (b)
13203     if (b->next == bpt)
13204     {
13205       b->next = bpt->next;
13206       break;
13207     }
13208
13209   /* Be sure no bpstat's are pointing at the breakpoint after it's
13210      been freed.  */
13211   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13212      in all threads for now.  Note that we cannot just remove bpstats
13213      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13214      commands are associated with the bpstat; if we remove it here,
13215      then the later call to bpstat_do_actions (&stop_bpstat); in
13216      event-top.c won't do anything, and temporary breakpoints with
13217      commands won't work.  */
13218
13219   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13220
13221   /* Now that breakpoint is removed from breakpoint list, update the
13222      global location list.  This will remove locations that used to
13223      belong to this breakpoint.  Do this before freeing the breakpoint
13224      itself, since remove_breakpoint looks at location's owner.  It
13225      might be better design to have location completely
13226      self-contained, but it's not the case now.  */
13227   update_global_location_list (UGLL_DONT_INSERT);
13228
13229   /* On the chance that someone will soon try again to delete this
13230      same bp, we mark it as deleted before freeing its storage.  */
13231   bpt->type = bp_none;
13232   delete bpt;
13233 }
13234
13235 /* Iterator function to call a user-provided callback function once
13236    for each of B and its related breakpoints.  */
13237
13238 static void
13239 iterate_over_related_breakpoints (struct breakpoint *b,
13240                                   gdb::function_view<void (breakpoint *)> function)
13241 {
13242   struct breakpoint *related;
13243
13244   related = b;
13245   do
13246     {
13247       struct breakpoint *next;
13248
13249       /* FUNCTION may delete RELATED.  */
13250       next = related->related_breakpoint;
13251
13252       if (next == related)
13253         {
13254           /* RELATED is the last ring entry.  */
13255           function (related);
13256
13257           /* FUNCTION may have deleted it, so we'd never reach back to
13258              B.  There's nothing left to do anyway, so just break
13259              out.  */
13260           break;
13261         }
13262       else
13263         function (related);
13264
13265       related = next;
13266     }
13267   while (related != b);
13268 }
13269
13270 static void
13271 delete_command (const char *arg, int from_tty)
13272 {
13273   struct breakpoint *b, *b_tmp;
13274
13275   dont_repeat ();
13276
13277   if (arg == 0)
13278     {
13279       int breaks_to_delete = 0;
13280
13281       /* Delete all breakpoints if no argument.  Do not delete
13282          internal breakpoints, these have to be deleted with an
13283          explicit breakpoint number argument.  */
13284       ALL_BREAKPOINTS (b)
13285         if (user_breakpoint_p (b))
13286           {
13287             breaks_to_delete = 1;
13288             break;
13289           }
13290
13291       /* Ask user only if there are some breakpoints to delete.  */
13292       if (!from_tty
13293           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13294         {
13295           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13296             if (user_breakpoint_p (b))
13297               delete_breakpoint (b);
13298         }
13299     }
13300   else
13301     map_breakpoint_numbers
13302       (arg, [&] (breakpoint *b)
13303        {
13304          iterate_over_related_breakpoints (b, delete_breakpoint);
13305        });
13306 }
13307
13308 /* Return true if all locations of B bound to PSPACE are pending.  If
13309    PSPACE is NULL, all locations of all program spaces are
13310    considered.  */
13311
13312 static int
13313 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13314 {
13315   struct bp_location *loc;
13316
13317   for (loc = b->loc; loc != NULL; loc = loc->next)
13318     if ((pspace == NULL
13319          || loc->pspace == pspace)
13320         && !loc->shlib_disabled
13321         && !loc->pspace->executing_startup)
13322       return 0;
13323   return 1;
13324 }
13325
13326 /* Subroutine of update_breakpoint_locations to simplify it.
13327    Return non-zero if multiple fns in list LOC have the same name.
13328    Null names are ignored.  */
13329
13330 static int
13331 ambiguous_names_p (struct bp_location *loc)
13332 {
13333   struct bp_location *l;
13334   htab_t htab = htab_create_alloc (13, htab_hash_string, streq_hash, NULL,
13335                                    xcalloc, xfree);
13336
13337   for (l = loc; l != NULL; l = l->next)
13338     {
13339       const char **slot;
13340       const char *name = l->function_name;
13341
13342       /* Allow for some names to be NULL, ignore them.  */
13343       if (name == NULL)
13344         continue;
13345
13346       slot = (const char **) htab_find_slot (htab, (const void *) name,
13347                                              INSERT);
13348       /* NOTE: We can assume slot != NULL here because xcalloc never
13349          returns NULL.  */
13350       if (*slot != NULL)
13351         {
13352           htab_delete (htab);
13353           return 1;
13354         }
13355       *slot = name;
13356     }
13357
13358   htab_delete (htab);
13359   return 0;
13360 }
13361
13362 /* When symbols change, it probably means the sources changed as well,
13363    and it might mean the static tracepoint markers are no longer at
13364    the same address or line numbers they used to be at last we
13365    checked.  Losing your static tracepoints whenever you rebuild is
13366    undesirable.  This function tries to resync/rematch gdb static
13367    tracepoints with the markers on the target, for static tracepoints
13368    that have not been set by marker id.  Static tracepoint that have
13369    been set by marker id are reset by marker id in breakpoint_re_set.
13370    The heuristic is:
13371
13372    1) For a tracepoint set at a specific address, look for a marker at
13373    the old PC.  If one is found there, assume to be the same marker.
13374    If the name / string id of the marker found is different from the
13375    previous known name, assume that means the user renamed the marker
13376    in the sources, and output a warning.
13377
13378    2) For a tracepoint set at a given line number, look for a marker
13379    at the new address of the old line number.  If one is found there,
13380    assume to be the same marker.  If the name / string id of the
13381    marker found is different from the previous known name, assume that
13382    means the user renamed the marker in the sources, and output a
13383    warning.
13384
13385    3) If a marker is no longer found at the same address or line, it
13386    may mean the marker no longer exists.  But it may also just mean
13387    the code changed a bit.  Maybe the user added a few lines of code
13388    that made the marker move up or down (in line number terms).  Ask
13389    the target for info about the marker with the string id as we knew
13390    it.  If found, update line number and address in the matching
13391    static tracepoint.  This will get confused if there's more than one
13392    marker with the same ID (possible in UST, although unadvised
13393    precisely because it confuses tools).  */
13394
13395 static struct symtab_and_line
13396 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13397 {
13398   struct tracepoint *tp = (struct tracepoint *) b;
13399   struct static_tracepoint_marker marker;
13400   CORE_ADDR pc;
13401
13402   pc = sal.pc;
13403   if (sal.line)
13404     find_line_pc (sal.symtab, sal.line, &pc);
13405
13406   if (target_static_tracepoint_marker_at (pc, &marker))
13407     {
13408       if (tp->static_trace_marker_id != marker.str_id)
13409         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13410                  b->number, tp->static_trace_marker_id.c_str (),
13411                  marker.str_id.c_str ());
13412
13413       tp->static_trace_marker_id = std::move (marker.str_id);
13414
13415       return sal;
13416     }
13417
13418   /* Old marker wasn't found on target at lineno.  Try looking it up
13419      by string ID.  */
13420   if (!sal.explicit_pc
13421       && sal.line != 0
13422       && sal.symtab != NULL
13423       && !tp->static_trace_marker_id.empty ())
13424     {
13425       std::vector<static_tracepoint_marker> markers
13426         = target_static_tracepoint_markers_by_strid
13427             (tp->static_trace_marker_id.c_str ());
13428
13429       if (!markers.empty ())
13430         {
13431           struct symbol *sym;
13432           struct static_tracepoint_marker *tpmarker;
13433           struct ui_out *uiout = current_uiout;
13434           struct explicit_location explicit_loc;
13435
13436           tpmarker = &markers[0];
13437
13438           tp->static_trace_marker_id = std::move (tpmarker->str_id);
13439
13440           warning (_("marker for static tracepoint %d (%s) not "
13441                      "found at previous line number"),
13442                    b->number, tp->static_trace_marker_id.c_str ());
13443
13444           symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
13445           sym = find_pc_sect_function (tpmarker->address, NULL);
13446           uiout->text ("Now in ");
13447           if (sym)
13448             {
13449               uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
13450               uiout->text (" at ");
13451             }
13452           uiout->field_string ("file",
13453                                symtab_to_filename_for_display (sal2.symtab));
13454           uiout->text (":");
13455
13456           if (uiout->is_mi_like_p ())
13457             {
13458               const char *fullname = symtab_to_fullname (sal2.symtab);
13459
13460               uiout->field_string ("fullname", fullname);
13461             }
13462
13463           uiout->field_int ("line", sal2.line);
13464           uiout->text ("\n");
13465
13466           b->loc->line_number = sal2.line;
13467           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13468
13469           b->location.reset (NULL);
13470           initialize_explicit_location (&explicit_loc);
13471           explicit_loc.source_filename
13472             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
13473           explicit_loc.line_offset.offset = b->loc->line_number;
13474           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
13475           b->location = new_explicit_location (&explicit_loc);
13476
13477           /* Might be nice to check if function changed, and warn if
13478              so.  */
13479         }
13480     }
13481   return sal;
13482 }
13483
13484 /* Returns 1 iff locations A and B are sufficiently same that
13485    we don't need to report breakpoint as changed.  */
13486
13487 static int
13488 locations_are_equal (struct bp_location *a, struct bp_location *b)
13489 {
13490   while (a && b)
13491     {
13492       if (a->address != b->address)
13493         return 0;
13494
13495       if (a->shlib_disabled != b->shlib_disabled)
13496         return 0;
13497
13498       if (a->enabled != b->enabled)
13499         return 0;
13500
13501       a = a->next;
13502       b = b->next;
13503     }
13504
13505   if ((a == NULL) != (b == NULL))
13506     return 0;
13507
13508   return 1;
13509 }
13510
13511 /* Split all locations of B that are bound to PSPACE out of B's
13512    location list to a separate list and return that list's head.  If
13513    PSPACE is NULL, hoist out all locations of B.  */
13514
13515 static struct bp_location *
13516 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
13517 {
13518   struct bp_location head;
13519   struct bp_location *i = b->loc;
13520   struct bp_location **i_link = &b->loc;
13521   struct bp_location *hoisted = &head;
13522
13523   if (pspace == NULL)
13524     {
13525       i = b->loc;
13526       b->loc = NULL;
13527       return i;
13528     }
13529
13530   head.next = NULL;
13531
13532   while (i != NULL)
13533     {
13534       if (i->pspace == pspace)
13535         {
13536           *i_link = i->next;
13537           i->next = NULL;
13538           hoisted->next = i;
13539           hoisted = i;
13540         }
13541       else
13542         i_link = &i->next;
13543       i = *i_link;
13544     }
13545
13546   return head.next;
13547 }
13548
13549 /* Create new breakpoint locations for B (a hardware or software
13550    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
13551    zero, then B is a ranged breakpoint.  Only recreates locations for
13552    FILTER_PSPACE.  Locations of other program spaces are left
13553    untouched.  */
13554
13555 void
13556 update_breakpoint_locations (struct breakpoint *b,
13557                              struct program_space *filter_pspace,
13558                              gdb::array_view<const symtab_and_line> sals,
13559                              gdb::array_view<const symtab_and_line> sals_end)
13560 {
13561   struct bp_location *existing_locations;
13562
13563   if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
13564     {
13565       /* Ranged breakpoints have only one start location and one end
13566          location.  */
13567       b->enable_state = bp_disabled;
13568       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13569                            "multiple locations found\n"),
13570                          b->number);
13571       return;
13572     }
13573
13574   /* If there's no new locations, and all existing locations are
13575      pending, don't do anything.  This optimizes the common case where
13576      all locations are in the same shared library, that was unloaded.
13577      We'd like to retain the location, so that when the library is
13578      loaded again, we don't loose the enabled/disabled status of the
13579      individual locations.  */
13580   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
13581     return;
13582
13583   existing_locations = hoist_existing_locations (b, filter_pspace);
13584
13585   for (const auto &sal : sals)
13586     {
13587       struct bp_location *new_loc;
13588
13589       switch_to_program_space_and_thread (sal.pspace);
13590
13591       new_loc = add_location_to_breakpoint (b, &sal);
13592
13593       /* Reparse conditions, they might contain references to the
13594          old symtab.  */
13595       if (b->cond_string != NULL)
13596         {
13597           const char *s;
13598
13599           s = b->cond_string;
13600           TRY
13601             {
13602               new_loc->cond = parse_exp_1 (&s, sal.pc,
13603                                            block_for_pc (sal.pc),
13604                                            0);
13605             }
13606           CATCH (e, RETURN_MASK_ERROR)
13607             {
13608               warning (_("failed to reevaluate condition "
13609                          "for breakpoint %d: %s"), 
13610                        b->number, e.message);
13611               new_loc->enabled = 0;
13612             }
13613           END_CATCH
13614         }
13615
13616       if (!sals_end.empty ())
13617         {
13618           CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13619
13620           new_loc->length = end - sals[0].pc + 1;
13621         }
13622     }
13623
13624   /* If possible, carry over 'disable' status from existing
13625      breakpoints.  */
13626   {
13627     struct bp_location *e = existing_locations;
13628     /* If there are multiple breakpoints with the same function name,
13629        e.g. for inline functions, comparing function names won't work.
13630        Instead compare pc addresses; this is just a heuristic as things
13631        may have moved, but in practice it gives the correct answer
13632        often enough until a better solution is found.  */
13633     int have_ambiguous_names = ambiguous_names_p (b->loc);
13634
13635     for (; e; e = e->next)
13636       {
13637         if (!e->enabled && e->function_name)
13638           {
13639             struct bp_location *l = b->loc;
13640             if (have_ambiguous_names)
13641               {
13642                 for (; l; l = l->next)
13643                   if (breakpoint_locations_match (e, l))
13644                     {
13645                       l->enabled = 0;
13646                       break;
13647                     }
13648               }
13649             else
13650               {
13651                 for (; l; l = l->next)
13652                   if (l->function_name
13653                       && strcmp (e->function_name, l->function_name) == 0)
13654                     {
13655                       l->enabled = 0;
13656                       break;
13657                     }
13658               }
13659           }
13660       }
13661   }
13662
13663   if (!locations_are_equal (existing_locations, b->loc))
13664     gdb::observers::breakpoint_modified.notify (b);
13665 }
13666
13667 /* Find the SaL locations corresponding to the given LOCATION.
13668    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13669
13670 static std::vector<symtab_and_line>
13671 location_to_sals (struct breakpoint *b, struct event_location *location,
13672                   struct program_space *search_pspace, int *found)
13673 {
13674   struct gdb_exception exception = exception_none;
13675
13676   gdb_assert (b->ops != NULL);
13677
13678   std::vector<symtab_and_line> sals;
13679
13680   TRY
13681     {
13682       sals = b->ops->decode_location (b, location, search_pspace);
13683     }
13684   CATCH (e, RETURN_MASK_ERROR)
13685     {
13686       int not_found_and_ok = 0;
13687
13688       exception = e;
13689
13690       /* For pending breakpoints, it's expected that parsing will
13691          fail until the right shared library is loaded.  User has
13692          already told to create pending breakpoints and don't need
13693          extra messages.  If breakpoint is in bp_shlib_disabled
13694          state, then user already saw the message about that
13695          breakpoint being disabled, and don't want to see more
13696          errors.  */
13697       if (e.error == NOT_FOUND_ERROR
13698           && (b->condition_not_parsed
13699               || (b->loc != NULL
13700                   && search_pspace != NULL
13701                   && b->loc->pspace != search_pspace)
13702               || (b->loc && b->loc->shlib_disabled)
13703               || (b->loc && b->loc->pspace->executing_startup)
13704               || b->enable_state == bp_disabled))
13705         not_found_and_ok = 1;
13706
13707       if (!not_found_and_ok)
13708         {
13709           /* We surely don't want to warn about the same breakpoint
13710              10 times.  One solution, implemented here, is disable
13711              the breakpoint on error.  Another solution would be to
13712              have separate 'warning emitted' flag.  Since this
13713              happens only when a binary has changed, I don't know
13714              which approach is better.  */
13715           b->enable_state = bp_disabled;
13716           throw_exception (e);
13717         }
13718     }
13719   END_CATCH
13720
13721   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13722     {
13723       for (auto &sal : sals)
13724         resolve_sal_pc (&sal);
13725       if (b->condition_not_parsed && b->extra_string != NULL)
13726         {
13727           char *cond_string, *extra_string;
13728           int thread, task;
13729
13730           find_condition_and_thread (b->extra_string, sals[0].pc,
13731                                      &cond_string, &thread, &task,
13732                                      &extra_string);
13733           gdb_assert (b->cond_string == NULL);
13734           if (cond_string)
13735             b->cond_string = cond_string;
13736           b->thread = thread;
13737           b->task = task;
13738           if (extra_string)
13739             {
13740               xfree (b->extra_string);
13741               b->extra_string = extra_string;
13742             }
13743           b->condition_not_parsed = 0;
13744         }
13745
13746       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13747         sals[0] = update_static_tracepoint (b, sals[0]);
13748
13749       *found = 1;
13750     }
13751   else
13752     *found = 0;
13753
13754   return sals;
13755 }
13756
13757 /* The default re_set method, for typical hardware or software
13758    breakpoints.  Reevaluate the breakpoint and recreate its
13759    locations.  */
13760
13761 static void
13762 breakpoint_re_set_default (struct breakpoint *b)
13763 {
13764   struct program_space *filter_pspace = current_program_space;
13765   std::vector<symtab_and_line> expanded, expanded_end;
13766
13767   int found;
13768   std::vector<symtab_and_line> sals = location_to_sals (b, b->location.get (),
13769                                                         filter_pspace, &found);
13770   if (found)
13771     expanded = std::move (sals);
13772
13773   if (b->location_range_end != NULL)
13774     {
13775       std::vector<symtab_and_line> sals_end
13776         = location_to_sals (b, b->location_range_end.get (),
13777                             filter_pspace, &found);
13778       if (found)
13779         expanded_end = std::move (sals_end);
13780     }
13781
13782   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
13783 }
13784
13785 /* Default method for creating SALs from an address string.  It basically
13786    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13787
13788 static void
13789 create_sals_from_location_default (const struct event_location *location,
13790                                    struct linespec_result *canonical,
13791                                    enum bptype type_wanted)
13792 {
13793   parse_breakpoint_sals (location, canonical);
13794 }
13795
13796 /* Call create_breakpoints_sal for the given arguments.  This is the default
13797    function for the `create_breakpoints_sal' method of
13798    breakpoint_ops.  */
13799
13800 static void
13801 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13802                                 struct linespec_result *canonical,
13803                                 gdb::unique_xmalloc_ptr<char> cond_string,
13804                                 gdb::unique_xmalloc_ptr<char> extra_string,
13805                                 enum bptype type_wanted,
13806                                 enum bpdisp disposition,
13807                                 int thread,
13808                                 int task, int ignore_count,
13809                                 const struct breakpoint_ops *ops,
13810                                 int from_tty, int enabled,
13811                                 int internal, unsigned flags)
13812 {
13813   create_breakpoints_sal (gdbarch, canonical,
13814                           std::move (cond_string),
13815                           std::move (extra_string),
13816                           type_wanted, disposition,
13817                           thread, task, ignore_count, ops, from_tty,
13818                           enabled, internal, flags);
13819 }
13820
13821 /* Decode the line represented by S by calling decode_line_full.  This is the
13822    default function for the `decode_location' method of breakpoint_ops.  */
13823
13824 static std::vector<symtab_and_line>
13825 decode_location_default (struct breakpoint *b,
13826                          const struct event_location *location,
13827                          struct program_space *search_pspace)
13828 {
13829   struct linespec_result canonical;
13830
13831   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
13832                     (struct symtab *) NULL, 0,
13833                     &canonical, multiple_symbols_all,
13834                     b->filter);
13835
13836   /* We should get 0 or 1 resulting SALs.  */
13837   gdb_assert (canonical.lsals.size () < 2);
13838
13839   if (!canonical.lsals.empty ())
13840     {
13841       const linespec_sals &lsal = canonical.lsals[0];
13842       return std::move (lsal.sals);
13843     }
13844   return {};
13845 }
13846
13847 /* Reset a breakpoint.  */
13848
13849 static void
13850 breakpoint_re_set_one (breakpoint *b)
13851 {
13852   input_radix = b->input_radix;
13853   set_language (b->language);
13854
13855   b->ops->re_set (b);
13856 }
13857
13858 /* Re-set breakpoint locations for the current program space.
13859    Locations bound to other program spaces are left untouched.  */
13860
13861 void
13862 breakpoint_re_set (void)
13863 {
13864   struct breakpoint *b, *b_tmp;
13865
13866   {
13867     scoped_restore_current_language save_language;
13868     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
13869     scoped_restore_current_pspace_and_thread restore_pspace_thread;
13870
13871     /* Note: we must not try to insert locations until after all
13872        breakpoints have been re-set.  Otherwise, e.g., when re-setting
13873        breakpoint 1, we'd insert the locations of breakpoint 2, which
13874        hadn't been re-set yet, and thus may have stale locations.  */
13875
13876     ALL_BREAKPOINTS_SAFE (b, b_tmp)
13877       {
13878         TRY
13879           {
13880             breakpoint_re_set_one (b);
13881           }
13882         CATCH (ex, RETURN_MASK_ALL)
13883           {
13884             exception_fprintf (gdb_stderr, ex,
13885                                "Error in re-setting breakpoint %d: ",
13886                                b->number);
13887           }
13888         END_CATCH
13889       }
13890
13891     jit_breakpoint_re_set ();
13892   }
13893
13894   create_overlay_event_breakpoint ();
13895   create_longjmp_master_breakpoint ();
13896   create_std_terminate_master_breakpoint ();
13897   create_exception_master_breakpoint ();
13898
13899   /* Now we can insert.  */
13900   update_global_location_list (UGLL_MAY_INSERT);
13901 }
13902 \f
13903 /* Reset the thread number of this breakpoint:
13904
13905    - If the breakpoint is for all threads, leave it as-is.
13906    - Else, reset it to the current thread for inferior_ptid.  */
13907 void
13908 breakpoint_re_set_thread (struct breakpoint *b)
13909 {
13910   if (b->thread != -1)
13911     {
13912       if (in_thread_list (inferior_ptid))
13913         b->thread = ptid_to_global_thread_id (inferior_ptid);
13914
13915       /* We're being called after following a fork.  The new fork is
13916          selected as current, and unless this was a vfork will have a
13917          different program space from the original thread.  Reset that
13918          as well.  */
13919       b->loc->pspace = current_program_space;
13920     }
13921 }
13922
13923 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13924    If from_tty is nonzero, it prints a message to that effect,
13925    which ends with a period (no newline).  */
13926
13927 void
13928 set_ignore_count (int bptnum, int count, int from_tty)
13929 {
13930   struct breakpoint *b;
13931
13932   if (count < 0)
13933     count = 0;
13934
13935   ALL_BREAKPOINTS (b)
13936     if (b->number == bptnum)
13937     {
13938       if (is_tracepoint (b))
13939         {
13940           if (from_tty && count != 0)
13941             printf_filtered (_("Ignore count ignored for tracepoint %d."),
13942                              bptnum);
13943           return;
13944         }
13945       
13946       b->ignore_count = count;
13947       if (from_tty)
13948         {
13949           if (count == 0)
13950             printf_filtered (_("Will stop next time "
13951                                "breakpoint %d is reached."),
13952                              bptnum);
13953           else if (count == 1)
13954             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
13955                              bptnum);
13956           else
13957             printf_filtered (_("Will ignore next %d "
13958                                "crossings of breakpoint %d."),
13959                              count, bptnum);
13960         }
13961       gdb::observers::breakpoint_modified.notify (b);
13962       return;
13963     }
13964
13965   error (_("No breakpoint number %d."), bptnum);
13966 }
13967
13968 /* Command to set ignore-count of breakpoint N to COUNT.  */
13969
13970 static void
13971 ignore_command (const char *args, int from_tty)
13972 {
13973   const char *p = args;
13974   int num;
13975
13976   if (p == 0)
13977     error_no_arg (_("a breakpoint number"));
13978
13979   num = get_number (&p);
13980   if (num == 0)
13981     error (_("bad breakpoint number: '%s'"), args);
13982   if (*p == 0)
13983     error (_("Second argument (specified ignore-count) is missing."));
13984
13985   set_ignore_count (num,
13986                     longest_to_int (value_as_long (parse_and_eval (p))),
13987                     from_tty);
13988   if (from_tty)
13989     printf_filtered ("\n");
13990 }
13991 \f
13992
13993 /* Call FUNCTION on each of the breakpoints with numbers in the range
13994    defined by BP_NUM_RANGE (an inclusive range).  */
13995
13996 static void
13997 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
13998                              gdb::function_view<void (breakpoint *)> function)
13999 {
14000   if (bp_num_range.first == 0)
14001     {
14002       warning (_("bad breakpoint number at or near '%d'"),
14003                bp_num_range.first);
14004     }
14005   else
14006     {
14007       struct breakpoint *b, *tmp;
14008
14009       for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
14010         {
14011           bool match = false;
14012
14013           ALL_BREAKPOINTS_SAFE (b, tmp)
14014             if (b->number == i)
14015               {
14016                 match = true;
14017                 function (b);
14018                 break;
14019               }
14020           if (!match)
14021             printf_unfiltered (_("No breakpoint number %d.\n"), i);
14022         }
14023     }
14024 }
14025
14026 /* Call FUNCTION on each of the breakpoints whose numbers are given in
14027    ARGS.  */
14028
14029 static void
14030 map_breakpoint_numbers (const char *args,
14031                         gdb::function_view<void (breakpoint *)> function)
14032 {
14033   if (args == NULL || *args == '\0')
14034     error_no_arg (_("one or more breakpoint numbers"));
14035
14036   number_or_range_parser parser (args);
14037
14038   while (!parser.finished ())
14039     {
14040       int num = parser.get_number ();
14041       map_breakpoint_number_range (std::make_pair (num, num), function);
14042     }
14043 }
14044
14045 /* Return the breakpoint location structure corresponding to the
14046    BP_NUM and LOC_NUM values.  */
14047
14048 static struct bp_location *
14049 find_location_by_number (int bp_num, int loc_num)
14050 {
14051   struct breakpoint *b;
14052
14053   ALL_BREAKPOINTS (b)
14054     if (b->number == bp_num)
14055       {
14056         break;
14057       }
14058
14059   if (!b || b->number != bp_num)
14060     error (_("Bad breakpoint number '%d'"), bp_num);
14061   
14062   if (loc_num == 0)
14063     error (_("Bad breakpoint location number '%d'"), loc_num);
14064
14065   int n = 0;
14066   for (bp_location *loc = b->loc; loc != NULL; loc = loc->next)
14067     if (++n == loc_num)
14068       return loc;
14069
14070   error (_("Bad breakpoint location number '%d'"), loc_num);
14071 }
14072
14073 /* Modes of operation for extract_bp_num.  */
14074 enum class extract_bp_kind
14075 {
14076   /* Extracting a breakpoint number.  */
14077   bp,
14078
14079   /* Extracting a location number.  */
14080   loc,
14081 };
14082
14083 /* Extract a breakpoint or location number (as determined by KIND)
14084    from the string starting at START.  TRAILER is a character which
14085    can be found after the number.  If you don't want a trailer, use
14086    '\0'.  If END_OUT is not NULL, it is set to point after the parsed
14087    string.  This always returns a positive integer.  */
14088
14089 static int
14090 extract_bp_num (extract_bp_kind kind, const char *start,
14091                 int trailer, const char **end_out = NULL)
14092 {
14093   const char *end = start;
14094   int num = get_number_trailer (&end, trailer);
14095   if (num < 0)
14096     error (kind == extract_bp_kind::bp
14097            ? _("Negative breakpoint number '%.*s'")
14098            : _("Negative breakpoint location number '%.*s'"),
14099            int (end - start), start);
14100   if (num == 0)
14101     error (kind == extract_bp_kind::bp
14102            ? _("Bad breakpoint number '%.*s'")
14103            : _("Bad breakpoint location number '%.*s'"),
14104            int (end - start), start);
14105
14106   if (end_out != NULL)
14107     *end_out = end;
14108   return num;
14109 }
14110
14111 /* Extract a breakpoint or location range (as determined by KIND) in
14112    the form NUM1-NUM2 stored at &ARG[arg_offset].  Returns a std::pair
14113    representing the (inclusive) range.  The returned pair's elements
14114    are always positive integers.  */
14115
14116 static std::pair<int, int>
14117 extract_bp_or_bp_range (extract_bp_kind kind,
14118                         const std::string &arg,
14119                         std::string::size_type arg_offset)
14120 {
14121   std::pair<int, int> range;
14122   const char *bp_loc = &arg[arg_offset];
14123   std::string::size_type dash = arg.find ('-', arg_offset);
14124   if (dash != std::string::npos)
14125     {
14126       /* bp_loc is a range (x-z).  */
14127       if (arg.length () == dash + 1)
14128         error (kind == extract_bp_kind::bp
14129                ? _("Bad breakpoint number at or near: '%s'")
14130                : _("Bad breakpoint location number at or near: '%s'"),
14131                bp_loc);
14132
14133       const char *end;
14134       const char *start_first = bp_loc;
14135       const char *start_second = &arg[dash + 1];
14136       range.first = extract_bp_num (kind, start_first, '-');
14137       range.second = extract_bp_num (kind, start_second, '\0', &end);
14138
14139       if (range.first > range.second)
14140         error (kind == extract_bp_kind::bp
14141                ? _("Inverted breakpoint range at '%.*s'")
14142                : _("Inverted breakpoint location range at '%.*s'"),
14143                int (end - start_first), start_first);
14144     }
14145   else
14146     {
14147       /* bp_loc is a single value.  */
14148       range.first = extract_bp_num (kind, bp_loc, '\0');
14149       range.second = range.first;
14150     }
14151   return range;
14152 }
14153
14154 /* Extract the breakpoint/location range specified by ARG.  Returns
14155    the breakpoint range in BP_NUM_RANGE, and the location range in
14156    BP_LOC_RANGE.
14157
14158    ARG may be in any of the following forms:
14159
14160    x     where 'x' is a breakpoint number.
14161    x-y   where 'x' and 'y' specify a breakpoint numbers range.
14162    x.y   where 'x' is a breakpoint number and 'y' a location number.
14163    x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
14164          location number range.
14165 */
14166
14167 static void
14168 extract_bp_number_and_location (const std::string &arg,
14169                                 std::pair<int, int> &bp_num_range,
14170                                 std::pair<int, int> &bp_loc_range)
14171 {
14172   std::string::size_type dot = arg.find ('.');
14173
14174   if (dot != std::string::npos)
14175     {
14176       /* Handle 'x.y' and 'x.y-z' cases.  */
14177
14178       if (arg.length () == dot + 1 || dot == 0)
14179         error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
14180
14181       bp_num_range.first
14182         = extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
14183       bp_num_range.second = bp_num_range.first;
14184
14185       bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
14186                                              arg, dot + 1);
14187     }
14188   else
14189     {
14190       /* Handle x and x-y cases.  */
14191
14192       bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
14193       bp_loc_range.first = 0;
14194       bp_loc_range.second = 0;
14195     }
14196 }
14197
14198 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM.  ENABLE
14199    specifies whether to enable or disable.  */
14200
14201 static void
14202 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
14203 {
14204   struct bp_location *loc = find_location_by_number (bp_num, loc_num);
14205   if (loc != NULL)
14206     {
14207       if (loc->enabled != enable)
14208         {
14209           loc->enabled = enable;
14210           mark_breakpoint_location_modified (loc);
14211         }
14212       if (target_supports_enable_disable_tracepoint ()
14213           && current_trace_status ()->running && loc->owner
14214           && is_tracepoint (loc->owner))
14215         target_disable_tracepoint (loc);
14216     }
14217   update_global_location_list (UGLL_DONT_INSERT);
14218 }
14219
14220 /* Enable or disable a range of breakpoint locations.  BP_NUM is the
14221    number of the breakpoint, and BP_LOC_RANGE specifies the
14222    (inclusive) range of location numbers of that breakpoint to
14223    enable/disable.  ENABLE specifies whether to enable or disable the
14224    location.  */
14225
14226 static void
14227 enable_disable_breakpoint_location_range (int bp_num,
14228                                           std::pair<int, int> &bp_loc_range,
14229                                           bool enable)
14230 {
14231   for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
14232     enable_disable_bp_num_loc (bp_num, i, enable);
14233 }
14234
14235 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14236    If from_tty is nonzero, it prints a message to that effect,
14237    which ends with a period (no newline).  */
14238
14239 void
14240 disable_breakpoint (struct breakpoint *bpt)
14241 {
14242   /* Never disable a watchpoint scope breakpoint; we want to
14243      hit them when we leave scope so we can delete both the
14244      watchpoint and its scope breakpoint at that time.  */
14245   if (bpt->type == bp_watchpoint_scope)
14246     return;
14247
14248   bpt->enable_state = bp_disabled;
14249
14250   /* Mark breakpoint locations modified.  */
14251   mark_breakpoint_modified (bpt);
14252
14253   if (target_supports_enable_disable_tracepoint ()
14254       && current_trace_status ()->running && is_tracepoint (bpt))
14255     {
14256       struct bp_location *location;
14257      
14258       for (location = bpt->loc; location; location = location->next)
14259         target_disable_tracepoint (location);
14260     }
14261
14262   update_global_location_list (UGLL_DONT_INSERT);
14263
14264   gdb::observers::breakpoint_modified.notify (bpt);
14265 }
14266
14267 /* Enable or disable the breakpoint(s) or breakpoint location(s)
14268    specified in ARGS.  ARGS may be in any of the formats handled by
14269    extract_bp_number_and_location.  ENABLE specifies whether to enable
14270    or disable the breakpoints/locations.  */
14271
14272 static void
14273 enable_disable_command (const char *args, int from_tty, bool enable)
14274 {
14275   if (args == 0)
14276     {
14277       struct breakpoint *bpt;
14278
14279       ALL_BREAKPOINTS (bpt)
14280         if (user_breakpoint_p (bpt))
14281           {
14282             if (enable)
14283               enable_breakpoint (bpt);
14284             else
14285               disable_breakpoint (bpt);
14286           }
14287     }
14288   else
14289     {
14290       std::string num = extract_arg (&args);
14291
14292       while (!num.empty ())
14293         {
14294           std::pair<int, int> bp_num_range, bp_loc_range;
14295
14296           extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
14297
14298           if (bp_loc_range.first == bp_loc_range.second
14299               && bp_loc_range.first == 0)
14300             {
14301               /* Handle breakpoint ids with formats 'x' or 'x-z'.  */
14302               map_breakpoint_number_range (bp_num_range,
14303                                            enable
14304                                            ? enable_breakpoint
14305                                            : disable_breakpoint);
14306             }
14307           else
14308             {
14309               /* Handle breakpoint ids with formats 'x.y' or
14310                  'x.y-z'.  */
14311               enable_disable_breakpoint_location_range
14312                 (bp_num_range.first, bp_loc_range, enable);
14313             }
14314           num = extract_arg (&args);
14315         }
14316     }
14317 }
14318
14319 /* The disable command disables the specified breakpoints/locations
14320    (or all defined breakpoints) so they're no longer effective in
14321    stopping the inferior.  ARGS may be in any of the forms defined in
14322    extract_bp_number_and_location.  */
14323
14324 static void
14325 disable_command (const char *args, int from_tty)
14326 {
14327   enable_disable_command (args, from_tty, false);
14328 }
14329
14330 static void
14331 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14332                         int count)
14333 {
14334   int target_resources_ok;
14335
14336   if (bpt->type == bp_hardware_breakpoint)
14337     {
14338       int i;
14339       i = hw_breakpoint_used_count ();
14340       target_resources_ok = 
14341         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14342                                             i + 1, 0);
14343       if (target_resources_ok == 0)
14344         error (_("No hardware breakpoint support in the target."));
14345       else if (target_resources_ok < 0)
14346         error (_("Hardware breakpoints used exceeds limit."));
14347     }
14348
14349   if (is_watchpoint (bpt))
14350     {
14351       /* Initialize it just to avoid a GCC false warning.  */
14352       enum enable_state orig_enable_state = bp_disabled;
14353
14354       TRY
14355         {
14356           struct watchpoint *w = (struct watchpoint *) bpt;
14357
14358           orig_enable_state = bpt->enable_state;
14359           bpt->enable_state = bp_enabled;
14360           update_watchpoint (w, 1 /* reparse */);
14361         }
14362       CATCH (e, RETURN_MASK_ALL)
14363         {
14364           bpt->enable_state = orig_enable_state;
14365           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14366                              bpt->number);
14367           return;
14368         }
14369       END_CATCH
14370     }
14371
14372   bpt->enable_state = bp_enabled;
14373
14374   /* Mark breakpoint locations modified.  */
14375   mark_breakpoint_modified (bpt);
14376
14377   if (target_supports_enable_disable_tracepoint ()
14378       && current_trace_status ()->running && is_tracepoint (bpt))
14379     {
14380       struct bp_location *location;
14381
14382       for (location = bpt->loc; location; location = location->next)
14383         target_enable_tracepoint (location);
14384     }
14385
14386   bpt->disposition = disposition;
14387   bpt->enable_count = count;
14388   update_global_location_list (UGLL_MAY_INSERT);
14389
14390   gdb::observers::breakpoint_modified.notify (bpt);
14391 }
14392
14393
14394 void
14395 enable_breakpoint (struct breakpoint *bpt)
14396 {
14397   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14398 }
14399
14400 /* The enable command enables the specified breakpoints/locations (or
14401    all defined breakpoints) so they once again become (or continue to
14402    be) effective in stopping the inferior.  ARGS may be in any of the
14403    forms defined in extract_bp_number_and_location.  */
14404
14405 static void
14406 enable_command (const char *args, int from_tty)
14407 {
14408   enable_disable_command (args, from_tty, true);
14409 }
14410
14411 static void
14412 enable_once_command (const char *args, int from_tty)
14413 {
14414   map_breakpoint_numbers
14415     (args, [&] (breakpoint *b)
14416      {
14417        iterate_over_related_breakpoints
14418          (b, [&] (breakpoint *bpt)
14419           {
14420             enable_breakpoint_disp (bpt, disp_disable, 1);
14421           });
14422      });
14423 }
14424
14425 static void
14426 enable_count_command (const char *args, int from_tty)
14427 {
14428   int count;
14429
14430   if (args == NULL)
14431     error_no_arg (_("hit count"));
14432
14433   count = get_number (&args);
14434
14435   map_breakpoint_numbers
14436     (args, [&] (breakpoint *b)
14437      {
14438        iterate_over_related_breakpoints
14439          (b, [&] (breakpoint *bpt)
14440           {
14441             enable_breakpoint_disp (bpt, disp_disable, count);
14442           });
14443      });
14444 }
14445
14446 static void
14447 enable_delete_command (const char *args, int from_tty)
14448 {
14449   map_breakpoint_numbers
14450     (args, [&] (breakpoint *b)
14451      {
14452        iterate_over_related_breakpoints
14453          (b, [&] (breakpoint *bpt)
14454           {
14455             enable_breakpoint_disp (bpt, disp_del, 1);
14456           });
14457      });
14458 }
14459 \f
14460 static void
14461 set_breakpoint_cmd (const char *args, int from_tty)
14462 {
14463 }
14464
14465 static void
14466 show_breakpoint_cmd (const char *args, int from_tty)
14467 {
14468 }
14469
14470 /* Invalidate last known value of any hardware watchpoint if
14471    the memory which that value represents has been written to by
14472    GDB itself.  */
14473
14474 static void
14475 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14476                                       CORE_ADDR addr, ssize_t len,
14477                                       const bfd_byte *data)
14478 {
14479   struct breakpoint *bp;
14480
14481   ALL_BREAKPOINTS (bp)
14482     if (bp->enable_state == bp_enabled
14483         && bp->type == bp_hardware_watchpoint)
14484       {
14485         struct watchpoint *wp = (struct watchpoint *) bp;
14486
14487         if (wp->val_valid && wp->val != nullptr)
14488           {
14489             struct bp_location *loc;
14490
14491             for (loc = bp->loc; loc != NULL; loc = loc->next)
14492               if (loc->loc_type == bp_loc_hardware_watchpoint
14493                   && loc->address + loc->length > addr
14494                   && addr + len > loc->address)
14495                 {
14496                   wp->val = NULL;
14497                   wp->val_valid = 0;
14498                 }
14499           }
14500       }
14501 }
14502
14503 /* Create and insert a breakpoint for software single step.  */
14504
14505 void
14506 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14507                                const address_space *aspace,
14508                                CORE_ADDR next_pc)
14509 {
14510   struct thread_info *tp = inferior_thread ();
14511   struct symtab_and_line sal;
14512   CORE_ADDR pc = next_pc;
14513
14514   if (tp->control.single_step_breakpoints == NULL)
14515     {
14516       tp->control.single_step_breakpoints
14517         = new_single_step_breakpoint (tp->global_num, gdbarch);
14518     }
14519
14520   sal = find_pc_line (pc, 0);
14521   sal.pc = pc;
14522   sal.section = find_pc_overlay (pc);
14523   sal.explicit_pc = 1;
14524   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14525
14526   update_global_location_list (UGLL_INSERT);
14527 }
14528
14529 /* Insert single step breakpoints according to the current state.  */
14530
14531 int
14532 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14533 {
14534   struct regcache *regcache = get_current_regcache ();
14535   std::vector<CORE_ADDR> next_pcs;
14536
14537   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14538
14539   if (!next_pcs.empty ())
14540     {
14541       struct frame_info *frame = get_current_frame ();
14542       const address_space *aspace = get_frame_address_space (frame);
14543
14544       for (CORE_ADDR pc : next_pcs)
14545         insert_single_step_breakpoint (gdbarch, aspace, pc);
14546
14547       return 1;
14548     }
14549   else
14550     return 0;
14551 }
14552
14553 /* See breakpoint.h.  */
14554
14555 int
14556 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14557                                        const address_space *aspace,
14558                                        CORE_ADDR pc)
14559 {
14560   struct bp_location *loc;
14561
14562   for (loc = bp->loc; loc != NULL; loc = loc->next)
14563     if (loc->inserted
14564         && breakpoint_location_address_match (loc, aspace, pc))
14565       return 1;
14566
14567   return 0;
14568 }
14569
14570 /* Check whether a software single-step breakpoint is inserted at
14571    PC.  */
14572
14573 int
14574 single_step_breakpoint_inserted_here_p (const address_space *aspace,
14575                                         CORE_ADDR pc)
14576 {
14577   struct breakpoint *bpt;
14578
14579   ALL_BREAKPOINTS (bpt)
14580     {
14581       if (bpt->type == bp_single_step
14582           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
14583         return 1;
14584     }
14585   return 0;
14586 }
14587
14588 /* Tracepoint-specific operations.  */
14589
14590 /* Set tracepoint count to NUM.  */
14591 static void
14592 set_tracepoint_count (int num)
14593 {
14594   tracepoint_count = num;
14595   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14596 }
14597
14598 static void
14599 trace_command (const char *arg, int from_tty)
14600 {
14601   struct breakpoint_ops *ops;
14602
14603   event_location_up location = string_to_event_location (&arg,
14604                                                          current_language);
14605   if (location != NULL
14606       && event_location_type (location.get ()) == PROBE_LOCATION)
14607     ops = &tracepoint_probe_breakpoint_ops;
14608   else
14609     ops = &tracepoint_breakpoint_ops;
14610
14611   create_breakpoint (get_current_arch (),
14612                      location.get (),
14613                      NULL, 0, arg, 1 /* parse arg */,
14614                      0 /* tempflag */,
14615                      bp_tracepoint /* type_wanted */,
14616                      0 /* Ignore count */,
14617                      pending_break_support,
14618                      ops,
14619                      from_tty,
14620                      1 /* enabled */,
14621                      0 /* internal */, 0);
14622 }
14623
14624 static void
14625 ftrace_command (const char *arg, int from_tty)
14626 {
14627   event_location_up location = string_to_event_location (&arg,
14628                                                          current_language);
14629   create_breakpoint (get_current_arch (),
14630                      location.get (),
14631                      NULL, 0, arg, 1 /* parse arg */,
14632                      0 /* tempflag */,
14633                      bp_fast_tracepoint /* type_wanted */,
14634                      0 /* Ignore count */,
14635                      pending_break_support,
14636                      &tracepoint_breakpoint_ops,
14637                      from_tty,
14638                      1 /* enabled */,
14639                      0 /* internal */, 0);
14640 }
14641
14642 /* strace command implementation.  Creates a static tracepoint.  */
14643
14644 static void
14645 strace_command (const char *arg, int from_tty)
14646 {
14647   struct breakpoint_ops *ops;
14648   event_location_up location;
14649
14650   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14651      or with a normal static tracepoint.  */
14652   if (arg && startswith (arg, "-m") && isspace (arg[2]))
14653     {
14654       ops = &strace_marker_breakpoint_ops;
14655       location = new_linespec_location (&arg, symbol_name_match_type::FULL);
14656     }
14657   else
14658     {
14659       ops = &tracepoint_breakpoint_ops;
14660       location = string_to_event_location (&arg, current_language);
14661     }
14662
14663   create_breakpoint (get_current_arch (),
14664                      location.get (),
14665                      NULL, 0, arg, 1 /* parse arg */,
14666                      0 /* tempflag */,
14667                      bp_static_tracepoint /* type_wanted */,
14668                      0 /* Ignore count */,
14669                      pending_break_support,
14670                      ops,
14671                      from_tty,
14672                      1 /* enabled */,
14673                      0 /* internal */, 0);
14674 }
14675
14676 /* Set up a fake reader function that gets command lines from a linked
14677    list that was acquired during tracepoint uploading.  */
14678
14679 static struct uploaded_tp *this_utp;
14680 static int next_cmd;
14681
14682 static char *
14683 read_uploaded_action (void)
14684 {
14685   char *rslt = nullptr;
14686
14687   if (next_cmd < this_utp->cmd_strings.size ())
14688     {
14689       rslt = this_utp->cmd_strings[next_cmd];
14690       next_cmd++;
14691     }
14692
14693   return rslt;
14694 }
14695
14696 /* Given information about a tracepoint as recorded on a target (which
14697    can be either a live system or a trace file), attempt to create an
14698    equivalent GDB tracepoint.  This is not a reliable process, since
14699    the target does not necessarily have all the information used when
14700    the tracepoint was originally defined.  */
14701   
14702 struct tracepoint *
14703 create_tracepoint_from_upload (struct uploaded_tp *utp)
14704 {
14705   const char *addr_str;
14706   char small_buf[100];
14707   struct tracepoint *tp;
14708
14709   if (utp->at_string)
14710     addr_str = utp->at_string;
14711   else
14712     {
14713       /* In the absence of a source location, fall back to raw
14714          address.  Since there is no way to confirm that the address
14715          means the same thing as when the trace was started, warn the
14716          user.  */
14717       warning (_("Uploaded tracepoint %d has no "
14718                  "source location, using raw address"),
14719                utp->number);
14720       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14721       addr_str = small_buf;
14722     }
14723
14724   /* There's not much we can do with a sequence of bytecodes.  */
14725   if (utp->cond && !utp->cond_string)
14726     warning (_("Uploaded tracepoint %d condition "
14727                "has no source form, ignoring it"),
14728              utp->number);
14729
14730   event_location_up location = string_to_event_location (&addr_str,
14731                                                          current_language);
14732   if (!create_breakpoint (get_current_arch (),
14733                           location.get (),
14734                           utp->cond_string, -1, addr_str,
14735                           0 /* parse cond/thread */,
14736                           0 /* tempflag */,
14737                           utp->type /* type_wanted */,
14738                           0 /* Ignore count */,
14739                           pending_break_support,
14740                           &tracepoint_breakpoint_ops,
14741                           0 /* from_tty */,
14742                           utp->enabled /* enabled */,
14743                           0 /* internal */,
14744                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14745     return NULL;
14746
14747   /* Get the tracepoint we just created.  */
14748   tp = get_tracepoint (tracepoint_count);
14749   gdb_assert (tp != NULL);
14750
14751   if (utp->pass > 0)
14752     {
14753       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14754                  tp->number);
14755
14756       trace_pass_command (small_buf, 0);
14757     }
14758
14759   /* If we have uploaded versions of the original commands, set up a
14760      special-purpose "reader" function and call the usual command line
14761      reader, then pass the result to the breakpoint command-setting
14762      function.  */
14763   if (!utp->cmd_strings.empty ())
14764     {
14765       counted_command_line cmd_list;
14766
14767       this_utp = utp;
14768       next_cmd = 0;
14769
14770       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL);
14771
14772       breakpoint_set_commands (tp, std::move (cmd_list));
14773     }
14774   else if (!utp->actions.empty ()
14775            || !utp->step_actions.empty ())
14776     warning (_("Uploaded tracepoint %d actions "
14777                "have no source form, ignoring them"),
14778              utp->number);
14779
14780   /* Copy any status information that might be available.  */
14781   tp->hit_count = utp->hit_count;
14782   tp->traceframe_usage = utp->traceframe_usage;
14783
14784   return tp;
14785 }
14786   
14787 /* Print information on tracepoint number TPNUM_EXP, or all if
14788    omitted.  */
14789
14790 static void
14791 info_tracepoints_command (const char *args, int from_tty)
14792 {
14793   struct ui_out *uiout = current_uiout;
14794   int num_printed;
14795
14796   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14797
14798   if (num_printed == 0)
14799     {
14800       if (args == NULL || *args == '\0')
14801         uiout->message ("No tracepoints.\n");
14802       else
14803         uiout->message ("No tracepoint matching '%s'.\n", args);
14804     }
14805
14806   default_collect_info ();
14807 }
14808
14809 /* The 'enable trace' command enables tracepoints.
14810    Not supported by all targets.  */
14811 static void
14812 enable_trace_command (const char *args, int from_tty)
14813 {
14814   enable_command (args, from_tty);
14815 }
14816
14817 /* The 'disable trace' command disables tracepoints.
14818    Not supported by all targets.  */
14819 static void
14820 disable_trace_command (const char *args, int from_tty)
14821 {
14822   disable_command (args, from_tty);
14823 }
14824
14825 /* Remove a tracepoint (or all if no argument).  */
14826 static void
14827 delete_trace_command (const char *arg, int from_tty)
14828 {
14829   struct breakpoint *b, *b_tmp;
14830
14831   dont_repeat ();
14832
14833   if (arg == 0)
14834     {
14835       int breaks_to_delete = 0;
14836
14837       /* Delete all breakpoints if no argument.
14838          Do not delete internal or call-dummy breakpoints, these
14839          have to be deleted with an explicit breakpoint number 
14840          argument.  */
14841       ALL_TRACEPOINTS (b)
14842         if (is_tracepoint (b) && user_breakpoint_p (b))
14843           {
14844             breaks_to_delete = 1;
14845             break;
14846           }
14847
14848       /* Ask user only if there are some breakpoints to delete.  */
14849       if (!from_tty
14850           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14851         {
14852           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14853             if (is_tracepoint (b) && user_breakpoint_p (b))
14854               delete_breakpoint (b);
14855         }
14856     }
14857   else
14858     map_breakpoint_numbers
14859       (arg, [&] (breakpoint *b)
14860        {
14861          iterate_over_related_breakpoints (b, delete_breakpoint);
14862        });
14863 }
14864
14865 /* Helper function for trace_pass_command.  */
14866
14867 static void
14868 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14869 {
14870   tp->pass_count = count;
14871   gdb::observers::breakpoint_modified.notify (tp);
14872   if (from_tty)
14873     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
14874                      tp->number, count);
14875 }
14876
14877 /* Set passcount for tracepoint.
14878
14879    First command argument is passcount, second is tracepoint number.
14880    If tracepoint number omitted, apply to most recently defined.
14881    Also accepts special argument "all".  */
14882
14883 static void
14884 trace_pass_command (const char *args, int from_tty)
14885 {
14886   struct tracepoint *t1;
14887   ULONGEST count;
14888
14889   if (args == 0 || *args == 0)
14890     error (_("passcount command requires an "
14891              "argument (count + optional TP num)"));
14892
14893   count = strtoulst (args, &args, 10);  /* Count comes first, then TP num.  */
14894
14895   args = skip_spaces (args);
14896   if (*args && strncasecmp (args, "all", 3) == 0)
14897     {
14898       struct breakpoint *b;
14899
14900       args += 3;                        /* Skip special argument "all".  */
14901       if (*args)
14902         error (_("Junk at end of arguments."));
14903
14904       ALL_TRACEPOINTS (b)
14905       {
14906         t1 = (struct tracepoint *) b;
14907         trace_pass_set_count (t1, count, from_tty);
14908       }
14909     }
14910   else if (*args == '\0')
14911     {
14912       t1 = get_tracepoint_by_number (&args, NULL);
14913       if (t1)
14914         trace_pass_set_count (t1, count, from_tty);
14915     }
14916   else
14917     {
14918       number_or_range_parser parser (args);
14919       while (!parser.finished ())
14920         {
14921           t1 = get_tracepoint_by_number (&args, &parser);
14922           if (t1)
14923             trace_pass_set_count (t1, count, from_tty);
14924         }
14925     }
14926 }
14927
14928 struct tracepoint *
14929 get_tracepoint (int num)
14930 {
14931   struct breakpoint *t;
14932
14933   ALL_TRACEPOINTS (t)
14934     if (t->number == num)
14935       return (struct tracepoint *) t;
14936
14937   return NULL;
14938 }
14939
14940 /* Find the tracepoint with the given target-side number (which may be
14941    different from the tracepoint number after disconnecting and
14942    reconnecting).  */
14943
14944 struct tracepoint *
14945 get_tracepoint_by_number_on_target (int num)
14946 {
14947   struct breakpoint *b;
14948
14949   ALL_TRACEPOINTS (b)
14950     {
14951       struct tracepoint *t = (struct tracepoint *) b;
14952
14953       if (t->number_on_target == num)
14954         return t;
14955     }
14956
14957   return NULL;
14958 }
14959
14960 /* Utility: parse a tracepoint number and look it up in the list.
14961    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14962    If the argument is missing, the most recent tracepoint
14963    (tracepoint_count) is returned.  */
14964
14965 struct tracepoint *
14966 get_tracepoint_by_number (const char **arg,
14967                           number_or_range_parser *parser)
14968 {
14969   struct breakpoint *t;
14970   int tpnum;
14971   const char *instring = arg == NULL ? NULL : *arg;
14972
14973   if (parser != NULL)
14974     {
14975       gdb_assert (!parser->finished ());
14976       tpnum = parser->get_number ();
14977     }
14978   else if (arg == NULL || *arg == NULL || ! **arg)
14979     tpnum = tracepoint_count;
14980   else
14981     tpnum = get_number (arg);
14982
14983   if (tpnum <= 0)
14984     {
14985       if (instring && *instring)
14986         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
14987                          instring);
14988       else
14989         printf_filtered (_("No previous tracepoint\n"));
14990       return NULL;
14991     }
14992
14993   ALL_TRACEPOINTS (t)
14994     if (t->number == tpnum)
14995     {
14996       return (struct tracepoint *) t;
14997     }
14998
14999   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15000   return NULL;
15001 }
15002
15003 void
15004 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15005 {
15006   if (b->thread != -1)
15007     fprintf_unfiltered (fp, " thread %d", b->thread);
15008
15009   if (b->task != 0)
15010     fprintf_unfiltered (fp, " task %d", b->task);
15011
15012   fprintf_unfiltered (fp, "\n");
15013 }
15014
15015 /* Save information on user settable breakpoints (watchpoints, etc) to
15016    a new script file named FILENAME.  If FILTER is non-NULL, call it
15017    on each breakpoint and only include the ones for which it returns
15018    non-zero.  */
15019
15020 static void
15021 save_breakpoints (const char *filename, int from_tty,
15022                   int (*filter) (const struct breakpoint *))
15023 {
15024   struct breakpoint *tp;
15025   int any = 0;
15026   int extra_trace_bits = 0;
15027
15028   if (filename == 0 || *filename == 0)
15029     error (_("Argument required (file name in which to save)"));
15030
15031   /* See if we have anything to save.  */
15032   ALL_BREAKPOINTS (tp)
15033   {
15034     /* Skip internal and momentary breakpoints.  */
15035     if (!user_breakpoint_p (tp))
15036       continue;
15037
15038     /* If we have a filter, only save the breakpoints it accepts.  */
15039     if (filter && !filter (tp))
15040       continue;
15041
15042     any = 1;
15043
15044     if (is_tracepoint (tp))
15045       {
15046         extra_trace_bits = 1;
15047
15048         /* We can stop searching.  */
15049         break;
15050       }
15051   }
15052
15053   if (!any)
15054     {
15055       warning (_("Nothing to save."));
15056       return;
15057     }
15058
15059   gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
15060
15061   stdio_file fp;
15062
15063   if (!fp.open (expanded_filename.get (), "w"))
15064     error (_("Unable to open file '%s' for saving (%s)"),
15065            expanded_filename.get (), safe_strerror (errno));
15066
15067   if (extra_trace_bits)
15068     save_trace_state_variables (&fp);
15069
15070   ALL_BREAKPOINTS (tp)
15071   {
15072     /* Skip internal and momentary breakpoints.  */
15073     if (!user_breakpoint_p (tp))
15074       continue;
15075
15076     /* If we have a filter, only save the breakpoints it accepts.  */
15077     if (filter && !filter (tp))
15078       continue;
15079
15080     tp->ops->print_recreate (tp, &fp);
15081
15082     /* Note, we can't rely on tp->number for anything, as we can't
15083        assume the recreated breakpoint numbers will match.  Use $bpnum
15084        instead.  */
15085
15086     if (tp->cond_string)
15087       fp.printf ("  condition $bpnum %s\n", tp->cond_string);
15088
15089     if (tp->ignore_count)
15090       fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15091
15092     if (tp->type != bp_dprintf && tp->commands)
15093       {
15094         fp.puts ("  commands\n");
15095         
15096         current_uiout->redirect (&fp);
15097         TRY
15098           {
15099             print_command_lines (current_uiout, tp->commands.get (), 2);
15100           }
15101         CATCH (ex, RETURN_MASK_ALL)
15102           {
15103           current_uiout->redirect (NULL);
15104             throw_exception (ex);
15105           }
15106         END_CATCH
15107
15108         current_uiout->redirect (NULL);
15109         fp.puts ("  end\n");
15110       }
15111
15112     if (tp->enable_state == bp_disabled)
15113       fp.puts ("disable $bpnum\n");
15114
15115     /* If this is a multi-location breakpoint, check if the locations
15116        should be individually disabled.  Watchpoint locations are
15117        special, and not user visible.  */
15118     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15119       {
15120         struct bp_location *loc;
15121         int n = 1;
15122
15123         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15124           if (!loc->enabled)
15125             fp.printf ("disable $bpnum.%d\n", n);
15126       }
15127   }
15128
15129   if (extra_trace_bits && *default_collect)
15130     fp.printf ("set default-collect %s\n", default_collect);
15131
15132   if (from_tty)
15133     printf_filtered (_("Saved to file '%s'.\n"), expanded_filename.get ());
15134 }
15135
15136 /* The `save breakpoints' command.  */
15137
15138 static void
15139 save_breakpoints_command (const char *args, int from_tty)
15140 {
15141   save_breakpoints (args, from_tty, NULL);
15142 }
15143
15144 /* The `save tracepoints' command.  */
15145
15146 static void
15147 save_tracepoints_command (const char *args, int from_tty)
15148 {
15149   save_breakpoints (args, from_tty, is_tracepoint);
15150 }
15151
15152 /* Create a vector of all tracepoints.  */
15153
15154 VEC(breakpoint_p) *
15155 all_tracepoints (void)
15156 {
15157   VEC(breakpoint_p) *tp_vec = 0;
15158   struct breakpoint *tp;
15159
15160   ALL_TRACEPOINTS (tp)
15161   {
15162     VEC_safe_push (breakpoint_p, tp_vec, tp);
15163   }
15164
15165   return tp_vec;
15166 }
15167
15168 \f
15169 /* This help string is used to consolidate all the help string for specifying
15170    locations used by several commands.  */
15171
15172 #define LOCATION_HELP_STRING \
15173 "Linespecs are colon-separated lists of location parameters, such as\n\
15174 source filename, function name, label name, and line number.\n\
15175 Example: To specify the start of a label named \"the_top\" in the\n\
15176 function \"fact\" in the file \"factorial.c\", use\n\
15177 \"factorial.c:fact:the_top\".\n\
15178 \n\
15179 Address locations begin with \"*\" and specify an exact address in the\n\
15180 program.  Example: To specify the fourth byte past the start function\n\
15181 \"main\", use \"*main + 4\".\n\
15182 \n\
15183 Explicit locations are similar to linespecs but use an option/argument\n\
15184 syntax to specify location parameters.\n\
15185 Example: To specify the start of the label named \"the_top\" in the\n\
15186 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15187 -function fact -label the_top\".\n\
15188 \n\
15189 By default, a specified function is matched against the program's\n\
15190 functions in all scopes.  For C++, this means in all namespaces and\n\
15191 classes.  For Ada, this means in all packages.  E.g., in C++,\n\
15192 \"func()\" matches \"A::func()\", \"A::B::func()\", etc.  The\n\
15193 \"-qualified\" flag overrides this behavior, making GDB interpret the\n\
15194 specified name as a complete fully-qualified name instead.\n"
15195
15196 /* This help string is used for the break, hbreak, tbreak and thbreak
15197    commands.  It is defined as a macro to prevent duplication.
15198    COMMAND should be a string constant containing the name of the
15199    command.  */
15200
15201 #define BREAK_ARGS_HELP(command) \
15202 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15203 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15204 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15205 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15206 `-probe-dtrace' (for a DTrace probe).\n\
15207 LOCATION may be a linespec, address, or explicit location as described\n\
15208 below.\n\
15209 \n\
15210 With no LOCATION, uses current execution address of the selected\n\
15211 stack frame.  This is useful for breaking on return to a stack frame.\n\
15212 \n\
15213 THREADNUM is the number from \"info threads\".\n\
15214 CONDITION is a boolean expression.\n\
15215 \n" LOCATION_HELP_STRING "\n\
15216 Multiple breakpoints at one place are permitted, and useful if their\n\
15217 conditions are different.\n\
15218 \n\
15219 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15220
15221 /* List of subcommands for "catch".  */
15222 static struct cmd_list_element *catch_cmdlist;
15223
15224 /* List of subcommands for "tcatch".  */
15225 static struct cmd_list_element *tcatch_cmdlist;
15226
15227 void
15228 add_catch_command (const char *name, const char *docstring,
15229                    cmd_const_sfunc_ftype *sfunc,
15230                    completer_ftype *completer,
15231                    void *user_data_catch,
15232                    void *user_data_tcatch)
15233 {
15234   struct cmd_list_element *command;
15235
15236   command = add_cmd (name, class_breakpoint, docstring,
15237                      &catch_cmdlist);
15238   set_cmd_sfunc (command, sfunc);
15239   set_cmd_context (command, user_data_catch);
15240   set_cmd_completer (command, completer);
15241
15242   command = add_cmd (name, class_breakpoint, docstring,
15243                      &tcatch_cmdlist);
15244   set_cmd_sfunc (command, sfunc);
15245   set_cmd_context (command, user_data_tcatch);
15246   set_cmd_completer (command, completer);
15247 }
15248
15249 static void
15250 save_command (const char *arg, int from_tty)
15251 {
15252   printf_unfiltered (_("\"save\" must be followed by "
15253                        "the name of a save subcommand.\n"));
15254   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15255 }
15256
15257 struct breakpoint *
15258 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15259                           void *data)
15260 {
15261   struct breakpoint *b, *b_tmp;
15262
15263   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15264     {
15265       if ((*callback) (b, data))
15266         return b;
15267     }
15268
15269   return NULL;
15270 }
15271
15272 /* Zero if any of the breakpoint's locations could be a location where
15273    functions have been inlined, nonzero otherwise.  */
15274
15275 static int
15276 is_non_inline_function (struct breakpoint *b)
15277 {
15278   /* The shared library event breakpoint is set on the address of a
15279      non-inline function.  */
15280   if (b->type == bp_shlib_event)
15281     return 1;
15282
15283   return 0;
15284 }
15285
15286 /* Nonzero if the specified PC cannot be a location where functions
15287    have been inlined.  */
15288
15289 int
15290 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
15291                            const struct target_waitstatus *ws)
15292 {
15293   struct breakpoint *b;
15294   struct bp_location *bl;
15295
15296   ALL_BREAKPOINTS (b)
15297     {
15298       if (!is_non_inline_function (b))
15299         continue;
15300
15301       for (bl = b->loc; bl != NULL; bl = bl->next)
15302         {
15303           if (!bl->shlib_disabled
15304               && bpstat_check_location (bl, aspace, pc, ws))
15305             return 1;
15306         }
15307     }
15308
15309   return 0;
15310 }
15311
15312 /* Remove any references to OBJFILE which is going to be freed.  */
15313
15314 void
15315 breakpoint_free_objfile (struct objfile *objfile)
15316 {
15317   struct bp_location **locp, *loc;
15318
15319   ALL_BP_LOCATIONS (loc, locp)
15320     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15321       loc->symtab = NULL;
15322 }
15323
15324 void
15325 initialize_breakpoint_ops (void)
15326 {
15327   static int initialized = 0;
15328
15329   struct breakpoint_ops *ops;
15330
15331   if (initialized)
15332     return;
15333   initialized = 1;
15334
15335   /* The breakpoint_ops structure to be inherit by all kinds of
15336      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15337      internal and momentary breakpoints, etc.).  */
15338   ops = &bkpt_base_breakpoint_ops;
15339   *ops = base_breakpoint_ops;
15340   ops->re_set = bkpt_re_set;
15341   ops->insert_location = bkpt_insert_location;
15342   ops->remove_location = bkpt_remove_location;
15343   ops->breakpoint_hit = bkpt_breakpoint_hit;
15344   ops->create_sals_from_location = bkpt_create_sals_from_location;
15345   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15346   ops->decode_location = bkpt_decode_location;
15347
15348   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15349   ops = &bkpt_breakpoint_ops;
15350   *ops = bkpt_base_breakpoint_ops;
15351   ops->re_set = bkpt_re_set;
15352   ops->resources_needed = bkpt_resources_needed;
15353   ops->print_it = bkpt_print_it;
15354   ops->print_mention = bkpt_print_mention;
15355   ops->print_recreate = bkpt_print_recreate;
15356
15357   /* Ranged breakpoints.  */
15358   ops = &ranged_breakpoint_ops;
15359   *ops = bkpt_breakpoint_ops;
15360   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15361   ops->resources_needed = resources_needed_ranged_breakpoint;
15362   ops->print_it = print_it_ranged_breakpoint;
15363   ops->print_one = print_one_ranged_breakpoint;
15364   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15365   ops->print_mention = print_mention_ranged_breakpoint;
15366   ops->print_recreate = print_recreate_ranged_breakpoint;
15367
15368   /* Internal breakpoints.  */
15369   ops = &internal_breakpoint_ops;
15370   *ops = bkpt_base_breakpoint_ops;
15371   ops->re_set = internal_bkpt_re_set;
15372   ops->check_status = internal_bkpt_check_status;
15373   ops->print_it = internal_bkpt_print_it;
15374   ops->print_mention = internal_bkpt_print_mention;
15375
15376   /* Momentary breakpoints.  */
15377   ops = &momentary_breakpoint_ops;
15378   *ops = bkpt_base_breakpoint_ops;
15379   ops->re_set = momentary_bkpt_re_set;
15380   ops->check_status = momentary_bkpt_check_status;
15381   ops->print_it = momentary_bkpt_print_it;
15382   ops->print_mention = momentary_bkpt_print_mention;
15383
15384   /* Probe breakpoints.  */
15385   ops = &bkpt_probe_breakpoint_ops;
15386   *ops = bkpt_breakpoint_ops;
15387   ops->insert_location = bkpt_probe_insert_location;
15388   ops->remove_location = bkpt_probe_remove_location;
15389   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15390   ops->decode_location = bkpt_probe_decode_location;
15391
15392   /* Watchpoints.  */
15393   ops = &watchpoint_breakpoint_ops;
15394   *ops = base_breakpoint_ops;
15395   ops->re_set = re_set_watchpoint;
15396   ops->insert_location = insert_watchpoint;
15397   ops->remove_location = remove_watchpoint;
15398   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15399   ops->check_status = check_status_watchpoint;
15400   ops->resources_needed = resources_needed_watchpoint;
15401   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15402   ops->print_it = print_it_watchpoint;
15403   ops->print_mention = print_mention_watchpoint;
15404   ops->print_recreate = print_recreate_watchpoint;
15405   ops->explains_signal = explains_signal_watchpoint;
15406
15407   /* Masked watchpoints.  */
15408   ops = &masked_watchpoint_breakpoint_ops;
15409   *ops = watchpoint_breakpoint_ops;
15410   ops->insert_location = insert_masked_watchpoint;
15411   ops->remove_location = remove_masked_watchpoint;
15412   ops->resources_needed = resources_needed_masked_watchpoint;
15413   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15414   ops->print_it = print_it_masked_watchpoint;
15415   ops->print_one_detail = print_one_detail_masked_watchpoint;
15416   ops->print_mention = print_mention_masked_watchpoint;
15417   ops->print_recreate = print_recreate_masked_watchpoint;
15418
15419   /* Tracepoints.  */
15420   ops = &tracepoint_breakpoint_ops;
15421   *ops = base_breakpoint_ops;
15422   ops->re_set = tracepoint_re_set;
15423   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15424   ops->print_one_detail = tracepoint_print_one_detail;
15425   ops->print_mention = tracepoint_print_mention;
15426   ops->print_recreate = tracepoint_print_recreate;
15427   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15428   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15429   ops->decode_location = tracepoint_decode_location;
15430
15431   /* Probe tracepoints.  */
15432   ops = &tracepoint_probe_breakpoint_ops;
15433   *ops = tracepoint_breakpoint_ops;
15434   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15435   ops->decode_location = tracepoint_probe_decode_location;
15436
15437   /* Static tracepoints with marker (`-m').  */
15438   ops = &strace_marker_breakpoint_ops;
15439   *ops = tracepoint_breakpoint_ops;
15440   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15441   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15442   ops->decode_location = strace_marker_decode_location;
15443
15444   /* Fork catchpoints.  */
15445   ops = &catch_fork_breakpoint_ops;
15446   *ops = base_breakpoint_ops;
15447   ops->insert_location = insert_catch_fork;
15448   ops->remove_location = remove_catch_fork;
15449   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15450   ops->print_it = print_it_catch_fork;
15451   ops->print_one = print_one_catch_fork;
15452   ops->print_mention = print_mention_catch_fork;
15453   ops->print_recreate = print_recreate_catch_fork;
15454
15455   /* Vfork catchpoints.  */
15456   ops = &catch_vfork_breakpoint_ops;
15457   *ops = base_breakpoint_ops;
15458   ops->insert_location = insert_catch_vfork;
15459   ops->remove_location = remove_catch_vfork;
15460   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15461   ops->print_it = print_it_catch_vfork;
15462   ops->print_one = print_one_catch_vfork;
15463   ops->print_mention = print_mention_catch_vfork;
15464   ops->print_recreate = print_recreate_catch_vfork;
15465
15466   /* Exec catchpoints.  */
15467   ops = &catch_exec_breakpoint_ops;
15468   *ops = base_breakpoint_ops;
15469   ops->insert_location = insert_catch_exec;
15470   ops->remove_location = remove_catch_exec;
15471   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15472   ops->print_it = print_it_catch_exec;
15473   ops->print_one = print_one_catch_exec;
15474   ops->print_mention = print_mention_catch_exec;
15475   ops->print_recreate = print_recreate_catch_exec;
15476
15477   /* Solib-related catchpoints.  */
15478   ops = &catch_solib_breakpoint_ops;
15479   *ops = base_breakpoint_ops;
15480   ops->insert_location = insert_catch_solib;
15481   ops->remove_location = remove_catch_solib;
15482   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15483   ops->check_status = check_status_catch_solib;
15484   ops->print_it = print_it_catch_solib;
15485   ops->print_one = print_one_catch_solib;
15486   ops->print_mention = print_mention_catch_solib;
15487   ops->print_recreate = print_recreate_catch_solib;
15488
15489   ops = &dprintf_breakpoint_ops;
15490   *ops = bkpt_base_breakpoint_ops;
15491   ops->re_set = dprintf_re_set;
15492   ops->resources_needed = bkpt_resources_needed;
15493   ops->print_it = bkpt_print_it;
15494   ops->print_mention = bkpt_print_mention;
15495   ops->print_recreate = dprintf_print_recreate;
15496   ops->after_condition_true = dprintf_after_condition_true;
15497   ops->breakpoint_hit = dprintf_breakpoint_hit;
15498 }
15499
15500 /* Chain containing all defined "enable breakpoint" subcommands.  */
15501
15502 static struct cmd_list_element *enablebreaklist = NULL;
15503
15504 void
15505 _initialize_breakpoint (void)
15506 {
15507   struct cmd_list_element *c;
15508
15509   initialize_breakpoint_ops ();
15510
15511   gdb::observers::solib_unloaded.attach (disable_breakpoints_in_unloaded_shlib);
15512   gdb::observers::free_objfile.attach (disable_breakpoints_in_freed_objfile);
15513   gdb::observers::memory_changed.attach (invalidate_bp_value_on_memory_change);
15514
15515   breakpoint_objfile_key
15516     = register_objfile_data_with_cleanup (NULL, free_breakpoint_objfile_data);
15517
15518   breakpoint_chain = 0;
15519   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15520      before a breakpoint is set.  */
15521   breakpoint_count = 0;
15522
15523   tracepoint_count = 0;
15524
15525   add_com ("ignore", class_breakpoint, ignore_command, _("\
15526 Set ignore-count of breakpoint number N to COUNT.\n\
15527 Usage is `ignore N COUNT'."));
15528
15529   add_com ("commands", class_breakpoint, commands_command, _("\
15530 Set commands to be executed when the given breakpoints are hit.\n\
15531 Give a space-separated breakpoint list as argument after \"commands\".\n\
15532 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
15533 (e.g. `5-7').\n\
15534 With no argument, the targeted breakpoint is the last one set.\n\
15535 The commands themselves follow starting on the next line.\n\
15536 Type a line containing \"end\" to indicate the end of them.\n\
15537 Give \"silent\" as the first line to make the breakpoint silent;\n\
15538 then no output is printed when it is hit, except what the commands print."));
15539
15540   c = add_com ("condition", class_breakpoint, condition_command, _("\
15541 Specify breakpoint number N to break only if COND is true.\n\
15542 Usage is `condition N COND', where N is an integer and COND is an\n\
15543 expression to be evaluated whenever breakpoint N is reached."));
15544   set_cmd_completer (c, condition_completer);
15545
15546   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15547 Set a temporary breakpoint.\n\
15548 Like \"break\" except the breakpoint is only temporary,\n\
15549 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15550 by using \"enable delete\" on the breakpoint number.\n\
15551 \n"
15552 BREAK_ARGS_HELP ("tbreak")));
15553   set_cmd_completer (c, location_completer);
15554
15555   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15556 Set a hardware assisted breakpoint.\n\
15557 Like \"break\" except the breakpoint requires hardware support,\n\
15558 some target hardware may not have this support.\n\
15559 \n"
15560 BREAK_ARGS_HELP ("hbreak")));
15561   set_cmd_completer (c, location_completer);
15562
15563   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15564 Set a temporary hardware assisted breakpoint.\n\
15565 Like \"hbreak\" except the breakpoint is only temporary,\n\
15566 so it will be deleted when hit.\n\
15567 \n"
15568 BREAK_ARGS_HELP ("thbreak")));
15569   set_cmd_completer (c, location_completer);
15570
15571   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15572 Enable some breakpoints.\n\
15573 Give breakpoint numbers (separated by spaces) as arguments.\n\
15574 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15575 This is used to cancel the effect of the \"disable\" command.\n\
15576 With a subcommand you can enable temporarily."),
15577                   &enablelist, "enable ", 1, &cmdlist);
15578
15579   add_com_alias ("en", "enable", class_breakpoint, 1);
15580
15581   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15582 Enable some breakpoints.\n\
15583 Give breakpoint numbers (separated by spaces) as arguments.\n\
15584 This is used to cancel the effect of the \"disable\" command.\n\
15585 May be abbreviated to simply \"enable\".\n"),
15586                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15587
15588   add_cmd ("once", no_class, enable_once_command, _("\
15589 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15590 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15591            &enablebreaklist);
15592
15593   add_cmd ("delete", no_class, enable_delete_command, _("\
15594 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15595 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15596            &enablebreaklist);
15597
15598   add_cmd ("count", no_class, enable_count_command, _("\
15599 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15600 If a breakpoint is hit while enabled in this fashion,\n\
15601 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15602            &enablebreaklist);
15603
15604   add_cmd ("delete", no_class, enable_delete_command, _("\
15605 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15606 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15607            &enablelist);
15608
15609   add_cmd ("once", no_class, enable_once_command, _("\
15610 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15611 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15612            &enablelist);
15613
15614   add_cmd ("count", no_class, enable_count_command, _("\
15615 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15616 If a breakpoint is hit while enabled in this fashion,\n\
15617 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15618            &enablelist);
15619
15620   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15621 Disable some breakpoints.\n\
15622 Arguments are breakpoint numbers with spaces in between.\n\
15623 To disable all breakpoints, give no argument.\n\
15624 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15625                   &disablelist, "disable ", 1, &cmdlist);
15626   add_com_alias ("dis", "disable", class_breakpoint, 1);
15627   add_com_alias ("disa", "disable", class_breakpoint, 1);
15628
15629   add_cmd ("breakpoints", class_alias, disable_command, _("\
15630 Disable some breakpoints.\n\
15631 Arguments are breakpoint numbers with spaces in between.\n\
15632 To disable all breakpoints, give no argument.\n\
15633 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15634 This command may be abbreviated \"disable\"."),
15635            &disablelist);
15636
15637   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15638 Delete some breakpoints or auto-display expressions.\n\
15639 Arguments are breakpoint numbers with spaces in between.\n\
15640 To delete all breakpoints, give no argument.\n\
15641 \n\
15642 Also a prefix command for deletion of other GDB objects.\n\
15643 The \"unset\" command is also an alias for \"delete\"."),
15644                   &deletelist, "delete ", 1, &cmdlist);
15645   add_com_alias ("d", "delete", class_breakpoint, 1);
15646   add_com_alias ("del", "delete", class_breakpoint, 1);
15647
15648   add_cmd ("breakpoints", class_alias, delete_command, _("\
15649 Delete some breakpoints or auto-display expressions.\n\
15650 Arguments are breakpoint numbers with spaces in between.\n\
15651 To delete all breakpoints, give no argument.\n\
15652 This command may be abbreviated \"delete\"."),
15653            &deletelist);
15654
15655   add_com ("clear", class_breakpoint, clear_command, _("\
15656 Clear breakpoint at specified location.\n\
15657 Argument may be a linespec, explicit, or address location as described below.\n\
15658 \n\
15659 With no argument, clears all breakpoints in the line that the selected frame\n\
15660 is executing in.\n"
15661 "\n" LOCATION_HELP_STRING "\n\
15662 See also the \"delete\" command which clears breakpoints by number."));
15663   add_com_alias ("cl", "clear", class_breakpoint, 1);
15664
15665   c = add_com ("break", class_breakpoint, break_command, _("\
15666 Set breakpoint at specified location.\n"
15667 BREAK_ARGS_HELP ("break")));
15668   set_cmd_completer (c, location_completer);
15669
15670   add_com_alias ("b", "break", class_run, 1);
15671   add_com_alias ("br", "break", class_run, 1);
15672   add_com_alias ("bre", "break", class_run, 1);
15673   add_com_alias ("brea", "break", class_run, 1);
15674
15675   if (dbx_commands)
15676     {
15677       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15678 Break in function/address or break at a line in the current file."),
15679                              &stoplist, "stop ", 1, &cmdlist);
15680       add_cmd ("in", class_breakpoint, stopin_command,
15681                _("Break in function or address."), &stoplist);
15682       add_cmd ("at", class_breakpoint, stopat_command,
15683                _("Break at a line in the current file."), &stoplist);
15684       add_com ("status", class_info, info_breakpoints_command, _("\
15685 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15686 The \"Type\" column indicates one of:\n\
15687 \tbreakpoint     - normal breakpoint\n\
15688 \twatchpoint     - watchpoint\n\
15689 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15690 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15691 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15692 address and file/line number respectively.\n\
15693 \n\
15694 Convenience variable \"$_\" and default examine address for \"x\"\n\
15695 are set to the address of the last breakpoint listed unless the command\n\
15696 is prefixed with \"server \".\n\n\
15697 Convenience variable \"$bpnum\" contains the number of the last\n\
15698 breakpoint set."));
15699     }
15700
15701   add_info ("breakpoints", info_breakpoints_command, _("\
15702 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15703 The \"Type\" column indicates one of:\n\
15704 \tbreakpoint     - normal breakpoint\n\
15705 \twatchpoint     - watchpoint\n\
15706 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15707 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15708 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15709 address and file/line number respectively.\n\
15710 \n\
15711 Convenience variable \"$_\" and default examine address for \"x\"\n\
15712 are set to the address of the last breakpoint listed unless the command\n\
15713 is prefixed with \"server \".\n\n\
15714 Convenience variable \"$bpnum\" contains the number of the last\n\
15715 breakpoint set."));
15716
15717   add_info_alias ("b", "breakpoints", 1);
15718
15719   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15720 Status of all breakpoints, or breakpoint number NUMBER.\n\
15721 The \"Type\" column indicates one of:\n\
15722 \tbreakpoint     - normal breakpoint\n\
15723 \twatchpoint     - watchpoint\n\
15724 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15725 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15726 \tuntil          - internal breakpoint used by the \"until\" command\n\
15727 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15728 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15729 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15730 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15731 address and file/line number respectively.\n\
15732 \n\
15733 Convenience variable \"$_\" and default examine address for \"x\"\n\
15734 are set to the address of the last breakpoint listed unless the command\n\
15735 is prefixed with \"server \".\n\n\
15736 Convenience variable \"$bpnum\" contains the number of the last\n\
15737 breakpoint set."),
15738            &maintenanceinfolist);
15739
15740   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15741 Set catchpoints to catch events."),
15742                   &catch_cmdlist, "catch ",
15743                   0/*allow-unknown*/, &cmdlist);
15744
15745   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15746 Set temporary catchpoints to catch events."),
15747                   &tcatch_cmdlist, "tcatch ",
15748                   0/*allow-unknown*/, &cmdlist);
15749
15750   add_catch_command ("fork", _("Catch calls to fork."),
15751                      catch_fork_command_1,
15752                      NULL,
15753                      (void *) (uintptr_t) catch_fork_permanent,
15754                      (void *) (uintptr_t) catch_fork_temporary);
15755   add_catch_command ("vfork", _("Catch calls to vfork."),
15756                      catch_fork_command_1,
15757                      NULL,
15758                      (void *) (uintptr_t) catch_vfork_permanent,
15759                      (void *) (uintptr_t) catch_vfork_temporary);
15760   add_catch_command ("exec", _("Catch calls to exec."),
15761                      catch_exec_command_1,
15762                      NULL,
15763                      CATCH_PERMANENT,
15764                      CATCH_TEMPORARY);
15765   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15766 Usage: catch load [REGEX]\n\
15767 If REGEX is given, only stop for libraries matching the regular expression."),
15768                      catch_load_command_1,
15769                      NULL,
15770                      CATCH_PERMANENT,
15771                      CATCH_TEMPORARY);
15772   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15773 Usage: catch unload [REGEX]\n\
15774 If REGEX is given, only stop for libraries matching the regular expression."),
15775                      catch_unload_command_1,
15776                      NULL,
15777                      CATCH_PERMANENT,
15778                      CATCH_TEMPORARY);
15779
15780   c = add_com ("watch", class_breakpoint, watch_command, _("\
15781 Set a watchpoint for an expression.\n\
15782 Usage: watch [-l|-location] EXPRESSION\n\
15783 A watchpoint stops execution of your program whenever the value of\n\
15784 an expression changes.\n\
15785 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15786 the memory to which it refers."));
15787   set_cmd_completer (c, expression_completer);
15788
15789   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15790 Set a read watchpoint for an expression.\n\
15791 Usage: rwatch [-l|-location] EXPRESSION\n\
15792 A watchpoint stops execution of your program whenever the value of\n\
15793 an expression is read.\n\
15794 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15795 the memory to which it refers."));
15796   set_cmd_completer (c, expression_completer);
15797
15798   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15799 Set a watchpoint for an expression.\n\
15800 Usage: awatch [-l|-location] EXPRESSION\n\
15801 A watchpoint stops execution of your program whenever the value of\n\
15802 an expression is either read or written.\n\
15803 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15804 the memory to which it refers."));
15805   set_cmd_completer (c, expression_completer);
15806
15807   add_info ("watchpoints", info_watchpoints_command, _("\
15808 Status of specified watchpoints (all watchpoints if no argument)."));
15809
15810   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15811      respond to changes - contrary to the description.  */
15812   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15813                             &can_use_hw_watchpoints, _("\
15814 Set debugger's willingness to use watchpoint hardware."), _("\
15815 Show debugger's willingness to use watchpoint hardware."), _("\
15816 If zero, gdb will not use hardware for new watchpoints, even if\n\
15817 such is available.  (However, any hardware watchpoints that were\n\
15818 created before setting this to nonzero, will continue to use watchpoint\n\
15819 hardware.)"),
15820                             NULL,
15821                             show_can_use_hw_watchpoints,
15822                             &setlist, &showlist);
15823
15824   can_use_hw_watchpoints = 1;
15825
15826   /* Tracepoint manipulation commands.  */
15827
15828   c = add_com ("trace", class_breakpoint, trace_command, _("\
15829 Set a tracepoint at specified location.\n\
15830 \n"
15831 BREAK_ARGS_HELP ("trace") "\n\
15832 Do \"help tracepoints\" for info on other tracepoint commands."));
15833   set_cmd_completer (c, location_completer);
15834
15835   add_com_alias ("tp", "trace", class_alias, 0);
15836   add_com_alias ("tr", "trace", class_alias, 1);
15837   add_com_alias ("tra", "trace", class_alias, 1);
15838   add_com_alias ("trac", "trace", class_alias, 1);
15839
15840   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15841 Set a fast tracepoint at specified location.\n\
15842 \n"
15843 BREAK_ARGS_HELP ("ftrace") "\n\
15844 Do \"help tracepoints\" for info on other tracepoint commands."));
15845   set_cmd_completer (c, location_completer);
15846
15847   c = add_com ("strace", class_breakpoint, strace_command, _("\
15848 Set a static tracepoint at location or marker.\n\
15849 \n\
15850 strace [LOCATION] [if CONDITION]\n\
15851 LOCATION may be a linespec, explicit, or address location (described below) \n\
15852 or -m MARKER_ID.\n\n\
15853 If a marker id is specified, probe the marker with that name.  With\n\
15854 no LOCATION, uses current execution address of the selected stack frame.\n\
15855 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15856 This collects arbitrary user data passed in the probe point call to the\n\
15857 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15858 by printing the $_sdata variable like any other convenience variable.\n\
15859 \n\
15860 CONDITION is a boolean expression.\n\
15861 \n" LOCATION_HELP_STRING "\n\
15862 Multiple tracepoints at one place are permitted, and useful if their\n\
15863 conditions are different.\n\
15864 \n\
15865 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15866 Do \"help tracepoints\" for info on other tracepoint commands."));
15867   set_cmd_completer (c, location_completer);
15868
15869   add_info ("tracepoints", info_tracepoints_command, _("\
15870 Status of specified tracepoints (all tracepoints if no argument).\n\
15871 Convenience variable \"$tpnum\" contains the number of the\n\
15872 last tracepoint set."));
15873
15874   add_info_alias ("tp", "tracepoints", 1);
15875
15876   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15877 Delete specified tracepoints.\n\
15878 Arguments are tracepoint numbers, separated by spaces.\n\
15879 No argument means delete all tracepoints."),
15880            &deletelist);
15881   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
15882
15883   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15884 Disable specified tracepoints.\n\
15885 Arguments are tracepoint numbers, separated by spaces.\n\
15886 No argument means disable all tracepoints."),
15887            &disablelist);
15888   deprecate_cmd (c, "disable");
15889
15890   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15891 Enable specified tracepoints.\n\
15892 Arguments are tracepoint numbers, separated by spaces.\n\
15893 No argument means enable all tracepoints."),
15894            &enablelist);
15895   deprecate_cmd (c, "enable");
15896
15897   add_com ("passcount", class_trace, trace_pass_command, _("\
15898 Set the passcount for a tracepoint.\n\
15899 The trace will end when the tracepoint has been passed 'count' times.\n\
15900 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15901 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
15902
15903   add_prefix_cmd ("save", class_breakpoint, save_command,
15904                   _("Save breakpoint definitions as a script."),
15905                   &save_cmdlist, "save ",
15906                   0/*allow-unknown*/, &cmdlist);
15907
15908   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
15909 Save current breakpoint definitions as a script.\n\
15910 This includes all types of breakpoints (breakpoints, watchpoints,\n\
15911 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
15912 session to restore them."),
15913                &save_cmdlist);
15914   set_cmd_completer (c, filename_completer);
15915
15916   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
15917 Save current tracepoint definitions as a script.\n\
15918 Use the 'source' command in another debug session to restore them."),
15919                &save_cmdlist);
15920   set_cmd_completer (c, filename_completer);
15921
15922   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
15923   deprecate_cmd (c, "save tracepoints");
15924
15925   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
15926 Breakpoint specific settings\n\
15927 Configure various breakpoint-specific variables such as\n\
15928 pending breakpoint behavior"),
15929                   &breakpoint_set_cmdlist, "set breakpoint ",
15930                   0/*allow-unknown*/, &setlist);
15931   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
15932 Breakpoint specific settings\n\
15933 Configure various breakpoint-specific variables such as\n\
15934 pending breakpoint behavior"),
15935                   &breakpoint_show_cmdlist, "show breakpoint ",
15936                   0/*allow-unknown*/, &showlist);
15937
15938   add_setshow_auto_boolean_cmd ("pending", no_class,
15939                                 &pending_break_support, _("\
15940 Set debugger's behavior regarding pending breakpoints."), _("\
15941 Show debugger's behavior regarding pending breakpoints."), _("\
15942 If on, an unrecognized breakpoint location will cause gdb to create a\n\
15943 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
15944 an error.  If auto, an unrecognized breakpoint location results in a\n\
15945 user-query to see if a pending breakpoint should be created."),
15946                                 NULL,
15947                                 show_pending_break_support,
15948                                 &breakpoint_set_cmdlist,
15949                                 &breakpoint_show_cmdlist);
15950
15951   pending_break_support = AUTO_BOOLEAN_AUTO;
15952
15953   add_setshow_boolean_cmd ("auto-hw", no_class,
15954                            &automatic_hardware_breakpoints, _("\
15955 Set automatic usage of hardware breakpoints."), _("\
15956 Show automatic usage of hardware breakpoints."), _("\
15957 If set, the debugger will automatically use hardware breakpoints for\n\
15958 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
15959 a warning will be emitted for such breakpoints."),
15960                            NULL,
15961                            show_automatic_hardware_breakpoints,
15962                            &breakpoint_set_cmdlist,
15963                            &breakpoint_show_cmdlist);
15964
15965   add_setshow_boolean_cmd ("always-inserted", class_support,
15966                            &always_inserted_mode, _("\
15967 Set mode for inserting breakpoints."), _("\
15968 Show mode for inserting breakpoints."), _("\
15969 When this mode is on, breakpoints are inserted immediately as soon as\n\
15970 they're created, kept inserted even when execution stops, and removed\n\
15971 only when the user deletes them.  When this mode is off (the default),\n\
15972 breakpoints are inserted only when execution continues, and removed\n\
15973 when execution stops."),
15974                                 NULL,
15975                                 &show_always_inserted_mode,
15976                                 &breakpoint_set_cmdlist,
15977                                 &breakpoint_show_cmdlist);
15978
15979   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
15980                         condition_evaluation_enums,
15981                         &condition_evaluation_mode_1, _("\
15982 Set mode of breakpoint condition evaluation."), _("\
15983 Show mode of breakpoint condition evaluation."), _("\
15984 When this is set to \"host\", breakpoint conditions will be\n\
15985 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
15986 breakpoint conditions will be downloaded to the target (if the target\n\
15987 supports such feature) and conditions will be evaluated on the target's side.\n\
15988 If this is set to \"auto\" (default), this will be automatically set to\n\
15989 \"target\" if it supports condition evaluation, otherwise it will\n\
15990 be set to \"gdb\""),
15991                            &set_condition_evaluation_mode,
15992                            &show_condition_evaluation_mode,
15993                            &breakpoint_set_cmdlist,
15994                            &breakpoint_show_cmdlist);
15995
15996   add_com ("break-range", class_breakpoint, break_range_command, _("\
15997 Set a breakpoint for an address range.\n\
15998 break-range START-LOCATION, END-LOCATION\n\
15999 where START-LOCATION and END-LOCATION can be one of the following:\n\
16000   LINENUM, for that line in the current file,\n\
16001   FILE:LINENUM, for that line in that file,\n\
16002   +OFFSET, for that number of lines after the current line\n\
16003            or the start of the range\n\
16004   FUNCTION, for the first line in that function,\n\
16005   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16006   *ADDRESS, for the instruction at that address.\n\
16007 \n\
16008 The breakpoint will stop execution of the inferior whenever it executes\n\
16009 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16010 range (including START-LOCATION and END-LOCATION)."));
16011
16012   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16013 Set a dynamic printf at specified location.\n\
16014 dprintf location,format string,arg1,arg2,...\n\
16015 location may be a linespec, explicit, or address location.\n"
16016 "\n" LOCATION_HELP_STRING));
16017   set_cmd_completer (c, location_completer);
16018
16019   add_setshow_enum_cmd ("dprintf-style", class_support,
16020                         dprintf_style_enums, &dprintf_style, _("\
16021 Set the style of usage for dynamic printf."), _("\
16022 Show the style of usage for dynamic printf."), _("\
16023 This setting chooses how GDB will do a dynamic printf.\n\
16024 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16025 console, as with the \"printf\" command.\n\
16026 If the value is \"call\", the print is done by calling a function in your\n\
16027 program; by default printf(), but you can choose a different function or\n\
16028 output stream by setting dprintf-function and dprintf-channel."),
16029                         update_dprintf_commands, NULL,
16030                         &setlist, &showlist);
16031
16032   dprintf_function = xstrdup ("printf");
16033   add_setshow_string_cmd ("dprintf-function", class_support,
16034                           &dprintf_function, _("\
16035 Set the function to use for dynamic printf"), _("\
16036 Show the function to use for dynamic printf"), NULL,
16037                           update_dprintf_commands, NULL,
16038                           &setlist, &showlist);
16039
16040   dprintf_channel = xstrdup ("");
16041   add_setshow_string_cmd ("dprintf-channel", class_support,
16042                           &dprintf_channel, _("\
16043 Set the channel to use for dynamic printf"), _("\
16044 Show the channel to use for dynamic printf"), NULL,
16045                           update_dprintf_commands, NULL,
16046                           &setlist, &showlist);
16047
16048   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16049                            &disconnected_dprintf, _("\
16050 Set whether dprintf continues after GDB disconnects."), _("\
16051 Show whether dprintf continues after GDB disconnects."), _("\
16052 Use this to let dprintf commands continue to hit and produce output\n\
16053 even if GDB disconnects or detaches from the target."),
16054                            NULL,
16055                            NULL,
16056                            &setlist, &showlist);
16057
16058   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16059 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16060 (target agent only) This is useful for formatted output in user-defined commands."));
16061
16062   automatic_hardware_breakpoints = 1;
16063
16064   gdb::observers::about_to_proceed.attach (breakpoint_about_to_proceed);
16065   gdb::observers::thread_exit.attach (remove_threaded_breakpoints);
16066 }