Constify add_abbrev_prefix_cmd
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2017 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 "observer.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 ignore_command (char *, int);
100
101 static void breakpoint_re_set_default (struct breakpoint *);
102
103 static void
104   create_sals_from_location_default (const struct event_location *location,
105                                      struct linespec_result *canonical,
106                                      enum bptype type_wanted);
107
108 static void create_breakpoints_sal_default (struct gdbarch *,
109                                             struct linespec_result *,
110                                             gdb::unique_xmalloc_ptr<char>,
111                                             gdb::unique_xmalloc_ptr<char>,
112                                             enum bptype,
113                                             enum bpdisp, int, int,
114                                             int,
115                                             const struct breakpoint_ops *,
116                                             int, int, int, unsigned);
117
118 static std::vector<symtab_and_line> decode_location_default
119   (struct breakpoint *b, const struct event_location *location,
120    struct program_space *search_pspace);
121
122 static void clear_command (char *, int);
123
124 static int can_use_hardware_watchpoint (struct value *);
125
126 static void mention (struct breakpoint *);
127
128 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
129                                                                enum bptype,
130                                                                const struct breakpoint_ops *);
131 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
132                                                        const struct symtab_and_line *);
133
134 /* This function is used in gdbtk sources and thus can not be made
135    static.  */
136 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
137                                        struct symtab_and_line,
138                                        enum bptype,
139                                        const struct breakpoint_ops *);
140
141 static struct breakpoint *
142   momentary_breakpoint_from_master (struct breakpoint *orig,
143                                     enum bptype type,
144                                     const struct breakpoint_ops *ops,
145                                     int loc_enabled);
146
147 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
148
149 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
150                                             CORE_ADDR bpaddr,
151                                             enum bptype bptype);
152
153 static void describe_other_breakpoints (struct gdbarch *,
154                                         struct program_space *, CORE_ADDR,
155                                         struct obj_section *, int);
156
157 static int watchpoint_locations_match (struct bp_location *loc1,
158                                        struct bp_location *loc2);
159
160 static int breakpoint_location_address_match (struct bp_location *bl,
161                                               const struct address_space *aspace,
162                                               CORE_ADDR addr);
163
164 static int breakpoint_location_address_range_overlap (struct bp_location *,
165                                                       const address_space *,
166                                                       CORE_ADDR, int);
167
168 static void info_breakpoints_command (char *, int);
169
170 static void info_watchpoints_command (char *, int);
171
172 static void commands_command (char *, int);
173
174 static void condition_command (char *, int);
175
176 static int remove_breakpoint (struct bp_location *);
177 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
178
179 static enum print_stop_action print_bp_stop_message (bpstat bs);
180
181 static int hw_breakpoint_used_count (void);
182
183 static int hw_watchpoint_use_count (struct breakpoint *);
184
185 static int hw_watchpoint_used_count_others (struct breakpoint *except,
186                                             enum bptype type,
187                                             int *other_type_used);
188
189 static void hbreak_command (char *, int);
190
191 static void thbreak_command (char *, int);
192
193 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
194                                     int count);
195
196 static void free_bp_location (struct bp_location *loc);
197 static void incref_bp_location (struct bp_location *loc);
198 static void decref_bp_location (struct bp_location **loc);
199
200 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
201
202 /* update_global_location_list's modes of operation wrt to whether to
203    insert locations now.  */
204 enum ugll_insert_mode
205 {
206   /* Don't insert any breakpoint locations into the inferior, only
207      remove already-inserted locations that no longer should be
208      inserted.  Functions that delete a breakpoint or breakpoints
209      should specify this mode, so that deleting a breakpoint doesn't
210      have the side effect of inserting the locations of other
211      breakpoints that are marked not-inserted, but should_be_inserted
212      returns true on them.
213
214      This behavior is useful is situations close to tear-down -- e.g.,
215      after an exec, while the target still has execution, but
216      breakpoint shadows of the previous executable image should *NOT*
217      be restored to the new image; or before detaching, where the
218      target still has execution and wants to delete breakpoints from
219      GDB's lists, and all breakpoints had already been removed from
220      the inferior.  */
221   UGLL_DONT_INSERT,
222
223   /* May insert breakpoints iff breakpoints_should_be_inserted_now
224      claims breakpoints should be inserted now.  */
225   UGLL_MAY_INSERT,
226
227   /* Insert locations now, irrespective of
228      breakpoints_should_be_inserted_now.  E.g., say all threads are
229      stopped right now, and the user did "continue".  We need to
230      insert breakpoints _before_ resuming the target, but
231      UGLL_MAY_INSERT wouldn't insert them, because
232      breakpoints_should_be_inserted_now returns false at that point,
233      as no thread is running yet.  */
234   UGLL_INSERT
235 };
236
237 static void update_global_location_list (enum ugll_insert_mode);
238
239 static void update_global_location_list_nothrow (enum ugll_insert_mode);
240
241 static int is_hardware_watchpoint (const struct breakpoint *bpt);
242
243 static void insert_breakpoint_locations (void);
244
245 static void info_tracepoints_command (char *, int);
246
247 static void enable_trace_command (char *, int);
248
249 static void disable_trace_command (char *, int);
250
251 static void trace_pass_command (char *, int);
252
253 static void set_tracepoint_count (int num);
254
255 static int is_masked_watchpoint (const struct breakpoint *b);
256
257 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
258
259 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
260    otherwise.  */
261
262 static int strace_marker_p (struct breakpoint *b);
263
264 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
265    that are implemented on top of software or hardware breakpoints
266    (user breakpoints, internal and momentary breakpoints, etc.).  */
267 static struct breakpoint_ops bkpt_base_breakpoint_ops;
268
269 /* Internal breakpoints class type.  */
270 static struct breakpoint_ops internal_breakpoint_ops;
271
272 /* Momentary breakpoints class type.  */
273 static struct breakpoint_ops momentary_breakpoint_ops;
274
275 /* The breakpoint_ops structure to be used in regular user created
276    breakpoints.  */
277 struct breakpoint_ops bkpt_breakpoint_ops;
278
279 /* Breakpoints set on probes.  */
280 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
281
282 /* Dynamic printf class type.  */
283 struct breakpoint_ops dprintf_breakpoint_ops;
284
285 /* The style in which to perform a dynamic printf.  This is a user
286    option because different output options have different tradeoffs;
287    if GDB does the printing, there is better error handling if there
288    is a problem with any of the arguments, but using an inferior
289    function lets you have special-purpose printers and sending of
290    output to the same place as compiled-in print functions.  */
291
292 static const char dprintf_style_gdb[] = "gdb";
293 static const char dprintf_style_call[] = "call";
294 static const char dprintf_style_agent[] = "agent";
295 static const char *const dprintf_style_enums[] = {
296   dprintf_style_gdb,
297   dprintf_style_call,
298   dprintf_style_agent,
299   NULL
300 };
301 static const char *dprintf_style = dprintf_style_gdb;
302
303 /* The function to use for dynamic printf if the preferred style is to
304    call into the inferior.  The value is simply a string that is
305    copied into the command, so it can be anything that GDB can
306    evaluate to a callable address, not necessarily a function name.  */
307
308 static char *dprintf_function;
309
310 /* The channel to use for dynamic printf if the preferred style is to
311    call into the inferior; if a nonempty string, it will be passed to
312    the call as the first argument, with the format string as the
313    second.  As with the dprintf function, this can be anything that
314    GDB knows how to evaluate, so in addition to common choices like
315    "stderr", this could be an app-specific expression like
316    "mystreams[curlogger]".  */
317
318 static char *dprintf_channel;
319
320 /* True if dprintf commands should continue to operate even if GDB
321    has disconnected.  */
322 static int disconnected_dprintf = 1;
323
324 struct command_line *
325 breakpoint_commands (struct breakpoint *b)
326 {
327   return b->commands ? b->commands.get () : NULL;
328 }
329
330 /* Flag indicating that a command has proceeded the inferior past the
331    current breakpoint.  */
332
333 static int breakpoint_proceeded;
334
335 const char *
336 bpdisp_text (enum bpdisp disp)
337 {
338   /* NOTE: the following values are a part of MI protocol and
339      represent values of 'disp' field returned when inferior stops at
340      a breakpoint.  */
341   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
342
343   return bpdisps[(int) disp];
344 }
345
346 /* Prototypes for exported functions.  */
347 /* If FALSE, gdb will not use hardware support for watchpoints, even
348    if such is available.  */
349 static int can_use_hw_watchpoints;
350
351 static void
352 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
353                              struct cmd_list_element *c,
354                              const char *value)
355 {
356   fprintf_filtered (file,
357                     _("Debugger's willingness to use "
358                       "watchpoint hardware is %s.\n"),
359                     value);
360 }
361
362 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
363    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
364    for unrecognized breakpoint locations.
365    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
366 static enum auto_boolean pending_break_support;
367 static void
368 show_pending_break_support (struct ui_file *file, int from_tty,
369                             struct cmd_list_element *c,
370                             const char *value)
371 {
372   fprintf_filtered (file,
373                     _("Debugger's behavior regarding "
374                       "pending breakpoints is %s.\n"),
375                     value);
376 }
377
378 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
379    set with "break" but falling in read-only memory.
380    If 0, gdb will warn about such breakpoints, but won't automatically
381    use hardware breakpoints.  */
382 static int automatic_hardware_breakpoints;
383 static void
384 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
385                                      struct cmd_list_element *c,
386                                      const char *value)
387 {
388   fprintf_filtered (file,
389                     _("Automatic usage of hardware breakpoints is %s.\n"),
390                     value);
391 }
392
393 /* If on, GDB keeps breakpoints inserted even if the inferior is
394    stopped, and immediately inserts any new breakpoints as soon as
395    they're created.  If off (default), GDB keeps breakpoints off of
396    the target as long as possible.  That is, it delays inserting
397    breakpoints until the next resume, and removes them again when the
398    target fully stops.  This is a bit safer in case GDB crashes while
399    processing user input.  */
400 static int always_inserted_mode = 0;
401
402 static void
403 show_always_inserted_mode (struct ui_file *file, int from_tty,
404                      struct cmd_list_element *c, const char *value)
405 {
406   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
407                     value);
408 }
409
410 /* See breakpoint.h.  */
411
412 int
413 breakpoints_should_be_inserted_now (void)
414 {
415   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
416     {
417       /* If breakpoints are global, they should be inserted even if no
418          thread under gdb's control is running, or even if there are
419          no threads under GDB's control yet.  */
420       return 1;
421     }
422   else if (target_has_execution)
423     {
424       struct thread_info *tp;
425
426       if (always_inserted_mode)
427         {
428           /* The user wants breakpoints inserted even if all threads
429              are stopped.  */
430           return 1;
431         }
432
433       if (threads_are_executing ())
434         return 1;
435
436       /* Don't remove breakpoints yet if, even though all threads are
437          stopped, we still have events to process.  */
438       ALL_NON_EXITED_THREADS (tp)
439         if (tp->resumed
440             && tp->suspend.waitstatus_pending_p)
441           return 1;
442     }
443   return 0;
444 }
445
446 static const char condition_evaluation_both[] = "host or target";
447
448 /* Modes for breakpoint condition evaluation.  */
449 static const char condition_evaluation_auto[] = "auto";
450 static const char condition_evaluation_host[] = "host";
451 static const char condition_evaluation_target[] = "target";
452 static const char *const condition_evaluation_enums[] = {
453   condition_evaluation_auto,
454   condition_evaluation_host,
455   condition_evaluation_target,
456   NULL
457 };
458
459 /* Global that holds the current mode for breakpoint condition evaluation.  */
460 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
461
462 /* Global that we use to display information to the user (gets its value from
463    condition_evaluation_mode_1.  */
464 static const char *condition_evaluation_mode = condition_evaluation_auto;
465
466 /* Translate a condition evaluation mode MODE into either "host"
467    or "target".  This is used mostly to translate from "auto" to the
468    real setting that is being used.  It returns the translated
469    evaluation mode.  */
470
471 static const char *
472 translate_condition_evaluation_mode (const char *mode)
473 {
474   if (mode == condition_evaluation_auto)
475     {
476       if (target_supports_evaluation_of_breakpoint_conditions ())
477         return condition_evaluation_target;
478       else
479         return condition_evaluation_host;
480     }
481   else
482     return mode;
483 }
484
485 /* Discovers what condition_evaluation_auto translates to.  */
486
487 static const char *
488 breakpoint_condition_evaluation_mode (void)
489 {
490   return translate_condition_evaluation_mode (condition_evaluation_mode);
491 }
492
493 /* Return true if GDB should evaluate breakpoint conditions or false
494    otherwise.  */
495
496 static int
497 gdb_evaluates_breakpoint_condition_p (void)
498 {
499   const char *mode = breakpoint_condition_evaluation_mode ();
500
501   return (mode == condition_evaluation_host);
502 }
503
504 /* Are we executing breakpoint commands?  */
505 static int executing_breakpoint_commands;
506
507 /* Are overlay event breakpoints enabled? */
508 static int overlay_events_enabled;
509
510 /* See description in breakpoint.h. */
511 int target_exact_watchpoints = 0;
512
513 /* Walk the following statement or block through all breakpoints.
514    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
515    current breakpoint.  */
516
517 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
518
519 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
520         for (B = breakpoint_chain;      \
521              B ? (TMP=B->next, 1): 0;   \
522              B = TMP)
523
524 /* Similar iterator for the low-level breakpoints.  SAFE variant is
525    not provided so update_global_location_list must not be called
526    while executing the block of ALL_BP_LOCATIONS.  */
527
528 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
529         for (BP_TMP = bp_locations;                                     \
530              BP_TMP < bp_locations + bp_locations_count && (B = *BP_TMP);\
531              BP_TMP++)
532
533 /* Iterates through locations with address ADDRESS for the currently selected
534    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
535    to where the loop should start from.
536    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
537    appropriate location to start with.  */
538
539 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
540         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
541              BP_LOCP_TMP = BP_LOCP_START;                               \
542              BP_LOCP_START                                              \
543              && (BP_LOCP_TMP < bp_locations + bp_locations_count        \
544              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
545              BP_LOCP_TMP++)
546
547 /* Iterator for tracepoints only.  */
548
549 #define ALL_TRACEPOINTS(B)  \
550   for (B = breakpoint_chain; B; B = B->next)  \
551     if (is_tracepoint (B))
552
553 /* Chains of all breakpoints defined.  */
554
555 struct breakpoint *breakpoint_chain;
556
557 /* Array is sorted by bp_locations_compare - primarily by the ADDRESS.  */
558
559 static struct bp_location **bp_locations;
560
561 /* Number of elements of BP_LOCATIONS.  */
562
563 static unsigned bp_locations_count;
564
565 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
566    ADDRESS for the current elements of BP_LOCATIONS which get a valid
567    result from bp_location_has_shadow.  You can use it for roughly
568    limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
569    an address you need to read.  */
570
571 static CORE_ADDR bp_locations_placed_address_before_address_max;
572
573 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
574    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
575    BP_LOCATIONS which get a valid result from bp_location_has_shadow.
576    You can use it for roughly limiting the subrange of BP_LOCATIONS to
577    scan for shadow bytes for an address you need to read.  */
578
579 static CORE_ADDR bp_locations_shadow_len_after_address_max;
580
581 /* The locations that no longer correspond to any breakpoint, unlinked
582    from the bp_locations array, but for which a hit may still be
583    reported by a target.  */
584 VEC(bp_location_p) *moribund_locations = NULL;
585
586 /* Number of last breakpoint made.  */
587
588 static int breakpoint_count;
589
590 /* The value of `breakpoint_count' before the last command that
591    created breakpoints.  If the last (break-like) command created more
592    than one breakpoint, then the difference between BREAKPOINT_COUNT
593    and PREV_BREAKPOINT_COUNT is more than one.  */
594 static int prev_breakpoint_count;
595
596 /* Number of last tracepoint made.  */
597
598 static int tracepoint_count;
599
600 static struct cmd_list_element *breakpoint_set_cmdlist;
601 static struct cmd_list_element *breakpoint_show_cmdlist;
602 struct cmd_list_element *save_cmdlist;
603
604 /* See declaration at breakpoint.h.  */
605
606 struct breakpoint *
607 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
608                     void *user_data)
609 {
610   struct breakpoint *b = NULL;
611
612   ALL_BREAKPOINTS (b)
613     {
614       if (func (b, user_data) != 0)
615         break;
616     }
617
618   return b;
619 }
620
621 /* Return whether a breakpoint is an active enabled breakpoint.  */
622 static int
623 breakpoint_enabled (struct breakpoint *b)
624 {
625   return (b->enable_state == bp_enabled);
626 }
627
628 /* Set breakpoint count to NUM.  */
629
630 static void
631 set_breakpoint_count (int num)
632 {
633   prev_breakpoint_count = breakpoint_count;
634   breakpoint_count = num;
635   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
636 }
637
638 /* Used by `start_rbreak_breakpoints' below, to record the current
639    breakpoint count before "rbreak" creates any breakpoint.  */
640 static int rbreak_start_breakpoint_count;
641
642 /* Called at the start an "rbreak" command to record the first
643    breakpoint made.  */
644
645 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
646 {
647   rbreak_start_breakpoint_count = breakpoint_count;
648 }
649
650 /* Called at the end of an "rbreak" command to record the last
651    breakpoint made.  */
652
653 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
654 {
655   prev_breakpoint_count = rbreak_start_breakpoint_count;
656 }
657
658 /* Used in run_command to zero the hit count when a new run starts.  */
659
660 void
661 clear_breakpoint_hit_counts (void)
662 {
663   struct breakpoint *b;
664
665   ALL_BREAKPOINTS (b)
666     b->hit_count = 0;
667 }
668
669 \f
670 /* Return the breakpoint with the specified number, or NULL
671    if the number does not refer to an existing breakpoint.  */
672
673 struct breakpoint *
674 get_breakpoint (int num)
675 {
676   struct breakpoint *b;
677
678   ALL_BREAKPOINTS (b)
679     if (b->number == num)
680       return b;
681   
682   return NULL;
683 }
684
685 \f
686
687 /* Mark locations as "conditions have changed" in case the target supports
688    evaluating conditions on its side.  */
689
690 static void
691 mark_breakpoint_modified (struct breakpoint *b)
692 {
693   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     return;
702
703   if (!is_breakpoint (b))
704     return;
705
706   for (loc = b->loc; loc; loc = loc->next)
707     loc->condition_changed = condition_modified;
708 }
709
710 /* Mark location as "conditions have changed" in case the target supports
711    evaluating conditions on its side.  */
712
713 static void
714 mark_breakpoint_location_modified (struct bp_location *loc)
715 {
716   /* This is only meaningful if the target is
717      evaluating conditions and if the user has
718      opted for condition evaluation on the target's
719      side.  */
720   if (gdb_evaluates_breakpoint_condition_p ()
721       || !target_supports_evaluation_of_breakpoint_conditions ())
722
723     return;
724
725   if (!is_breakpoint (loc->owner))
726     return;
727
728   loc->condition_changed = condition_modified;
729 }
730
731 /* Sets the condition-evaluation mode using the static global
732    condition_evaluation_mode.  */
733
734 static void
735 set_condition_evaluation_mode (char *args, int from_tty,
736                                struct cmd_list_element *c)
737 {
738   const char *old_mode, *new_mode;
739
740   if ((condition_evaluation_mode_1 == condition_evaluation_target)
741       && !target_supports_evaluation_of_breakpoint_conditions ())
742     {
743       condition_evaluation_mode_1 = condition_evaluation_mode;
744       warning (_("Target does not support breakpoint condition evaluation.\n"
745                  "Using host evaluation mode instead."));
746       return;
747     }
748
749   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
750   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
751
752   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
753      settings was "auto".  */
754   condition_evaluation_mode = condition_evaluation_mode_1;
755
756   /* Only update the mode if the user picked a different one.  */
757   if (new_mode != old_mode)
758     {
759       struct bp_location *loc, **loc_tmp;
760       /* If the user switched to a different evaluation mode, we
761          need to synch the changes with the target as follows:
762
763          "host" -> "target": Send all (valid) conditions to the target.
764          "target" -> "host": Remove all the conditions from the target.
765       */
766
767       if (new_mode == condition_evaluation_target)
768         {
769           /* Mark everything modified and synch conditions with the
770              target.  */
771           ALL_BP_LOCATIONS (loc, loc_tmp)
772             mark_breakpoint_location_modified (loc);
773         }
774       else
775         {
776           /* Manually mark non-duplicate locations to synch conditions
777              with the target.  We do this to remove all the conditions the
778              target knows about.  */
779           ALL_BP_LOCATIONS (loc, loc_tmp)
780             if (is_breakpoint (loc->owner) && loc->inserted)
781               loc->needs_update = 1;
782         }
783
784       /* Do the update.  */
785       update_global_location_list (UGLL_MAY_INSERT);
786     }
787
788   return;
789 }
790
791 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
792    what "auto" is translating to.  */
793
794 static void
795 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
796                                 struct cmd_list_element *c, const char *value)
797 {
798   if (condition_evaluation_mode == condition_evaluation_auto)
799     fprintf_filtered (file,
800                       _("Breakpoint condition evaluation "
801                         "mode is %s (currently %s).\n"),
802                       value,
803                       breakpoint_condition_evaluation_mode ());
804   else
805     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
806                       value);
807 }
808
809 /* A comparison function for bp_location AP and BP that is used by
810    bsearch.  This comparison function only cares about addresses, unlike
811    the more general bp_locations_compare function.  */
812
813 static int
814 bp_locations_compare_addrs (const void *ap, const void *bp)
815 {
816   const struct bp_location *a = *(const struct bp_location **) ap;
817   const struct bp_location *b = *(const struct bp_location **) bp;
818
819   if (a->address == b->address)
820     return 0;
821   else
822     return ((a->address > b->address) - (a->address < b->address));
823 }
824
825 /* Helper function to skip all bp_locations with addresses
826    less than ADDRESS.  It returns the first bp_location that
827    is greater than or equal to ADDRESS.  If none is found, just
828    return NULL.  */
829
830 static struct bp_location **
831 get_first_locp_gte_addr (CORE_ADDR address)
832 {
833   struct bp_location dummy_loc;
834   struct bp_location *dummy_locp = &dummy_loc;
835   struct bp_location **locp_found = NULL;
836
837   /* Initialize the dummy location's address field.  */
838   dummy_loc.address = address;
839
840   /* Find a close match to the first location at ADDRESS.  */
841   locp_found = ((struct bp_location **)
842                 bsearch (&dummy_locp, bp_locations, bp_locations_count,
843                          sizeof (struct bp_location **),
844                          bp_locations_compare_addrs));
845
846   /* Nothing was found, nothing left to do.  */
847   if (locp_found == NULL)
848     return NULL;
849
850   /* We may have found a location that is at ADDRESS but is not the first in the
851      location's list.  Go backwards (if possible) and locate the first one.  */
852   while ((locp_found - 1) >= bp_locations
853          && (*(locp_found - 1))->address == address)
854     locp_found--;
855
856   return locp_found;
857 }
858
859 void
860 set_breakpoint_condition (struct breakpoint *b, const char *exp,
861                           int from_tty)
862 {
863   xfree (b->cond_string);
864   b->cond_string = NULL;
865
866   if (is_watchpoint (b))
867     {
868       struct watchpoint *w = (struct watchpoint *) b;
869
870       w->cond_exp.reset ();
871     }
872   else
873     {
874       struct bp_location *loc;
875
876       for (loc = b->loc; loc; loc = loc->next)
877         {
878           loc->cond.reset ();
879
880           /* No need to free the condition agent expression
881              bytecode (if we have one).  We will handle this
882              when we go through update_global_location_list.  */
883         }
884     }
885
886   if (*exp == 0)
887     {
888       if (from_tty)
889         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
890     }
891   else
892     {
893       const char *arg = exp;
894
895       /* I don't know if it matters whether this is the string the user
896          typed in or the decompiled expression.  */
897       b->cond_string = xstrdup (arg);
898       b->condition_not_parsed = 0;
899
900       if (is_watchpoint (b))
901         {
902           struct watchpoint *w = (struct watchpoint *) b;
903
904           innermost_block = NULL;
905           arg = exp;
906           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
907           if (*arg)
908             error (_("Junk at end of expression"));
909           w->cond_exp_valid_block = innermost_block;
910         }
911       else
912         {
913           struct bp_location *loc;
914
915           for (loc = b->loc; loc; loc = loc->next)
916             {
917               arg = exp;
918               loc->cond =
919                 parse_exp_1 (&arg, loc->address,
920                              block_for_pc (loc->address), 0);
921               if (*arg)
922                 error (_("Junk at end of expression"));
923             }
924         }
925     }
926   mark_breakpoint_modified (b);
927
928   observer_notify_breakpoint_modified (b);
929 }
930
931 /* Completion for the "condition" command.  */
932
933 static void
934 condition_completer (struct cmd_list_element *cmd,
935                      completion_tracker &tracker,
936                      const char *text, const char *word)
937 {
938   const char *space;
939
940   text = skip_spaces (text);
941   space = skip_to_space (text);
942   if (*space == '\0')
943     {
944       int len;
945       struct breakpoint *b;
946       VEC (char_ptr) *result = NULL;
947
948       if (text[0] == '$')
949         {
950           /* We don't support completion of history indices.  */
951           if (!isdigit (text[1]))
952             complete_internalvar (tracker, &text[1]);
953           return;
954         }
955
956       /* We're completing the breakpoint number.  */
957       len = strlen (text);
958
959       ALL_BREAKPOINTS (b)
960         {
961           char number[50];
962
963           xsnprintf (number, sizeof (number), "%d", b->number);
964
965           if (strncmp (number, text, len) == 0)
966             {
967               gdb::unique_xmalloc_ptr<char> copy (xstrdup (number));
968               tracker.add_completion (std::move (copy));
969             }
970         }
971
972       return;
973     }
974
975   /* We're completing the expression part.  */
976   text = skip_spaces (space);
977   expression_completer (cmd, tracker, text, word);
978 }
979
980 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
981
982 static void
983 condition_command (char *arg, int from_tty)
984 {
985   struct breakpoint *b;
986   char *p;
987   int bnum;
988
989   if (arg == 0)
990     error_no_arg (_("breakpoint number"));
991
992   p = arg;
993   bnum = get_number (&p);
994   if (bnum == 0)
995     error (_("Bad breakpoint argument: '%s'"), arg);
996
997   ALL_BREAKPOINTS (b)
998     if (b->number == bnum)
999       {
1000         /* Check if this breakpoint has a "stop" method implemented in an
1001            extension language.  This method and conditions entered into GDB
1002            from the CLI are mutually exclusive.  */
1003         const struct extension_language_defn *extlang
1004           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1005
1006         if (extlang != NULL)
1007           {
1008             error (_("Only one stop condition allowed.  There is currently"
1009                      " a %s stop condition defined for this breakpoint."),
1010                    ext_lang_capitalized_name (extlang));
1011           }
1012         set_breakpoint_condition (b, p, from_tty);
1013
1014         if (is_breakpoint (b))
1015           update_global_location_list (UGLL_MAY_INSERT);
1016
1017         return;
1018       }
1019
1020   error (_("No breakpoint number %d."), bnum);
1021 }
1022
1023 /* Check that COMMAND do not contain commands that are suitable
1024    only for tracepoints and not suitable for ordinary breakpoints.
1025    Throw if any such commands is found.  */
1026
1027 static void
1028 check_no_tracepoint_commands (struct command_line *commands)
1029 {
1030   struct command_line *c;
1031
1032   for (c = commands; c; c = c->next)
1033     {
1034       int i;
1035
1036       if (c->control_type == while_stepping_control)
1037         error (_("The 'while-stepping' command can "
1038                  "only be used for tracepoints"));
1039
1040       for (i = 0; i < c->body_count; ++i)
1041         check_no_tracepoint_commands ((c->body_list)[i]);
1042
1043       /* Not that command parsing removes leading whitespace and comment
1044          lines and also empty lines.  So, we only need to check for
1045          command directly.  */
1046       if (strstr (c->line, "collect ") == c->line)
1047         error (_("The 'collect' command can only be used for tracepoints"));
1048
1049       if (strstr (c->line, "teval ") == c->line)
1050         error (_("The 'teval' command can only be used for tracepoints"));
1051     }
1052 }
1053
1054 struct longjmp_breakpoint : public breakpoint
1055 {
1056   ~longjmp_breakpoint () override;
1057 };
1058
1059 /* Encapsulate tests for different types of tracepoints.  */
1060
1061 static bool
1062 is_tracepoint_type (bptype type)
1063 {
1064   return (type == bp_tracepoint
1065           || type == bp_fast_tracepoint
1066           || type == bp_static_tracepoint);
1067 }
1068
1069 static bool
1070 is_longjmp_type (bptype type)
1071 {
1072   return type == bp_longjmp || type == bp_exception;
1073 }
1074
1075 int
1076 is_tracepoint (const struct breakpoint *b)
1077 {
1078   return is_tracepoint_type (b->type);
1079 }
1080
1081 /* Factory function to create an appropriate instance of breakpoint given
1082    TYPE.  */
1083
1084 static std::unique_ptr<breakpoint>
1085 new_breakpoint_from_type (bptype type)
1086 {
1087   breakpoint *b;
1088
1089   if (is_tracepoint_type (type))
1090     b = new tracepoint ();
1091   else if (is_longjmp_type (type))
1092     b = new longjmp_breakpoint ();
1093   else
1094     b = new breakpoint ();
1095
1096   return std::unique_ptr<breakpoint> (b);
1097 }
1098
1099 /* A helper function that validates that COMMANDS are valid for a
1100    breakpoint.  This function will throw an exception if a problem is
1101    found.  */
1102
1103 static void
1104 validate_commands_for_breakpoint (struct breakpoint *b,
1105                                   struct command_line *commands)
1106 {
1107   if (is_tracepoint (b))
1108     {
1109       struct tracepoint *t = (struct tracepoint *) b;
1110       struct command_line *c;
1111       struct command_line *while_stepping = 0;
1112
1113       /* Reset the while-stepping step count.  The previous commands
1114          might have included a while-stepping action, while the new
1115          ones might not.  */
1116       t->step_count = 0;
1117
1118       /* We need to verify that each top-level element of commands is
1119          valid for tracepoints, that there's at most one
1120          while-stepping element, and that the while-stepping's body
1121          has valid tracing commands excluding nested while-stepping.
1122          We also need to validate the tracepoint action line in the
1123          context of the tracepoint --- validate_actionline actually
1124          has side effects, like setting the tracepoint's
1125          while-stepping STEP_COUNT, in addition to checking if the
1126          collect/teval actions parse and make sense in the
1127          tracepoint's context.  */
1128       for (c = commands; c; c = c->next)
1129         {
1130           if (c->control_type == while_stepping_control)
1131             {
1132               if (b->type == bp_fast_tracepoint)
1133                 error (_("The 'while-stepping' command "
1134                          "cannot be used for fast tracepoint"));
1135               else if (b->type == bp_static_tracepoint)
1136                 error (_("The 'while-stepping' command "
1137                          "cannot be used for static tracepoint"));
1138
1139               if (while_stepping)
1140                 error (_("The 'while-stepping' command "
1141                          "can be used only once"));
1142               else
1143                 while_stepping = c;
1144             }
1145
1146           validate_actionline (c->line, b);
1147         }
1148       if (while_stepping)
1149         {
1150           struct command_line *c2;
1151
1152           gdb_assert (while_stepping->body_count == 1);
1153           c2 = while_stepping->body_list[0];
1154           for (; c2; c2 = c2->next)
1155             {
1156               if (c2->control_type == while_stepping_control)
1157                 error (_("The 'while-stepping' command cannot be nested"));
1158             }
1159         }
1160     }
1161   else
1162     {
1163       check_no_tracepoint_commands (commands);
1164     }
1165 }
1166
1167 /* Return a vector of all the static tracepoints set at ADDR.  The
1168    caller is responsible for releasing the vector.  */
1169
1170 VEC(breakpoint_p) *
1171 static_tracepoints_here (CORE_ADDR addr)
1172 {
1173   struct breakpoint *b;
1174   VEC(breakpoint_p) *found = 0;
1175   struct bp_location *loc;
1176
1177   ALL_BREAKPOINTS (b)
1178     if (b->type == bp_static_tracepoint)
1179       {
1180         for (loc = b->loc; loc; loc = loc->next)
1181           if (loc->address == addr)
1182             VEC_safe_push(breakpoint_p, found, b);
1183       }
1184
1185   return found;
1186 }
1187
1188 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1189    validate that only allowed commands are included.  */
1190
1191 void
1192 breakpoint_set_commands (struct breakpoint *b, 
1193                          command_line_up &&commands)
1194 {
1195   validate_commands_for_breakpoint (b, commands.get ());
1196
1197   b->commands = std::move (commands);
1198   observer_notify_breakpoint_modified (b);
1199 }
1200
1201 /* Set the internal `silent' flag on the breakpoint.  Note that this
1202    is not the same as the "silent" that may appear in the breakpoint's
1203    commands.  */
1204
1205 void
1206 breakpoint_set_silent (struct breakpoint *b, int silent)
1207 {
1208   int old_silent = b->silent;
1209
1210   b->silent = silent;
1211   if (old_silent != silent)
1212     observer_notify_breakpoint_modified (b);
1213 }
1214
1215 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1216    breakpoint work for any thread.  */
1217
1218 void
1219 breakpoint_set_thread (struct breakpoint *b, int thread)
1220 {
1221   int old_thread = b->thread;
1222
1223   b->thread = thread;
1224   if (old_thread != thread)
1225     observer_notify_breakpoint_modified (b);
1226 }
1227
1228 /* Set the task for this breakpoint.  If TASK is 0, make the
1229    breakpoint work for any task.  */
1230
1231 void
1232 breakpoint_set_task (struct breakpoint *b, int task)
1233 {
1234   int old_task = b->task;
1235
1236   b->task = task;
1237   if (old_task != task)
1238     observer_notify_breakpoint_modified (b);
1239 }
1240
1241 void
1242 check_tracepoint_command (char *line, void *closure)
1243 {
1244   struct breakpoint *b = (struct breakpoint *) closure;
1245
1246   validate_actionline (line, b);
1247 }
1248
1249 static void
1250 commands_command_1 (const char *arg, int from_tty,
1251                     struct command_line *control)
1252 {
1253   counted_command_line cmd;
1254
1255   std::string new_arg;
1256
1257   if (arg == NULL || !*arg)
1258     {
1259       if (breakpoint_count - prev_breakpoint_count > 1)
1260         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1261                                  breakpoint_count);
1262       else if (breakpoint_count > 0)
1263         new_arg = string_printf ("%d", breakpoint_count);
1264       arg = new_arg.c_str ();
1265     }
1266
1267   map_breakpoint_numbers
1268     (arg, [&] (breakpoint *b)
1269      {
1270        if (cmd == NULL)
1271          {
1272            if (control != NULL)
1273              cmd = copy_command_lines (control->body_list[0]);
1274            else
1275              {
1276                std::string str
1277                  = string_printf (_("Type commands for breakpoint(s) "
1278                                     "%s, one per line."),
1279                                   arg);
1280
1281                cmd = read_command_lines (&str[0],
1282                                          from_tty, 1,
1283                                          (is_tracepoint (b)
1284                                           ? check_tracepoint_command : 0),
1285                                          b);
1286              }
1287          }
1288
1289        /* If a breakpoint was on the list more than once, we don't need to
1290           do anything.  */
1291        if (b->commands != cmd)
1292          {
1293            validate_commands_for_breakpoint (b, cmd.get ());
1294            b->commands = cmd;
1295            observer_notify_breakpoint_modified (b);
1296          }
1297      });
1298
1299   if (cmd == NULL)
1300     error (_("No breakpoints specified."));
1301 }
1302
1303 static void
1304 commands_command (char *arg, int from_tty)
1305 {
1306   commands_command_1 (arg, from_tty, NULL);
1307 }
1308
1309 /* Like commands_command, but instead of reading the commands from
1310    input stream, takes them from an already parsed command structure.
1311
1312    This is used by cli-script.c to DTRT with breakpoint commands
1313    that are part of if and while bodies.  */
1314 enum command_control_type
1315 commands_from_control_command (const char *arg, struct command_line *cmd)
1316 {
1317   commands_command_1 (arg, 0, cmd);
1318   return simple_control;
1319 }
1320
1321 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1322
1323 static int
1324 bp_location_has_shadow (struct bp_location *bl)
1325 {
1326   if (bl->loc_type != bp_loc_software_breakpoint)
1327     return 0;
1328   if (!bl->inserted)
1329     return 0;
1330   if (bl->target_info.shadow_len == 0)
1331     /* BL isn't valid, or doesn't shadow memory.  */
1332     return 0;
1333   return 1;
1334 }
1335
1336 /* Update BUF, which is LEN bytes read from the target address
1337    MEMADDR, by replacing a memory breakpoint with its shadowed
1338    contents.
1339
1340    If READBUF is not NULL, this buffer must not overlap with the of
1341    the breakpoint location's shadow_contents buffer.  Otherwise, a
1342    failed assertion internal error will be raised.  */
1343
1344 static void
1345 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1346                             const gdb_byte *writebuf_org,
1347                             ULONGEST memaddr, LONGEST len,
1348                             struct bp_target_info *target_info,
1349                             struct gdbarch *gdbarch)
1350 {
1351   /* Now do full processing of the found relevant range of elements.  */
1352   CORE_ADDR bp_addr = 0;
1353   int bp_size = 0;
1354   int bptoffset = 0;
1355
1356   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1357                                  current_program_space->aspace, 0))
1358     {
1359       /* The breakpoint is inserted in a different address space.  */
1360       return;
1361     }
1362
1363   /* Addresses and length of the part of the breakpoint that
1364      we need to copy.  */
1365   bp_addr = target_info->placed_address;
1366   bp_size = target_info->shadow_len;
1367
1368   if (bp_addr + bp_size <= memaddr)
1369     {
1370       /* The breakpoint is entirely before the chunk of memory we are
1371          reading.  */
1372       return;
1373     }
1374
1375   if (bp_addr >= memaddr + len)
1376     {
1377       /* The breakpoint is entirely after the chunk of memory we are
1378          reading.  */
1379       return;
1380     }
1381
1382   /* Offset within shadow_contents.  */
1383   if (bp_addr < memaddr)
1384     {
1385       /* Only copy the second part of the breakpoint.  */
1386       bp_size -= memaddr - bp_addr;
1387       bptoffset = memaddr - bp_addr;
1388       bp_addr = memaddr;
1389     }
1390
1391   if (bp_addr + bp_size > memaddr + len)
1392     {
1393       /* Only copy the first part of the breakpoint.  */
1394       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1395     }
1396
1397   if (readbuf != NULL)
1398     {
1399       /* Verify that the readbuf buffer does not overlap with the
1400          shadow_contents buffer.  */
1401       gdb_assert (target_info->shadow_contents >= readbuf + len
1402                   || readbuf >= (target_info->shadow_contents
1403                                  + target_info->shadow_len));
1404
1405       /* Update the read buffer with this inserted breakpoint's
1406          shadow.  */
1407       memcpy (readbuf + bp_addr - memaddr,
1408               target_info->shadow_contents + bptoffset, bp_size);
1409     }
1410   else
1411     {
1412       const unsigned char *bp;
1413       CORE_ADDR addr = target_info->reqstd_address;
1414       int placed_size;
1415
1416       /* Update the shadow with what we want to write to memory.  */
1417       memcpy (target_info->shadow_contents + bptoffset,
1418               writebuf_org + bp_addr - memaddr, bp_size);
1419
1420       /* Determine appropriate breakpoint contents and size for this
1421          address.  */
1422       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1423
1424       /* Update the final write buffer with this inserted
1425          breakpoint's INSN.  */
1426       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1427     }
1428 }
1429
1430 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1431    by replacing any memory breakpoints with their shadowed contents.
1432
1433    If READBUF is not NULL, this buffer must not overlap with any of
1434    the breakpoint location's shadow_contents buffers.  Otherwise,
1435    a failed assertion internal error will be raised.
1436
1437    The range of shadowed area by each bp_location is:
1438      bl->address - bp_locations_placed_address_before_address_max
1439      up to bl->address + bp_locations_shadow_len_after_address_max
1440    The range we were requested to resolve shadows for is:
1441      memaddr ... memaddr + len
1442    Thus the safe cutoff boundaries for performance optimization are
1443      memaddr + len <= (bl->address
1444                        - bp_locations_placed_address_before_address_max)
1445    and:
1446      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1447
1448 void
1449 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1450                         const gdb_byte *writebuf_org,
1451                         ULONGEST memaddr, LONGEST len)
1452 {
1453   /* Left boundary, right boundary and median element of our binary
1454      search.  */
1455   unsigned bc_l, bc_r, bc;
1456
1457   /* Find BC_L which is a leftmost element which may affect BUF
1458      content.  It is safe to report lower value but a failure to
1459      report higher one.  */
1460
1461   bc_l = 0;
1462   bc_r = bp_locations_count;
1463   while (bc_l + 1 < bc_r)
1464     {
1465       struct bp_location *bl;
1466
1467       bc = (bc_l + bc_r) / 2;
1468       bl = bp_locations[bc];
1469
1470       /* Check first BL->ADDRESS will not overflow due to the added
1471          constant.  Then advance the left boundary only if we are sure
1472          the BC element can in no way affect the BUF content (MEMADDR
1473          to MEMADDR + LEN range).
1474
1475          Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1476          offset so that we cannot miss a breakpoint with its shadow
1477          range tail still reaching MEMADDR.  */
1478
1479       if ((bl->address + bp_locations_shadow_len_after_address_max
1480            >= bl->address)
1481           && (bl->address + bp_locations_shadow_len_after_address_max
1482               <= memaddr))
1483         bc_l = bc;
1484       else
1485         bc_r = bc;
1486     }
1487
1488   /* Due to the binary search above, we need to make sure we pick the
1489      first location that's at BC_L's address.  E.g., if there are
1490      multiple locations at the same address, BC_L may end up pointing
1491      at a duplicate location, and miss the "master"/"inserted"
1492      location.  Say, given locations L1, L2 and L3 at addresses A and
1493      B:
1494
1495       L1@A, L2@A, L3@B, ...
1496
1497      BC_L could end up pointing at location L2, while the "master"
1498      location could be L1.  Since the `loc->inserted' flag is only set
1499      on "master" locations, we'd forget to restore the shadow of L1
1500      and L2.  */
1501   while (bc_l > 0
1502          && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1503     bc_l--;
1504
1505   /* Now do full processing of the found relevant range of elements.  */
1506
1507   for (bc = bc_l; bc < bp_locations_count; bc++)
1508   {
1509     struct bp_location *bl = bp_locations[bc];
1510
1511     /* bp_location array has BL->OWNER always non-NULL.  */
1512     if (bl->owner->type == bp_none)
1513       warning (_("reading through apparently deleted breakpoint #%d?"),
1514                bl->owner->number);
1515
1516     /* Performance optimization: any further element can no longer affect BUF
1517        content.  */
1518
1519     if (bl->address >= bp_locations_placed_address_before_address_max
1520         && memaddr + len <= (bl->address
1521                              - bp_locations_placed_address_before_address_max))
1522       break;
1523
1524     if (!bp_location_has_shadow (bl))
1525       continue;
1526
1527     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1528                                 memaddr, len, &bl->target_info, bl->gdbarch);
1529   }
1530 }
1531
1532 \f
1533
1534 /* Return true if BPT is either a software breakpoint or a hardware
1535    breakpoint.  */
1536
1537 int
1538 is_breakpoint (const struct breakpoint *bpt)
1539 {
1540   return (bpt->type == bp_breakpoint
1541           || bpt->type == bp_hardware_breakpoint
1542           || bpt->type == bp_dprintf);
1543 }
1544
1545 /* Return true if BPT is of any hardware watchpoint kind.  */
1546
1547 static int
1548 is_hardware_watchpoint (const struct breakpoint *bpt)
1549 {
1550   return (bpt->type == bp_hardware_watchpoint
1551           || bpt->type == bp_read_watchpoint
1552           || bpt->type == bp_access_watchpoint);
1553 }
1554
1555 /* Return true if BPT is of any watchpoint kind, hardware or
1556    software.  */
1557
1558 int
1559 is_watchpoint (const struct breakpoint *bpt)
1560 {
1561   return (is_hardware_watchpoint (bpt)
1562           || bpt->type == bp_watchpoint);
1563 }
1564
1565 /* Returns true if the current thread and its running state are safe
1566    to evaluate or update watchpoint B.  Watchpoints on local
1567    expressions need to be evaluated in the context of the thread that
1568    was current when the watchpoint was created, and, that thread needs
1569    to be stopped to be able to select the correct frame context.
1570    Watchpoints on global expressions can be evaluated on any thread,
1571    and in any state.  It is presently left to the target allowing
1572    memory accesses when threads are running.  */
1573
1574 static int
1575 watchpoint_in_thread_scope (struct watchpoint *b)
1576 {
1577   return (b->pspace == current_program_space
1578           && (ptid_equal (b->watchpoint_thread, null_ptid)
1579               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1580                   && !is_executing (inferior_ptid))));
1581 }
1582
1583 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1584    associated bp_watchpoint_scope breakpoint.  */
1585
1586 static void
1587 watchpoint_del_at_next_stop (struct watchpoint *w)
1588 {
1589   if (w->related_breakpoint != w)
1590     {
1591       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1592       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1593       w->related_breakpoint->disposition = disp_del_at_next_stop;
1594       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1595       w->related_breakpoint = w;
1596     }
1597   w->disposition = disp_del_at_next_stop;
1598 }
1599
1600 /* Extract a bitfield value from value VAL using the bit parameters contained in
1601    watchpoint W.  */
1602
1603 static struct value *
1604 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1605 {
1606   struct value *bit_val;
1607
1608   if (val == NULL)
1609     return NULL;
1610
1611   bit_val = allocate_value (value_type (val));
1612
1613   unpack_value_bitfield (bit_val,
1614                          w->val_bitpos,
1615                          w->val_bitsize,
1616                          value_contents_for_printing (val),
1617                          value_offset (val),
1618                          val);
1619
1620   return bit_val;
1621 }
1622
1623 /* Allocate a dummy location and add it to B, which must be a software
1624    watchpoint.  This is required because even if a software watchpoint
1625    is not watching any memory, bpstat_stop_status requires a location
1626    to be able to report stops.  */
1627
1628 static void
1629 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1630                                             struct program_space *pspace)
1631 {
1632   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1633
1634   b->loc = allocate_bp_location (b);
1635   b->loc->pspace = pspace;
1636   b->loc->address = -1;
1637   b->loc->length = -1;
1638 }
1639
1640 /* Returns true if B is a software watchpoint that is not watching any
1641    memory (e.g., "watch $pc").  */
1642
1643 static int
1644 is_no_memory_software_watchpoint (struct breakpoint *b)
1645 {
1646   return (b->type == bp_watchpoint
1647           && b->loc != NULL
1648           && b->loc->next == NULL
1649           && b->loc->address == -1
1650           && b->loc->length == -1);
1651 }
1652
1653 /* Assuming that B is a watchpoint:
1654    - Reparse watchpoint expression, if REPARSE is non-zero
1655    - Evaluate expression and store the result in B->val
1656    - Evaluate the condition if there is one, and store the result
1657      in b->loc->cond.
1658    - Update the list of values that must be watched in B->loc.
1659
1660    If the watchpoint disposition is disp_del_at_next_stop, then do
1661    nothing.  If this is local watchpoint that is out of scope, delete
1662    it.
1663
1664    Even with `set breakpoint always-inserted on' the watchpoints are
1665    removed + inserted on each stop here.  Normal breakpoints must
1666    never be removed because they might be missed by a running thread
1667    when debugging in non-stop mode.  On the other hand, hardware
1668    watchpoints (is_hardware_watchpoint; processed here) are specific
1669    to each LWP since they are stored in each LWP's hardware debug
1670    registers.  Therefore, such LWP must be stopped first in order to
1671    be able to modify its hardware watchpoints.
1672
1673    Hardware watchpoints must be reset exactly once after being
1674    presented to the user.  It cannot be done sooner, because it would
1675    reset the data used to present the watchpoint hit to the user.  And
1676    it must not be done later because it could display the same single
1677    watchpoint hit during multiple GDB stops.  Note that the latter is
1678    relevant only to the hardware watchpoint types bp_read_watchpoint
1679    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1680    not user-visible - its hit is suppressed if the memory content has
1681    not changed.
1682
1683    The following constraints influence the location where we can reset
1684    hardware watchpoints:
1685
1686    * target_stopped_by_watchpoint and target_stopped_data_address are
1687      called several times when GDB stops.
1688
1689    [linux] 
1690    * Multiple hardware watchpoints can be hit at the same time,
1691      causing GDB to stop.  GDB only presents one hardware watchpoint
1692      hit at a time as the reason for stopping, and all the other hits
1693      are presented later, one after the other, each time the user
1694      requests the execution to be resumed.  Execution is not resumed
1695      for the threads still having pending hit event stored in
1696      LWP_INFO->STATUS.  While the watchpoint is already removed from
1697      the inferior on the first stop the thread hit event is kept being
1698      reported from its cached value by linux_nat_stopped_data_address
1699      until the real thread resume happens after the watchpoint gets
1700      presented and thus its LWP_INFO->STATUS gets reset.
1701
1702    Therefore the hardware watchpoint hit can get safely reset on the
1703    watchpoint removal from inferior.  */
1704
1705 static void
1706 update_watchpoint (struct watchpoint *b, int reparse)
1707 {
1708   int within_current_scope;
1709   struct frame_id saved_frame_id;
1710   int frame_saved;
1711
1712   /* If this is a local watchpoint, we only want to check if the
1713      watchpoint frame is in scope if the current thread is the thread
1714      that was used to create the watchpoint.  */
1715   if (!watchpoint_in_thread_scope (b))
1716     return;
1717
1718   if (b->disposition == disp_del_at_next_stop)
1719     return;
1720  
1721   frame_saved = 0;
1722
1723   /* Determine if the watchpoint is within scope.  */
1724   if (b->exp_valid_block == NULL)
1725     within_current_scope = 1;
1726   else
1727     {
1728       struct frame_info *fi = get_current_frame ();
1729       struct gdbarch *frame_arch = get_frame_arch (fi);
1730       CORE_ADDR frame_pc = get_frame_pc (fi);
1731
1732       /* If we're at a point where the stack has been destroyed
1733          (e.g. in a function epilogue), unwinding may not work
1734          properly. Do not attempt to recreate locations at this
1735          point.  See similar comments in watchpoint_check.  */
1736       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1737         return;
1738
1739       /* Save the current frame's ID so we can restore it after
1740          evaluating the watchpoint expression on its own frame.  */
1741       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1742          took a frame parameter, so that we didn't have to change the
1743          selected frame.  */
1744       frame_saved = 1;
1745       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1746
1747       fi = frame_find_by_id (b->watchpoint_frame);
1748       within_current_scope = (fi != NULL);
1749       if (within_current_scope)
1750         select_frame (fi);
1751     }
1752
1753   /* We don't free locations.  They are stored in the bp_location array
1754      and update_global_location_list will eventually delete them and
1755      remove breakpoints if needed.  */
1756   b->loc = NULL;
1757
1758   if (within_current_scope && reparse)
1759     {
1760       const char *s;
1761
1762       b->exp.reset ();
1763       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1764       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1765       /* If the meaning of expression itself changed, the old value is
1766          no longer relevant.  We don't want to report a watchpoint hit
1767          to the user when the old value and the new value may actually
1768          be completely different objects.  */
1769       value_free (b->val);
1770       b->val = NULL;
1771       b->val_valid = 0;
1772
1773       /* Note that unlike with breakpoints, the watchpoint's condition
1774          expression is stored in the breakpoint object, not in the
1775          locations (re)created below.  */
1776       if (b->cond_string != NULL)
1777         {
1778           b->cond_exp.reset ();
1779
1780           s = b->cond_string;
1781           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1782         }
1783     }
1784
1785   /* If we failed to parse the expression, for example because
1786      it refers to a global variable in a not-yet-loaded shared library,
1787      don't try to insert watchpoint.  We don't automatically delete
1788      such watchpoint, though, since failure to parse expression
1789      is different from out-of-scope watchpoint.  */
1790   if (!target_has_execution)
1791     {
1792       /* Without execution, memory can't change.  No use to try and
1793          set watchpoint locations.  The watchpoint will be reset when
1794          the target gains execution, through breakpoint_re_set.  */
1795       if (!can_use_hw_watchpoints)
1796         {
1797           if (b->ops->works_in_software_mode (b))
1798             b->type = bp_watchpoint;
1799           else
1800             error (_("Can't set read/access watchpoint when "
1801                      "hardware watchpoints are disabled."));
1802         }
1803     }
1804   else if (within_current_scope && b->exp)
1805     {
1806       int pc = 0;
1807       struct value *val_chain, *v, *result, *next;
1808       struct program_space *frame_pspace;
1809
1810       fetch_subexp_value (b->exp.get (), &pc, &v, &result, &val_chain, 0);
1811
1812       /* Avoid setting b->val if it's already set.  The meaning of
1813          b->val is 'the last value' user saw, and we should update
1814          it only if we reported that last value to user.  As it
1815          happens, the code that reports it updates b->val directly.
1816          We don't keep track of the memory value for masked
1817          watchpoints.  */
1818       if (!b->val_valid && !is_masked_watchpoint (b))
1819         {
1820           if (b->val_bitsize != 0)
1821             {
1822               v = extract_bitfield_from_watchpoint_value (b, v);
1823               if (v != NULL)
1824                 release_value (v);
1825             }
1826           b->val = v;
1827           b->val_valid = 1;
1828         }
1829
1830       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1831
1832       /* Look at each value on the value chain.  */
1833       for (v = val_chain; v; v = value_next (v))
1834         {
1835           /* If it's a memory location, and GDB actually needed
1836              its contents to evaluate the expression, then we
1837              must watch it.  If the first value returned is
1838              still lazy, that means an error occurred reading it;
1839              watch it anyway in case it becomes readable.  */
1840           if (VALUE_LVAL (v) == lval_memory
1841               && (v == val_chain || ! value_lazy (v)))
1842             {
1843               struct type *vtype = check_typedef (value_type (v));
1844
1845               /* We only watch structs and arrays if user asked
1846                  for it explicitly, never if they just happen to
1847                  appear in the middle of some value chain.  */
1848               if (v == result
1849                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1850                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1851                 {
1852                   CORE_ADDR addr;
1853                   enum target_hw_bp_type type;
1854                   struct bp_location *loc, **tmp;
1855                   int bitpos = 0, bitsize = 0;
1856
1857                   if (value_bitsize (v) != 0)
1858                     {
1859                       /* Extract the bit parameters out from the bitfield
1860                          sub-expression.  */
1861                       bitpos = value_bitpos (v);
1862                       bitsize = value_bitsize (v);
1863                     }
1864                   else if (v == result && b->val_bitsize != 0)
1865                     {
1866                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1867                         lvalue whose bit parameters are saved in the fields
1868                         VAL_BITPOS and VAL_BITSIZE.  */
1869                       bitpos = b->val_bitpos;
1870                       bitsize = b->val_bitsize;
1871                     }
1872
1873                   addr = value_address (v);
1874                   if (bitsize != 0)
1875                     {
1876                       /* Skip the bytes that don't contain the bitfield.  */
1877                       addr += bitpos / 8;
1878                     }
1879
1880                   type = hw_write;
1881                   if (b->type == bp_read_watchpoint)
1882                     type = hw_read;
1883                   else if (b->type == bp_access_watchpoint)
1884                     type = hw_access;
1885
1886                   loc = allocate_bp_location (b);
1887                   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
1888                     ;
1889                   *tmp = loc;
1890                   loc->gdbarch = get_type_arch (value_type (v));
1891
1892                   loc->pspace = frame_pspace;
1893                   loc->address = addr;
1894
1895                   if (bitsize != 0)
1896                     {
1897                       /* Just cover the bytes that make up the bitfield.  */
1898                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
1899                     }
1900                   else
1901                     loc->length = TYPE_LENGTH (value_type (v));
1902
1903                   loc->watchpoint_type = type;
1904                 }
1905             }
1906         }
1907
1908       /* Change the type of breakpoint between hardware assisted or
1909          an ordinary watchpoint depending on the hardware support
1910          and free hardware slots.  REPARSE is set when the inferior
1911          is started.  */
1912       if (reparse)
1913         {
1914           int reg_cnt;
1915           enum bp_loc_type loc_type;
1916           struct bp_location *bl;
1917
1918           reg_cnt = can_use_hardware_watchpoint (val_chain);
1919
1920           if (reg_cnt)
1921             {
1922               int i, target_resources_ok, other_type_used;
1923               enum bptype type;
1924
1925               /* Use an exact watchpoint when there's only one memory region to be
1926                  watched, and only one debug register is needed to watch it.  */
1927               b->exact = target_exact_watchpoints && reg_cnt == 1;
1928
1929               /* We need to determine how many resources are already
1930                  used for all other hardware watchpoints plus this one
1931                  to see if we still have enough resources to also fit
1932                  this watchpoint in as well.  */
1933
1934               /* If this is a software watchpoint, we try to turn it
1935                  to a hardware one -- count resources as if B was of
1936                  hardware watchpoint type.  */
1937               type = b->type;
1938               if (type == bp_watchpoint)
1939                 type = bp_hardware_watchpoint;
1940
1941               /* This watchpoint may or may not have been placed on
1942                  the list yet at this point (it won't be in the list
1943                  if we're trying to create it for the first time,
1944                  through watch_command), so always account for it
1945                  manually.  */
1946
1947               /* Count resources used by all watchpoints except B.  */
1948               i = hw_watchpoint_used_count_others (b, type, &other_type_used);
1949
1950               /* Add in the resources needed for B.  */
1951               i += hw_watchpoint_use_count (b);
1952
1953               target_resources_ok
1954                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1955               if (target_resources_ok <= 0)
1956                 {
1957                   int sw_mode = b->ops->works_in_software_mode (b);
1958
1959                   if (target_resources_ok == 0 && !sw_mode)
1960                     error (_("Target does not support this type of "
1961                              "hardware watchpoint."));
1962                   else if (target_resources_ok < 0 && !sw_mode)
1963                     error (_("There are not enough available hardware "
1964                              "resources for this watchpoint."));
1965
1966                   /* Downgrade to software watchpoint.  */
1967                   b->type = bp_watchpoint;
1968                 }
1969               else
1970                 {
1971                   /* If this was a software watchpoint, we've just
1972                      found we have enough resources to turn it to a
1973                      hardware watchpoint.  Otherwise, this is a
1974                      nop.  */
1975                   b->type = type;
1976                 }
1977             }
1978           else if (!b->ops->works_in_software_mode (b))
1979             {
1980               if (!can_use_hw_watchpoints)
1981                 error (_("Can't set read/access watchpoint when "
1982                          "hardware watchpoints are disabled."));
1983               else
1984                 error (_("Expression cannot be implemented with "
1985                          "read/access watchpoint."));
1986             }
1987           else
1988             b->type = bp_watchpoint;
1989
1990           loc_type = (b->type == bp_watchpoint? bp_loc_other
1991                       : bp_loc_hardware_watchpoint);
1992           for (bl = b->loc; bl; bl = bl->next)
1993             bl->loc_type = loc_type;
1994         }
1995
1996       for (v = val_chain; v; v = next)
1997         {
1998           next = value_next (v);
1999           if (v != b->val)
2000             value_free (v);
2001         }
2002
2003       /* If a software watchpoint is not watching any memory, then the
2004          above left it without any location set up.  But,
2005          bpstat_stop_status requires a location to be able to report
2006          stops, so make sure there's at least a dummy one.  */
2007       if (b->type == bp_watchpoint && b->loc == NULL)
2008         software_watchpoint_add_no_memory_location (b, frame_pspace);
2009     }
2010   else if (!within_current_scope)
2011     {
2012       printf_filtered (_("\
2013 Watchpoint %d deleted because the program has left the block\n\
2014 in which its expression is valid.\n"),
2015                        b->number);
2016       watchpoint_del_at_next_stop (b);
2017     }
2018
2019   /* Restore the selected frame.  */
2020   if (frame_saved)
2021     select_frame (frame_find_by_id (saved_frame_id));
2022 }
2023
2024
2025 /* Returns 1 iff breakpoint location should be
2026    inserted in the inferior.  We don't differentiate the type of BL's owner
2027    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2028    breakpoint_ops is not defined, because in insert_bp_location,
2029    tracepoint's insert_location will not be called.  */
2030 static int
2031 should_be_inserted (struct bp_location *bl)
2032 {
2033   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2034     return 0;
2035
2036   if (bl->owner->disposition == disp_del_at_next_stop)
2037     return 0;
2038
2039   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2040     return 0;
2041
2042   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2043     return 0;
2044
2045   /* This is set for example, when we're attached to the parent of a
2046      vfork, and have detached from the child.  The child is running
2047      free, and we expect it to do an exec or exit, at which point the
2048      OS makes the parent schedulable again (and the target reports
2049      that the vfork is done).  Until the child is done with the shared
2050      memory region, do not insert breakpoints in the parent, otherwise
2051      the child could still trip on the parent's breakpoints.  Since
2052      the parent is blocked anyway, it won't miss any breakpoint.  */
2053   if (bl->pspace->breakpoints_not_allowed)
2054     return 0;
2055
2056   /* Don't insert a breakpoint if we're trying to step past its
2057      location, except if the breakpoint is a single-step breakpoint,
2058      and the breakpoint's thread is the thread which is stepping past
2059      a breakpoint.  */
2060   if ((bl->loc_type == bp_loc_software_breakpoint
2061        || bl->loc_type == bp_loc_hardware_breakpoint)
2062       && stepping_past_instruction_at (bl->pspace->aspace,
2063                                        bl->address)
2064       /* The single-step breakpoint may be inserted at the location
2065          we're trying to step if the instruction branches to itself.
2066          However, the instruction won't be executed at all and it may
2067          break the semantics of the instruction, for example, the
2068          instruction is a conditional branch or updates some flags.
2069          We can't fix it unless GDB is able to emulate the instruction
2070          or switch to displaced stepping.  */
2071       && !(bl->owner->type == bp_single_step
2072            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2073     {
2074       if (debug_infrun)
2075         {
2076           fprintf_unfiltered (gdb_stdlog,
2077                               "infrun: skipping breakpoint: "
2078                               "stepping past insn at: %s\n",
2079                               paddress (bl->gdbarch, bl->address));
2080         }
2081       return 0;
2082     }
2083
2084   /* Don't insert watchpoints if we're trying to step past the
2085      instruction that triggered one.  */
2086   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2087       && stepping_past_nonsteppable_watchpoint ())
2088     {
2089       if (debug_infrun)
2090         {
2091           fprintf_unfiltered (gdb_stdlog,
2092                               "infrun: stepping past non-steppable watchpoint. "
2093                               "skipping watchpoint at %s:%d\n",
2094                               paddress (bl->gdbarch, bl->address),
2095                               bl->length);
2096         }
2097       return 0;
2098     }
2099
2100   return 1;
2101 }
2102
2103 /* Same as should_be_inserted but does the check assuming
2104    that the location is not duplicated.  */
2105
2106 static int
2107 unduplicated_should_be_inserted (struct bp_location *bl)
2108 {
2109   int result;
2110   const int save_duplicate = bl->duplicate;
2111
2112   bl->duplicate = 0;
2113   result = should_be_inserted (bl);
2114   bl->duplicate = save_duplicate;
2115   return result;
2116 }
2117
2118 /* Parses a conditional described by an expression COND into an
2119    agent expression bytecode suitable for evaluation
2120    by the bytecode interpreter.  Return NULL if there was
2121    any error during parsing.  */
2122
2123 static agent_expr_up
2124 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2125 {
2126   if (cond == NULL)
2127     return NULL;
2128
2129   agent_expr_up aexpr;
2130
2131   /* We don't want to stop processing, so catch any errors
2132      that may show up.  */
2133   TRY
2134     {
2135       aexpr = gen_eval_for_expr (scope, cond);
2136     }
2137
2138   CATCH (ex, RETURN_MASK_ERROR)
2139     {
2140       /* If we got here, it means the condition could not be parsed to a valid
2141          bytecode expression and thus can't be evaluated on the target's side.
2142          It's no use iterating through the conditions.  */
2143     }
2144   END_CATCH
2145
2146   /* We have a valid agent expression.  */
2147   return aexpr;
2148 }
2149
2150 /* Based on location BL, create a list of breakpoint conditions to be
2151    passed on to the target.  If we have duplicated locations with different
2152    conditions, we will add such conditions to the list.  The idea is that the
2153    target will evaluate the list of conditions and will only notify GDB when
2154    one of them is true.  */
2155
2156 static void
2157 build_target_condition_list (struct bp_location *bl)
2158 {
2159   struct bp_location **locp = NULL, **loc2p;
2160   int null_condition_or_parse_error = 0;
2161   int modified = bl->needs_update;
2162   struct bp_location *loc;
2163
2164   /* Release conditions left over from a previous insert.  */
2165   bl->target_info.conditions.clear ();
2166
2167   /* This is only meaningful if the target is
2168      evaluating conditions and if the user has
2169      opted for condition evaluation on the target's
2170      side.  */
2171   if (gdb_evaluates_breakpoint_condition_p ()
2172       || !target_supports_evaluation_of_breakpoint_conditions ())
2173     return;
2174
2175   /* Do a first pass to check for locations with no assigned
2176      conditions or conditions that fail to parse to a valid agent expression
2177      bytecode.  If any of these happen, then it's no use to send conditions
2178      to the target since this location will always trigger and generate a
2179      response back to GDB.  */
2180   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2181     {
2182       loc = (*loc2p);
2183       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2184         {
2185           if (modified)
2186             {
2187               /* Re-parse the conditions since something changed.  In that
2188                  case we already freed the condition bytecodes (see
2189                  force_breakpoint_reinsertion).  We just
2190                  need to parse the condition to bytecodes again.  */
2191               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2192                                                         loc->cond.get ());
2193             }
2194
2195           /* If we have a NULL bytecode expression, it means something
2196              went wrong or we have a null condition expression.  */
2197           if (!loc->cond_bytecode)
2198             {
2199               null_condition_or_parse_error = 1;
2200               break;
2201             }
2202         }
2203     }
2204
2205   /* If any of these happened, it means we will have to evaluate the conditions
2206      for the location's address on gdb's side.  It is no use keeping bytecodes
2207      for all the other duplicate locations, thus we free all of them here.
2208
2209      This is so we have a finer control over which locations' conditions are
2210      being evaluated by GDB or the remote stub.  */
2211   if (null_condition_or_parse_error)
2212     {
2213       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2214         {
2215           loc = (*loc2p);
2216           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2217             {
2218               /* Only go as far as the first NULL bytecode is
2219                  located.  */
2220               if (!loc->cond_bytecode)
2221                 return;
2222
2223               loc->cond_bytecode.reset ();
2224             }
2225         }
2226     }
2227
2228   /* No NULL conditions or failed bytecode generation.  Build a condition list
2229      for this location's address.  */
2230   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2231     {
2232       loc = (*loc2p);
2233       if (loc->cond
2234           && is_breakpoint (loc->owner)
2235           && loc->pspace->num == bl->pspace->num
2236           && loc->owner->enable_state == bp_enabled
2237           && loc->enabled)
2238         {
2239           /* Add the condition to the vector.  This will be used later
2240              to send the conditions to the target.  */
2241           bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2242         }
2243     }
2244
2245   return;
2246 }
2247
2248 /* Parses a command described by string CMD into an agent expression
2249    bytecode suitable for evaluation by the bytecode interpreter.
2250    Return NULL if there was any error during parsing.  */
2251
2252 static agent_expr_up
2253 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2254 {
2255   struct cleanup *old_cleanups = 0;
2256   struct expression **argvec;
2257   const char *cmdrest;
2258   const char *format_start, *format_end;
2259   struct format_piece *fpieces;
2260   int nargs;
2261   struct gdbarch *gdbarch = get_current_arch ();
2262
2263   if (cmd == NULL)
2264     return NULL;
2265
2266   cmdrest = cmd;
2267
2268   if (*cmdrest == ',')
2269     ++cmdrest;
2270   cmdrest = skip_spaces (cmdrest);
2271
2272   if (*cmdrest++ != '"')
2273     error (_("No format string following the location"));
2274
2275   format_start = cmdrest;
2276
2277   fpieces = parse_format_string (&cmdrest);
2278
2279   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2280
2281   format_end = cmdrest;
2282
2283   if (*cmdrest++ != '"')
2284     error (_("Bad format string, non-terminated '\"'."));
2285   
2286   cmdrest = skip_spaces (cmdrest);
2287
2288   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2289     error (_("Invalid argument syntax"));
2290
2291   if (*cmdrest == ',')
2292     cmdrest++;
2293   cmdrest = skip_spaces (cmdrest);
2294
2295   /* For each argument, make an expression.  */
2296
2297   argvec = (struct expression **) alloca (strlen (cmd)
2298                                          * sizeof (struct expression *));
2299
2300   nargs = 0;
2301   while (*cmdrest != '\0')
2302     {
2303       const char *cmd1;
2304
2305       cmd1 = cmdrest;
2306       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2307       argvec[nargs++] = expr.release ();
2308       cmdrest = cmd1;
2309       if (*cmdrest == ',')
2310         ++cmdrest;
2311     }
2312
2313   agent_expr_up aexpr;
2314
2315   /* We don't want to stop processing, so catch any errors
2316      that may show up.  */
2317   TRY
2318     {
2319       aexpr = gen_printf (scope, gdbarch, 0, 0,
2320                           format_start, format_end - format_start,
2321                           fpieces, nargs, argvec);
2322     }
2323   CATCH (ex, RETURN_MASK_ERROR)
2324     {
2325       /* If we got here, it means the command could not be parsed to a valid
2326          bytecode expression and thus can't be evaluated on the target's side.
2327          It's no use iterating through the other commands.  */
2328     }
2329   END_CATCH
2330
2331   do_cleanups (old_cleanups);
2332
2333   /* We have a valid agent expression, return it.  */
2334   return aexpr;
2335 }
2336
2337 /* Based on location BL, create a list of breakpoint commands to be
2338    passed on to the target.  If we have duplicated locations with
2339    different commands, we will add any such to the list.  */
2340
2341 static void
2342 build_target_command_list (struct bp_location *bl)
2343 {
2344   struct bp_location **locp = NULL, **loc2p;
2345   int null_command_or_parse_error = 0;
2346   int modified = bl->needs_update;
2347   struct bp_location *loc;
2348
2349   /* Clear commands left over from a previous insert.  */
2350   bl->target_info.tcommands.clear ();
2351
2352   if (!target_can_run_breakpoint_commands ())
2353     return;
2354
2355   /* For now, limit to agent-style dprintf breakpoints.  */
2356   if (dprintf_style != dprintf_style_agent)
2357     return;
2358
2359   /* For now, if we have any duplicate location that isn't a dprintf,
2360      don't install the target-side commands, as that would make the
2361      breakpoint not be reported to the core, and we'd lose
2362      control.  */
2363   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2364     {
2365       loc = (*loc2p);
2366       if (is_breakpoint (loc->owner)
2367           && loc->pspace->num == bl->pspace->num
2368           && loc->owner->type != bp_dprintf)
2369         return;
2370     }
2371
2372   /* Do a first pass to check for locations with no assigned
2373      conditions or conditions that fail to parse to a valid agent expression
2374      bytecode.  If any of these happen, then it's no use to send conditions
2375      to the target since this location will always trigger and generate a
2376      response back to GDB.  */
2377   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2378     {
2379       loc = (*loc2p);
2380       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2381         {
2382           if (modified)
2383             {
2384               /* Re-parse the commands since something changed.  In that
2385                  case we already freed the command bytecodes (see
2386                  force_breakpoint_reinsertion).  We just
2387                  need to parse the command to bytecodes again.  */
2388               loc->cmd_bytecode
2389                 = parse_cmd_to_aexpr (bl->address,
2390                                       loc->owner->extra_string);
2391             }
2392
2393           /* If we have a NULL bytecode expression, it means something
2394              went wrong or we have a null command expression.  */
2395           if (!loc->cmd_bytecode)
2396             {
2397               null_command_or_parse_error = 1;
2398               break;
2399             }
2400         }
2401     }
2402
2403   /* If anything failed, then we're not doing target-side commands,
2404      and so clean up.  */
2405   if (null_command_or_parse_error)
2406     {
2407       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2408         {
2409           loc = (*loc2p);
2410           if (is_breakpoint (loc->owner)
2411               && loc->pspace->num == bl->pspace->num)
2412             {
2413               /* Only go as far as the first NULL bytecode is
2414                  located.  */
2415               if (loc->cmd_bytecode == NULL)
2416                 return;
2417
2418               loc->cmd_bytecode.reset ();
2419             }
2420         }
2421     }
2422
2423   /* No NULL commands or failed bytecode generation.  Build a command list
2424      for this location's address.  */
2425   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2426     {
2427       loc = (*loc2p);
2428       if (loc->owner->extra_string
2429           && is_breakpoint (loc->owner)
2430           && loc->pspace->num == bl->pspace->num
2431           && loc->owner->enable_state == bp_enabled
2432           && loc->enabled)
2433         {
2434           /* Add the command to the vector.  This will be used later
2435              to send the commands to the target.  */
2436           bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2437         }
2438     }
2439
2440   bl->target_info.persist = 0;
2441   /* Maybe flag this location as persistent.  */
2442   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2443     bl->target_info.persist = 1;
2444 }
2445
2446 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2447    of breakpoint according to ADDR except single-step breakpoint.
2448    Get the kind of single-step breakpoint according to the current
2449    registers state.  */
2450
2451 static int
2452 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2453 {
2454   if (bl->owner->type == bp_single_step)
2455     {
2456       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2457       struct regcache *regcache;
2458
2459       regcache = get_thread_regcache (thr->ptid);
2460
2461       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2462                                                          regcache, addr);
2463     }
2464   else
2465     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2466 }
2467
2468 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2469    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2470    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2471    Returns 0 for success, 1 if the bp_location type is not supported or
2472    -1 for failure.
2473
2474    NOTE drow/2003-09-09: This routine could be broken down to an
2475    object-style method for each breakpoint or catchpoint type.  */
2476 static int
2477 insert_bp_location (struct bp_location *bl,
2478                     struct ui_file *tmp_error_stream,
2479                     int *disabled_breaks,
2480                     int *hw_breakpoint_error,
2481                     int *hw_bp_error_explained_already)
2482 {
2483   enum errors bp_err = GDB_NO_ERROR;
2484   const char *bp_err_message = NULL;
2485
2486   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2487     return 0;
2488
2489   /* Note we don't initialize bl->target_info, as that wipes out
2490      the breakpoint location's shadow_contents if the breakpoint
2491      is still inserted at that location.  This in turn breaks
2492      target_read_memory which depends on these buffers when
2493      a memory read is requested at the breakpoint location:
2494      Once the target_info has been wiped, we fail to see that
2495      we have a breakpoint inserted at that address and thus
2496      read the breakpoint instead of returning the data saved in
2497      the breakpoint location's shadow contents.  */
2498   bl->target_info.reqstd_address = bl->address;
2499   bl->target_info.placed_address_space = bl->pspace->aspace;
2500   bl->target_info.length = bl->length;
2501
2502   /* When working with target-side conditions, we must pass all the conditions
2503      for the same breakpoint address down to the target since GDB will not
2504      insert those locations.  With a list of breakpoint conditions, the target
2505      can decide when to stop and notify GDB.  */
2506
2507   if (is_breakpoint (bl->owner))
2508     {
2509       build_target_condition_list (bl);
2510       build_target_command_list (bl);
2511       /* Reset the modification marker.  */
2512       bl->needs_update = 0;
2513     }
2514
2515   if (bl->loc_type == bp_loc_software_breakpoint
2516       || bl->loc_type == bp_loc_hardware_breakpoint)
2517     {
2518       if (bl->owner->type != bp_hardware_breakpoint)
2519         {
2520           /* If the explicitly specified breakpoint type
2521              is not hardware breakpoint, check the memory map to see
2522              if the breakpoint address is in read only memory or not.
2523
2524              Two important cases are:
2525              - location type is not hardware breakpoint, memory
2526              is readonly.  We change the type of the location to
2527              hardware breakpoint.
2528              - location type is hardware breakpoint, memory is
2529              read-write.  This means we've previously made the
2530              location hardware one, but then the memory map changed,
2531              so we undo.
2532              
2533              When breakpoints are removed, remove_breakpoints will use
2534              location types we've just set here, the only possible
2535              problem is that memory map has changed during running
2536              program, but it's not going to work anyway with current
2537              gdb.  */
2538           struct mem_region *mr 
2539             = lookup_mem_region (bl->target_info.reqstd_address);
2540           
2541           if (mr)
2542             {
2543               if (automatic_hardware_breakpoints)
2544                 {
2545                   enum bp_loc_type new_type;
2546                   
2547                   if (mr->attrib.mode != MEM_RW)
2548                     new_type = bp_loc_hardware_breakpoint;
2549                   else 
2550                     new_type = bp_loc_software_breakpoint;
2551                   
2552                   if (new_type != bl->loc_type)
2553                     {
2554                       static int said = 0;
2555
2556                       bl->loc_type = new_type;
2557                       if (!said)
2558                         {
2559                           fprintf_filtered (gdb_stdout,
2560                                             _("Note: automatically using "
2561                                               "hardware breakpoints for "
2562                                               "read-only addresses.\n"));
2563                           said = 1;
2564                         }
2565                     }
2566                 }
2567               else if (bl->loc_type == bp_loc_software_breakpoint
2568                        && mr->attrib.mode != MEM_RW)
2569                 {
2570                   fprintf_unfiltered (tmp_error_stream,
2571                                       _("Cannot insert breakpoint %d.\n"
2572                                         "Cannot set software breakpoint "
2573                                         "at read-only address %s\n"),
2574                                       bl->owner->number,
2575                                       paddress (bl->gdbarch, bl->address));
2576                   return 1;
2577                 }
2578             }
2579         }
2580         
2581       /* First check to see if we have to handle an overlay.  */
2582       if (overlay_debugging == ovly_off
2583           || bl->section == NULL
2584           || !(section_is_overlay (bl->section)))
2585         {
2586           /* No overlay handling: just set the breakpoint.  */
2587           TRY
2588             {
2589               int val;
2590
2591               val = bl->owner->ops->insert_location (bl);
2592               if (val)
2593                 bp_err = GENERIC_ERROR;
2594             }
2595           CATCH (e, RETURN_MASK_ALL)
2596             {
2597               bp_err = e.error;
2598               bp_err_message = e.message;
2599             }
2600           END_CATCH
2601         }
2602       else
2603         {
2604           /* This breakpoint is in an overlay section.
2605              Shall we set a breakpoint at the LMA?  */
2606           if (!overlay_events_enabled)
2607             {
2608               /* Yes -- overlay event support is not active, 
2609                  so we must try to set a breakpoint at the LMA.
2610                  This will not work for a hardware breakpoint.  */
2611               if (bl->loc_type == bp_loc_hardware_breakpoint)
2612                 warning (_("hardware breakpoint %d not supported in overlay!"),
2613                          bl->owner->number);
2614               else
2615                 {
2616                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2617                                                              bl->section);
2618                   /* Set a software (trap) breakpoint at the LMA.  */
2619                   bl->overlay_target_info = bl->target_info;
2620                   bl->overlay_target_info.reqstd_address = addr;
2621
2622                   /* No overlay handling: just set the breakpoint.  */
2623                   TRY
2624                     {
2625                       int val;
2626
2627                       bl->overlay_target_info.kind
2628                         = breakpoint_kind (bl, &addr);
2629                       bl->overlay_target_info.placed_address = addr;
2630                       val = target_insert_breakpoint (bl->gdbarch,
2631                                                       &bl->overlay_target_info);
2632                       if (val)
2633                         bp_err = GENERIC_ERROR;
2634                     }
2635                   CATCH (e, RETURN_MASK_ALL)
2636                     {
2637                       bp_err = e.error;
2638                       bp_err_message = e.message;
2639                     }
2640                   END_CATCH
2641
2642                   if (bp_err != GDB_NO_ERROR)
2643                     fprintf_unfiltered (tmp_error_stream,
2644                                         "Overlay breakpoint %d "
2645                                         "failed: in ROM?\n",
2646                                         bl->owner->number);
2647                 }
2648             }
2649           /* Shall we set a breakpoint at the VMA? */
2650           if (section_is_mapped (bl->section))
2651             {
2652               /* Yes.  This overlay section is mapped into memory.  */
2653               TRY
2654                 {
2655                   int val;
2656
2657                   val = bl->owner->ops->insert_location (bl);
2658                   if (val)
2659                     bp_err = GENERIC_ERROR;
2660                 }
2661               CATCH (e, RETURN_MASK_ALL)
2662                 {
2663                   bp_err = e.error;
2664                   bp_err_message = e.message;
2665                 }
2666               END_CATCH
2667             }
2668           else
2669             {
2670               /* No.  This breakpoint will not be inserted.  
2671                  No error, but do not mark the bp as 'inserted'.  */
2672               return 0;
2673             }
2674         }
2675
2676       if (bp_err != GDB_NO_ERROR)
2677         {
2678           /* Can't set the breakpoint.  */
2679
2680           /* In some cases, we might not be able to insert a
2681              breakpoint in a shared library that has already been
2682              removed, but we have not yet processed the shlib unload
2683              event.  Unfortunately, some targets that implement
2684              breakpoint insertion themselves can't tell why the
2685              breakpoint insertion failed (e.g., the remote target
2686              doesn't define error codes), so we must treat generic
2687              errors as memory errors.  */
2688           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2689               && bl->loc_type == bp_loc_software_breakpoint
2690               && (solib_name_from_address (bl->pspace, bl->address)
2691                   || shared_objfile_contains_address_p (bl->pspace,
2692                                                         bl->address)))
2693             {
2694               /* See also: disable_breakpoints_in_shlibs.  */
2695               bl->shlib_disabled = 1;
2696               observer_notify_breakpoint_modified (bl->owner);
2697               if (!*disabled_breaks)
2698                 {
2699                   fprintf_unfiltered (tmp_error_stream, 
2700                                       "Cannot insert breakpoint %d.\n", 
2701                                       bl->owner->number);
2702                   fprintf_unfiltered (tmp_error_stream, 
2703                                       "Temporarily disabling shared "
2704                                       "library breakpoints:\n");
2705                 }
2706               *disabled_breaks = 1;
2707               fprintf_unfiltered (tmp_error_stream,
2708                                   "breakpoint #%d\n", bl->owner->number);
2709               return 0;
2710             }
2711           else
2712             {
2713               if (bl->loc_type == bp_loc_hardware_breakpoint)
2714                 {
2715                   *hw_breakpoint_error = 1;
2716                   *hw_bp_error_explained_already = bp_err_message != NULL;
2717                   fprintf_unfiltered (tmp_error_stream,
2718                                       "Cannot insert hardware breakpoint %d%s",
2719                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2720                   if (bp_err_message != NULL)
2721                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2722                 }
2723               else
2724                 {
2725                   if (bp_err_message == NULL)
2726                     {
2727                       std::string message
2728                         = memory_error_message (TARGET_XFER_E_IO,
2729                                                 bl->gdbarch, bl->address);
2730
2731                       fprintf_unfiltered (tmp_error_stream,
2732                                           "Cannot insert breakpoint %d.\n"
2733                                           "%s\n",
2734                                           bl->owner->number, message.c_str ());
2735                     }
2736                   else
2737                     {
2738                       fprintf_unfiltered (tmp_error_stream,
2739                                           "Cannot insert breakpoint %d: %s\n",
2740                                           bl->owner->number,
2741                                           bp_err_message);
2742                     }
2743                 }
2744               return 1;
2745
2746             }
2747         }
2748       else
2749         bl->inserted = 1;
2750
2751       return 0;
2752     }
2753
2754   else if (bl->loc_type == bp_loc_hardware_watchpoint
2755            /* NOTE drow/2003-09-08: This state only exists for removing
2756               watchpoints.  It's not clear that it's necessary...  */
2757            && bl->owner->disposition != disp_del_at_next_stop)
2758     {
2759       int val;
2760
2761       gdb_assert (bl->owner->ops != NULL
2762                   && bl->owner->ops->insert_location != NULL);
2763
2764       val = bl->owner->ops->insert_location (bl);
2765
2766       /* If trying to set a read-watchpoint, and it turns out it's not
2767          supported, try emulating one with an access watchpoint.  */
2768       if (val == 1 && bl->watchpoint_type == hw_read)
2769         {
2770           struct bp_location *loc, **loc_temp;
2771
2772           /* But don't try to insert it, if there's already another
2773              hw_access location that would be considered a duplicate
2774              of this one.  */
2775           ALL_BP_LOCATIONS (loc, loc_temp)
2776             if (loc != bl
2777                 && loc->watchpoint_type == hw_access
2778                 && watchpoint_locations_match (bl, loc))
2779               {
2780                 bl->duplicate = 1;
2781                 bl->inserted = 1;
2782                 bl->target_info = loc->target_info;
2783                 bl->watchpoint_type = hw_access;
2784                 val = 0;
2785                 break;
2786               }
2787
2788           if (val == 1)
2789             {
2790               bl->watchpoint_type = hw_access;
2791               val = bl->owner->ops->insert_location (bl);
2792
2793               if (val)
2794                 /* Back to the original value.  */
2795                 bl->watchpoint_type = hw_read;
2796             }
2797         }
2798
2799       bl->inserted = (val == 0);
2800     }
2801
2802   else if (bl->owner->type == bp_catchpoint)
2803     {
2804       int val;
2805
2806       gdb_assert (bl->owner->ops != NULL
2807                   && bl->owner->ops->insert_location != NULL);
2808
2809       val = bl->owner->ops->insert_location (bl);
2810       if (val)
2811         {
2812           bl->owner->enable_state = bp_disabled;
2813
2814           if (val == 1)
2815             warning (_("\
2816 Error inserting catchpoint %d: Your system does not support this type\n\
2817 of catchpoint."), bl->owner->number);
2818           else
2819             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2820         }
2821
2822       bl->inserted = (val == 0);
2823
2824       /* We've already printed an error message if there was a problem
2825          inserting this catchpoint, and we've disabled the catchpoint,
2826          so just return success.  */
2827       return 0;
2828     }
2829
2830   return 0;
2831 }
2832
2833 /* This function is called when program space PSPACE is about to be
2834    deleted.  It takes care of updating breakpoints to not reference
2835    PSPACE anymore.  */
2836
2837 void
2838 breakpoint_program_space_exit (struct program_space *pspace)
2839 {
2840   struct breakpoint *b, *b_temp;
2841   struct bp_location *loc, **loc_temp;
2842
2843   /* Remove any breakpoint that was set through this program space.  */
2844   ALL_BREAKPOINTS_SAFE (b, b_temp)
2845     {
2846       if (b->pspace == pspace)
2847         delete_breakpoint (b);
2848     }
2849
2850   /* Breakpoints set through other program spaces could have locations
2851      bound to PSPACE as well.  Remove those.  */
2852   ALL_BP_LOCATIONS (loc, loc_temp)
2853     {
2854       struct bp_location *tmp;
2855
2856       if (loc->pspace == pspace)
2857         {
2858           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2859           if (loc->owner->loc == loc)
2860             loc->owner->loc = loc->next;
2861           else
2862             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2863               if (tmp->next == loc)
2864                 {
2865                   tmp->next = loc->next;
2866                   break;
2867                 }
2868         }
2869     }
2870
2871   /* Now update the global location list to permanently delete the
2872      removed locations above.  */
2873   update_global_location_list (UGLL_DONT_INSERT);
2874 }
2875
2876 /* Make sure all breakpoints are inserted in inferior.
2877    Throws exception on any error.
2878    A breakpoint that is already inserted won't be inserted
2879    again, so calling this function twice is safe.  */
2880 void
2881 insert_breakpoints (void)
2882 {
2883   struct breakpoint *bpt;
2884
2885   ALL_BREAKPOINTS (bpt)
2886     if (is_hardware_watchpoint (bpt))
2887       {
2888         struct watchpoint *w = (struct watchpoint *) bpt;
2889
2890         update_watchpoint (w, 0 /* don't reparse.  */);
2891       }
2892
2893   /* Updating watchpoints creates new locations, so update the global
2894      location list.  Explicitly tell ugll to insert locations and
2895      ignore breakpoints_always_inserted_mode.  */
2896   update_global_location_list (UGLL_INSERT);
2897 }
2898
2899 /* Invoke CALLBACK for each of bp_location.  */
2900
2901 void
2902 iterate_over_bp_locations (walk_bp_location_callback callback)
2903 {
2904   struct bp_location *loc, **loc_tmp;
2905
2906   ALL_BP_LOCATIONS (loc, loc_tmp)
2907     {
2908       callback (loc, NULL);
2909     }
2910 }
2911
2912 /* This is used when we need to synch breakpoint conditions between GDB and the
2913    target.  It is the case with deleting and disabling of breakpoints when using
2914    always-inserted mode.  */
2915
2916 static void
2917 update_inserted_breakpoint_locations (void)
2918 {
2919   struct bp_location *bl, **blp_tmp;
2920   int error_flag = 0;
2921   int val = 0;
2922   int disabled_breaks = 0;
2923   int hw_breakpoint_error = 0;
2924   int hw_bp_details_reported = 0;
2925
2926   string_file tmp_error_stream;
2927
2928   /* Explicitly mark the warning -- this will only be printed if
2929      there was an error.  */
2930   tmp_error_stream.puts ("Warning:\n");
2931
2932   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2933
2934   ALL_BP_LOCATIONS (bl, blp_tmp)
2935     {
2936       /* We only want to update software breakpoints and hardware
2937          breakpoints.  */
2938       if (!is_breakpoint (bl->owner))
2939         continue;
2940
2941       /* We only want to update locations that are already inserted
2942          and need updating.  This is to avoid unwanted insertion during
2943          deletion of breakpoints.  */
2944       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2945         continue;
2946
2947       switch_to_program_space_and_thread (bl->pspace);
2948
2949       /* For targets that support global breakpoints, there's no need
2950          to select an inferior to insert breakpoint to.  In fact, even
2951          if we aren't attached to any process yet, we should still
2952          insert breakpoints.  */
2953       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2954           && ptid_equal (inferior_ptid, null_ptid))
2955         continue;
2956
2957       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2958                                     &hw_breakpoint_error, &hw_bp_details_reported);
2959       if (val)
2960         error_flag = val;
2961     }
2962
2963   if (error_flag)
2964     {
2965       target_terminal::ours_for_output ();
2966       error_stream (tmp_error_stream);
2967     }
2968 }
2969
2970 /* Used when starting or continuing the program.  */
2971
2972 static void
2973 insert_breakpoint_locations (void)
2974 {
2975   struct breakpoint *bpt;
2976   struct bp_location *bl, **blp_tmp;
2977   int error_flag = 0;
2978   int val = 0;
2979   int disabled_breaks = 0;
2980   int hw_breakpoint_error = 0;
2981   int hw_bp_error_explained_already = 0;
2982
2983   string_file tmp_error_stream;
2984
2985   /* Explicitly mark the warning -- this will only be printed if
2986      there was an error.  */
2987   tmp_error_stream.puts ("Warning:\n");
2988
2989   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2990
2991   ALL_BP_LOCATIONS (bl, blp_tmp)
2992     {
2993       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2994         continue;
2995
2996       /* There is no point inserting thread-specific breakpoints if
2997          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2998          has BL->OWNER always non-NULL.  */
2999       if (bl->owner->thread != -1
3000           && !valid_global_thread_id (bl->owner->thread))
3001         continue;
3002
3003       switch_to_program_space_and_thread (bl->pspace);
3004
3005       /* For targets that support global breakpoints, there's no need
3006          to select an inferior to insert breakpoint to.  In fact, even
3007          if we aren't attached to any process yet, we should still
3008          insert breakpoints.  */
3009       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3010           && ptid_equal (inferior_ptid, null_ptid))
3011         continue;
3012
3013       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3014                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3015       if (val)
3016         error_flag = val;
3017     }
3018
3019   /* If we failed to insert all locations of a watchpoint, remove
3020      them, as half-inserted watchpoint is of limited use.  */
3021   ALL_BREAKPOINTS (bpt)  
3022     {
3023       int some_failed = 0;
3024       struct bp_location *loc;
3025
3026       if (!is_hardware_watchpoint (bpt))
3027         continue;
3028
3029       if (!breakpoint_enabled (bpt))
3030         continue;
3031
3032       if (bpt->disposition == disp_del_at_next_stop)
3033         continue;
3034       
3035       for (loc = bpt->loc; loc; loc = loc->next)
3036         if (!loc->inserted && should_be_inserted (loc))
3037           {
3038             some_failed = 1;
3039             break;
3040           }
3041       if (some_failed)
3042         {
3043           for (loc = bpt->loc; loc; loc = loc->next)
3044             if (loc->inserted)
3045               remove_breakpoint (loc);
3046
3047           hw_breakpoint_error = 1;
3048           tmp_error_stream.printf ("Could not insert "
3049                                    "hardware watchpoint %d.\n",
3050                                    bpt->number);
3051           error_flag = -1;
3052         }
3053     }
3054
3055   if (error_flag)
3056     {
3057       /* If a hardware breakpoint or watchpoint was inserted, add a
3058          message about possibly exhausted resources.  */
3059       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3060         {
3061           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3062 You may have requested too many hardware breakpoints/watchpoints.\n");
3063         }
3064       target_terminal::ours_for_output ();
3065       error_stream (tmp_error_stream);
3066     }
3067 }
3068
3069 /* Used when the program stops.
3070    Returns zero if successful, or non-zero if there was a problem
3071    removing a breakpoint location.  */
3072
3073 int
3074 remove_breakpoints (void)
3075 {
3076   struct bp_location *bl, **blp_tmp;
3077   int val = 0;
3078
3079   ALL_BP_LOCATIONS (bl, blp_tmp)
3080   {
3081     if (bl->inserted && !is_tracepoint (bl->owner))
3082       val |= remove_breakpoint (bl);
3083   }
3084   return val;
3085 }
3086
3087 /* When a thread exits, remove breakpoints that are related to
3088    that thread.  */
3089
3090 static void
3091 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3092 {
3093   struct breakpoint *b, *b_tmp;
3094
3095   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3096     {
3097       if (b->thread == tp->global_num && user_breakpoint_p (b))
3098         {
3099           b->disposition = disp_del_at_next_stop;
3100
3101           printf_filtered (_("\
3102 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3103                            b->number, print_thread_id (tp));
3104
3105           /* Hide it from the user.  */
3106           b->number = 0;
3107        }
3108     }
3109 }
3110
3111 /* Remove breakpoints of process PID.  */
3112
3113 int
3114 remove_breakpoints_pid (int pid)
3115 {
3116   struct bp_location *bl, **blp_tmp;
3117   int val;
3118   struct inferior *inf = find_inferior_pid (pid);
3119
3120   ALL_BP_LOCATIONS (bl, blp_tmp)
3121   {
3122     if (bl->pspace != inf->pspace)
3123       continue;
3124
3125     if (bl->inserted && !bl->target_info.persist)
3126       {
3127         val = remove_breakpoint (bl);
3128         if (val != 0)
3129           return val;
3130       }
3131   }
3132   return 0;
3133 }
3134
3135 static int internal_breakpoint_number = -1;
3136
3137 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3138    If INTERNAL is non-zero, the breakpoint number will be populated
3139    from internal_breakpoint_number and that variable decremented.
3140    Otherwise the breakpoint number will be populated from
3141    breakpoint_count and that value incremented.  Internal breakpoints
3142    do not set the internal var bpnum.  */
3143 static void
3144 set_breakpoint_number (int internal, struct breakpoint *b)
3145 {
3146   if (internal)
3147     b->number = internal_breakpoint_number--;
3148   else
3149     {
3150       set_breakpoint_count (breakpoint_count + 1);
3151       b->number = breakpoint_count;
3152     }
3153 }
3154
3155 static struct breakpoint *
3156 create_internal_breakpoint (struct gdbarch *gdbarch,
3157                             CORE_ADDR address, enum bptype type,
3158                             const struct breakpoint_ops *ops)
3159 {
3160   symtab_and_line sal;
3161   sal.pc = address;
3162   sal.section = find_pc_overlay (sal.pc);
3163   sal.pspace = current_program_space;
3164
3165   breakpoint *b = set_raw_breakpoint (gdbarch, sal, type, ops);
3166   b->number = internal_breakpoint_number--;
3167   b->disposition = disp_donttouch;
3168
3169   return b;
3170 }
3171
3172 static const char *const longjmp_names[] =
3173   {
3174     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3175   };
3176 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3177
3178 /* Per-objfile data private to breakpoint.c.  */
3179 struct breakpoint_objfile_data
3180 {
3181   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3182   struct bound_minimal_symbol overlay_msym {};
3183
3184   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3185   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES] {};
3186
3187   /* True if we have looked for longjmp probes.  */
3188   int longjmp_searched = 0;
3189
3190   /* SystemTap probe points for longjmp (if any).  These are non-owning
3191      references.  */
3192   std::vector<probe *> longjmp_probes;
3193
3194   /* Minimal symbol for "std::terminate()" (if any).  */
3195   struct bound_minimal_symbol terminate_msym {};
3196
3197   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3198   struct bound_minimal_symbol exception_msym {};
3199
3200   /* True if we have looked for exception probes.  */
3201   int exception_searched = 0;
3202
3203   /* SystemTap probe points for unwinding (if any).  These are non-owning
3204      references.  */
3205   std::vector<probe *> exception_probes;
3206 };
3207
3208 static const struct objfile_data *breakpoint_objfile_key;
3209
3210 /* Minimal symbol not found sentinel.  */
3211 static struct minimal_symbol msym_not_found;
3212
3213 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3214
3215 static int
3216 msym_not_found_p (const struct minimal_symbol *msym)
3217 {
3218   return msym == &msym_not_found;
3219 }
3220
3221 /* Return per-objfile data needed by breakpoint.c.
3222    Allocate the data if necessary.  */
3223
3224 static struct breakpoint_objfile_data *
3225 get_breakpoint_objfile_data (struct objfile *objfile)
3226 {
3227   struct breakpoint_objfile_data *bp_objfile_data;
3228
3229   bp_objfile_data = ((struct breakpoint_objfile_data *)
3230                      objfile_data (objfile, breakpoint_objfile_key));
3231   if (bp_objfile_data == NULL)
3232     {
3233       bp_objfile_data = new breakpoint_objfile_data ();
3234       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3235     }
3236   return bp_objfile_data;
3237 }
3238
3239 static void
3240 free_breakpoint_objfile_data (struct objfile *obj, void *data)
3241 {
3242   struct breakpoint_objfile_data *bp_objfile_data
3243     = (struct breakpoint_objfile_data *) data;
3244
3245   delete bp_objfile_data;
3246 }
3247
3248 static void
3249 create_overlay_event_breakpoint (void)
3250 {
3251   struct objfile *objfile;
3252   const char *const func_name = "_ovly_debug_event";
3253
3254   ALL_OBJFILES (objfile)
3255     {
3256       struct breakpoint *b;
3257       struct breakpoint_objfile_data *bp_objfile_data;
3258       CORE_ADDR addr;
3259       struct explicit_location explicit_loc;
3260
3261       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3262
3263       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3264         continue;
3265
3266       if (bp_objfile_data->overlay_msym.minsym == NULL)
3267         {
3268           struct bound_minimal_symbol m;
3269
3270           m = lookup_minimal_symbol_text (func_name, objfile);
3271           if (m.minsym == NULL)
3272             {
3273               /* Avoid future lookups in this objfile.  */
3274               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3275               continue;
3276             }
3277           bp_objfile_data->overlay_msym = m;
3278         }
3279
3280       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3281       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3282                                       bp_overlay_event,
3283                                       &internal_breakpoint_ops);
3284       initialize_explicit_location (&explicit_loc);
3285       explicit_loc.function_name = ASTRDUP (func_name);
3286       b->location = new_explicit_location (&explicit_loc);
3287
3288       if (overlay_debugging == ovly_auto)
3289         {
3290           b->enable_state = bp_enabled;
3291           overlay_events_enabled = 1;
3292         }
3293       else
3294        {
3295          b->enable_state = bp_disabled;
3296          overlay_events_enabled = 0;
3297        }
3298     }
3299 }
3300
3301 static void
3302 create_longjmp_master_breakpoint (void)
3303 {
3304   struct program_space *pspace;
3305
3306   scoped_restore_current_program_space restore_pspace;
3307
3308   ALL_PSPACES (pspace)
3309   {
3310     struct objfile *objfile;
3311
3312     set_current_program_space (pspace);
3313
3314     ALL_OBJFILES (objfile)
3315     {
3316       int i;
3317       struct gdbarch *gdbarch;
3318       struct breakpoint_objfile_data *bp_objfile_data;
3319
3320       gdbarch = get_objfile_arch (objfile);
3321
3322       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3323
3324       if (!bp_objfile_data->longjmp_searched)
3325         {
3326           std::vector<probe *> ret
3327             = find_probes_in_objfile (objfile, "libc", "longjmp");
3328
3329           if (!ret.empty ())
3330             {
3331               /* We are only interested in checking one element.  */
3332               probe *p = ret[0];
3333
3334               if (!can_evaluate_probe_arguments (p))
3335                 {
3336                   /* We cannot use the probe interface here, because it does
3337                      not know how to evaluate arguments.  */
3338                   ret.clear ();
3339                 }
3340             }
3341           bp_objfile_data->longjmp_probes = ret;
3342           bp_objfile_data->longjmp_searched = 1;
3343         }
3344
3345       if (!bp_objfile_data->longjmp_probes.empty ())
3346         {
3347           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3348
3349           for (probe *p : bp_objfile_data->longjmp_probes)
3350             {
3351               struct breakpoint *b;
3352
3353               b = create_internal_breakpoint (gdbarch,
3354                                               get_probe_address (p, objfile),
3355                                               bp_longjmp_master,
3356                                               &internal_breakpoint_ops);
3357               b->location = new_probe_location ("-probe-stap libc:longjmp");
3358               b->enable_state = bp_disabled;
3359             }
3360
3361           continue;
3362         }
3363
3364       if (!gdbarch_get_longjmp_target_p (gdbarch))
3365         continue;
3366
3367       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3368         {
3369           struct breakpoint *b;
3370           const char *func_name;
3371           CORE_ADDR addr;
3372           struct explicit_location explicit_loc;
3373
3374           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3375             continue;
3376
3377           func_name = longjmp_names[i];
3378           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3379             {
3380               struct bound_minimal_symbol m;
3381
3382               m = lookup_minimal_symbol_text (func_name, objfile);
3383               if (m.minsym == NULL)
3384                 {
3385                   /* Prevent future lookups in this objfile.  */
3386                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3387                   continue;
3388                 }
3389               bp_objfile_data->longjmp_msym[i] = m;
3390             }
3391
3392           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3393           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3394                                           &internal_breakpoint_ops);
3395           initialize_explicit_location (&explicit_loc);
3396           explicit_loc.function_name = ASTRDUP (func_name);
3397           b->location = new_explicit_location (&explicit_loc);
3398           b->enable_state = bp_disabled;
3399         }
3400     }
3401   }
3402 }
3403
3404 /* Create a master std::terminate breakpoint.  */
3405 static void
3406 create_std_terminate_master_breakpoint (void)
3407 {
3408   struct program_space *pspace;
3409   const char *const func_name = "std::terminate()";
3410
3411   scoped_restore_current_program_space restore_pspace;
3412
3413   ALL_PSPACES (pspace)
3414   {
3415     struct objfile *objfile;
3416     CORE_ADDR addr;
3417
3418     set_current_program_space (pspace);
3419
3420     ALL_OBJFILES (objfile)
3421     {
3422       struct breakpoint *b;
3423       struct breakpoint_objfile_data *bp_objfile_data;
3424       struct explicit_location explicit_loc;
3425
3426       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3427
3428       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3429         continue;
3430
3431       if (bp_objfile_data->terminate_msym.minsym == NULL)
3432         {
3433           struct bound_minimal_symbol m;
3434
3435           m = lookup_minimal_symbol (func_name, NULL, objfile);
3436           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3437                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3438             {
3439               /* Prevent future lookups in this objfile.  */
3440               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3441               continue;
3442             }
3443           bp_objfile_data->terminate_msym = m;
3444         }
3445
3446       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3447       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3448                                       bp_std_terminate_master,
3449                                       &internal_breakpoint_ops);
3450       initialize_explicit_location (&explicit_loc);
3451       explicit_loc.function_name = ASTRDUP (func_name);
3452       b->location = new_explicit_location (&explicit_loc);
3453       b->enable_state = bp_disabled;
3454     }
3455   }
3456 }
3457
3458 /* Install a master breakpoint on the unwinder's debug hook.  */
3459
3460 static void
3461 create_exception_master_breakpoint (void)
3462 {
3463   struct objfile *objfile;
3464   const char *const func_name = "_Unwind_DebugHook";
3465
3466   ALL_OBJFILES (objfile)
3467     {
3468       struct breakpoint *b;
3469       struct gdbarch *gdbarch;
3470       struct breakpoint_objfile_data *bp_objfile_data;
3471       CORE_ADDR addr;
3472       struct explicit_location explicit_loc;
3473
3474       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3475
3476       /* We prefer the SystemTap probe point if it exists.  */
3477       if (!bp_objfile_data->exception_searched)
3478         {
3479           std::vector<probe *> ret
3480             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3481
3482           if (!ret.empty ())
3483             {
3484               /* We are only interested in checking one element.  */
3485               probe *p = ret[0];
3486
3487               if (!can_evaluate_probe_arguments (p))
3488                 {
3489                   /* We cannot use the probe interface here, because it does
3490                      not know how to evaluate arguments.  */
3491                   ret.clear ();
3492                 }
3493             }
3494           bp_objfile_data->exception_probes = ret;
3495           bp_objfile_data->exception_searched = 1;
3496         }
3497
3498       if (!bp_objfile_data->exception_probes.empty ())
3499         {
3500           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3501
3502           for (probe *p : bp_objfile_data->exception_probes)
3503             {
3504               struct breakpoint *b;
3505
3506               b = create_internal_breakpoint (gdbarch,
3507                                               get_probe_address (p, objfile),
3508                                               bp_exception_master,
3509                                               &internal_breakpoint_ops);
3510               b->location = new_probe_location ("-probe-stap libgcc:unwind");
3511               b->enable_state = bp_disabled;
3512             }
3513
3514           continue;
3515         }
3516
3517       /* Otherwise, try the hook function.  */
3518
3519       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3520         continue;
3521
3522       gdbarch = get_objfile_arch (objfile);
3523
3524       if (bp_objfile_data->exception_msym.minsym == NULL)
3525         {
3526           struct bound_minimal_symbol debug_hook;
3527
3528           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3529           if (debug_hook.minsym == NULL)
3530             {
3531               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3532               continue;
3533             }
3534
3535           bp_objfile_data->exception_msym = debug_hook;
3536         }
3537
3538       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3539       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3540                                                  &current_target);
3541       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3542                                       &internal_breakpoint_ops);
3543       initialize_explicit_location (&explicit_loc);
3544       explicit_loc.function_name = ASTRDUP (func_name);
3545       b->location = new_explicit_location (&explicit_loc);
3546       b->enable_state = bp_disabled;
3547     }
3548 }
3549
3550 /* Does B have a location spec?  */
3551
3552 static int
3553 breakpoint_event_location_empty_p (const struct breakpoint *b)
3554 {
3555   return b->location != NULL && event_location_empty_p (b->location.get ());
3556 }
3557
3558 void
3559 update_breakpoints_after_exec (void)
3560 {
3561   struct breakpoint *b, *b_tmp;
3562   struct bp_location *bploc, **bplocp_tmp;
3563
3564   /* We're about to delete breakpoints from GDB's lists.  If the
3565      INSERTED flag is true, GDB will try to lift the breakpoints by
3566      writing the breakpoints' "shadow contents" back into memory.  The
3567      "shadow contents" are NOT valid after an exec, so GDB should not
3568      do that.  Instead, the target is responsible from marking
3569      breakpoints out as soon as it detects an exec.  We don't do that
3570      here instead, because there may be other attempts to delete
3571      breakpoints after detecting an exec and before reaching here.  */
3572   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3573     if (bploc->pspace == current_program_space)
3574       gdb_assert (!bploc->inserted);
3575
3576   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3577   {
3578     if (b->pspace != current_program_space)
3579       continue;
3580
3581     /* Solib breakpoints must be explicitly reset after an exec().  */
3582     if (b->type == bp_shlib_event)
3583       {
3584         delete_breakpoint (b);
3585         continue;
3586       }
3587
3588     /* JIT breakpoints must be explicitly reset after an exec().  */
3589     if (b->type == bp_jit_event)
3590       {
3591         delete_breakpoint (b);
3592         continue;
3593       }
3594
3595     /* Thread event breakpoints must be set anew after an exec(),
3596        as must overlay event and longjmp master breakpoints.  */
3597     if (b->type == bp_thread_event || b->type == bp_overlay_event
3598         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3599         || b->type == bp_exception_master)
3600       {
3601         delete_breakpoint (b);
3602         continue;
3603       }
3604
3605     /* Step-resume breakpoints are meaningless after an exec().  */
3606     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3607       {
3608         delete_breakpoint (b);
3609         continue;
3610       }
3611
3612     /* Just like single-step breakpoints.  */
3613     if (b->type == bp_single_step)
3614       {
3615         delete_breakpoint (b);
3616         continue;
3617       }
3618
3619     /* Longjmp and longjmp-resume breakpoints are also meaningless
3620        after an exec.  */
3621     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3622         || b->type == bp_longjmp_call_dummy
3623         || b->type == bp_exception || b->type == bp_exception_resume)
3624       {
3625         delete_breakpoint (b);
3626         continue;
3627       }
3628
3629     if (b->type == bp_catchpoint)
3630       {
3631         /* For now, none of the bp_catchpoint breakpoints need to
3632            do anything at this point.  In the future, if some of
3633            the catchpoints need to something, we will need to add
3634            a new method, and call this method from here.  */
3635         continue;
3636       }
3637
3638     /* bp_finish is a special case.  The only way we ought to be able
3639        to see one of these when an exec() has happened, is if the user
3640        caught a vfork, and then said "finish".  Ordinarily a finish just
3641        carries them to the call-site of the current callee, by setting
3642        a temporary bp there and resuming.  But in this case, the finish
3643        will carry them entirely through the vfork & exec.
3644
3645        We don't want to allow a bp_finish to remain inserted now.  But
3646        we can't safely delete it, 'cause finish_command has a handle to
3647        the bp on a bpstat, and will later want to delete it.  There's a
3648        chance (and I've seen it happen) that if we delete the bp_finish
3649        here, that its storage will get reused by the time finish_command
3650        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3651        We really must allow finish_command to delete a bp_finish.
3652
3653        In the absence of a general solution for the "how do we know
3654        it's safe to delete something others may have handles to?"
3655        problem, what we'll do here is just uninsert the bp_finish, and
3656        let finish_command delete it.
3657
3658        (We know the bp_finish is "doomed" in the sense that it's
3659        momentary, and will be deleted as soon as finish_command sees
3660        the inferior stopped.  So it doesn't matter that the bp's
3661        address is probably bogus in the new a.out, unlike e.g., the
3662        solib breakpoints.)  */
3663
3664     if (b->type == bp_finish)
3665       {
3666         continue;
3667       }
3668
3669     /* Without a symbolic address, we have little hope of the
3670        pre-exec() address meaning the same thing in the post-exec()
3671        a.out.  */
3672     if (breakpoint_event_location_empty_p (b))
3673       {
3674         delete_breakpoint (b);
3675         continue;
3676       }
3677   }
3678 }
3679
3680 int
3681 detach_breakpoints (ptid_t ptid)
3682 {
3683   struct bp_location *bl, **blp_tmp;
3684   int val = 0;
3685   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3686   struct inferior *inf = current_inferior ();
3687
3688   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3689     error (_("Cannot detach breakpoints of inferior_ptid"));
3690
3691   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3692   inferior_ptid = ptid;
3693   ALL_BP_LOCATIONS (bl, blp_tmp)
3694   {
3695     if (bl->pspace != inf->pspace)
3696       continue;
3697
3698     /* This function must physically remove breakpoints locations
3699        from the specified ptid, without modifying the breakpoint
3700        package's state.  Locations of type bp_loc_other are only
3701        maintained at GDB side.  So, there is no need to remove
3702        these bp_loc_other locations.  Moreover, removing these
3703        would modify the breakpoint package's state.  */
3704     if (bl->loc_type == bp_loc_other)
3705       continue;
3706
3707     if (bl->inserted)
3708       val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3709   }
3710
3711   return val;
3712 }
3713
3714 /* Remove the breakpoint location BL from the current address space.
3715    Note that this is used to detach breakpoints from a child fork.
3716    When we get here, the child isn't in the inferior list, and neither
3717    do we have objects to represent its address space --- we should
3718    *not* look at bl->pspace->aspace here.  */
3719
3720 static int
3721 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3722 {
3723   int val;
3724
3725   /* BL is never in moribund_locations by our callers.  */
3726   gdb_assert (bl->owner != NULL);
3727
3728   /* The type of none suggests that owner is actually deleted.
3729      This should not ever happen.  */
3730   gdb_assert (bl->owner->type != bp_none);
3731
3732   if (bl->loc_type == bp_loc_software_breakpoint
3733       || bl->loc_type == bp_loc_hardware_breakpoint)
3734     {
3735       /* "Normal" instruction breakpoint: either the standard
3736          trap-instruction bp (bp_breakpoint), or a
3737          bp_hardware_breakpoint.  */
3738
3739       /* First check to see if we have to handle an overlay.  */
3740       if (overlay_debugging == ovly_off
3741           || bl->section == NULL
3742           || !(section_is_overlay (bl->section)))
3743         {
3744           /* No overlay handling: just remove the breakpoint.  */
3745
3746           /* If we're trying to uninsert a memory breakpoint that we
3747              know is set in a dynamic object that is marked
3748              shlib_disabled, then either the dynamic object was
3749              removed with "remove-symbol-file" or with
3750              "nosharedlibrary".  In the former case, we don't know
3751              whether another dynamic object might have loaded over the
3752              breakpoint's address -- the user might well let us know
3753              about it next with add-symbol-file (the whole point of
3754              add-symbol-file is letting the user manually maintain a
3755              list of dynamically loaded objects).  If we have the
3756              breakpoint's shadow memory, that is, this is a software
3757              breakpoint managed by GDB, check whether the breakpoint
3758              is still inserted in memory, to avoid overwriting wrong
3759              code with stale saved shadow contents.  Note that HW
3760              breakpoints don't have shadow memory, as they're
3761              implemented using a mechanism that is not dependent on
3762              being able to modify the target's memory, and as such
3763              they should always be removed.  */
3764           if (bl->shlib_disabled
3765               && bl->target_info.shadow_len != 0
3766               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3767             val = 0;
3768           else
3769             val = bl->owner->ops->remove_location (bl, reason);
3770         }
3771       else
3772         {
3773           /* This breakpoint is in an overlay section.
3774              Did we set a breakpoint at the LMA?  */
3775           if (!overlay_events_enabled)
3776               {
3777                 /* Yes -- overlay event support is not active, so we
3778                    should have set a breakpoint at the LMA.  Remove it.  
3779                 */
3780                 /* Ignore any failures: if the LMA is in ROM, we will
3781                    have already warned when we failed to insert it.  */
3782                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3783                   target_remove_hw_breakpoint (bl->gdbarch,
3784                                                &bl->overlay_target_info);
3785                 else
3786                   target_remove_breakpoint (bl->gdbarch,
3787                                             &bl->overlay_target_info,
3788                                             reason);
3789               }
3790           /* Did we set a breakpoint at the VMA? 
3791              If so, we will have marked the breakpoint 'inserted'.  */
3792           if (bl->inserted)
3793             {
3794               /* Yes -- remove it.  Previously we did not bother to
3795                  remove the breakpoint if the section had been
3796                  unmapped, but let's not rely on that being safe.  We
3797                  don't know what the overlay manager might do.  */
3798
3799               /* However, we should remove *software* breakpoints only
3800                  if the section is still mapped, or else we overwrite
3801                  wrong code with the saved shadow contents.  */
3802               if (bl->loc_type == bp_loc_hardware_breakpoint
3803                   || section_is_mapped (bl->section))
3804                 val = bl->owner->ops->remove_location (bl, reason);
3805               else
3806                 val = 0;
3807             }
3808           else
3809             {
3810               /* No -- not inserted, so no need to remove.  No error.  */
3811               val = 0;
3812             }
3813         }
3814
3815       /* In some cases, we might not be able to remove a breakpoint in
3816          a shared library that has already been removed, but we have
3817          not yet processed the shlib unload event.  Similarly for an
3818          unloaded add-symbol-file object - the user might not yet have
3819          had the chance to remove-symbol-file it.  shlib_disabled will
3820          be set if the library/object has already been removed, but
3821          the breakpoint hasn't been uninserted yet, e.g., after
3822          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3823          always-inserted mode.  */
3824       if (val
3825           && (bl->loc_type == bp_loc_software_breakpoint
3826               && (bl->shlib_disabled
3827                   || solib_name_from_address (bl->pspace, bl->address)
3828                   || shared_objfile_contains_address_p (bl->pspace,
3829                                                         bl->address))))
3830         val = 0;
3831
3832       if (val)
3833         return val;
3834       bl->inserted = (reason == DETACH_BREAKPOINT);
3835     }
3836   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3837     {
3838       gdb_assert (bl->owner->ops != NULL
3839                   && bl->owner->ops->remove_location != NULL);
3840
3841       bl->inserted = (reason == DETACH_BREAKPOINT);
3842       bl->owner->ops->remove_location (bl, reason);
3843
3844       /* Failure to remove any of the hardware watchpoints comes here.  */
3845       if (reason == REMOVE_BREAKPOINT && bl->inserted)
3846         warning (_("Could not remove hardware watchpoint %d."),
3847                  bl->owner->number);
3848     }
3849   else if (bl->owner->type == bp_catchpoint
3850            && breakpoint_enabled (bl->owner)
3851            && !bl->duplicate)
3852     {
3853       gdb_assert (bl->owner->ops != NULL
3854                   && bl->owner->ops->remove_location != NULL);
3855
3856       val = bl->owner->ops->remove_location (bl, reason);
3857       if (val)
3858         return val;
3859
3860       bl->inserted = (reason == DETACH_BREAKPOINT);
3861     }
3862
3863   return 0;
3864 }
3865
3866 static int
3867 remove_breakpoint (struct bp_location *bl)
3868 {
3869   /* BL is never in moribund_locations by our callers.  */
3870   gdb_assert (bl->owner != NULL);
3871
3872   /* The type of none suggests that owner is actually deleted.
3873      This should not ever happen.  */
3874   gdb_assert (bl->owner->type != bp_none);
3875
3876   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3877
3878   switch_to_program_space_and_thread (bl->pspace);
3879
3880   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
3881 }
3882
3883 /* Clear the "inserted" flag in all breakpoints.  */
3884
3885 void
3886 mark_breakpoints_out (void)
3887 {
3888   struct bp_location *bl, **blp_tmp;
3889
3890   ALL_BP_LOCATIONS (bl, blp_tmp)
3891     if (bl->pspace == current_program_space)
3892       bl->inserted = 0;
3893 }
3894
3895 /* Clear the "inserted" flag in all breakpoints and delete any
3896    breakpoints which should go away between runs of the program.
3897
3898    Plus other such housekeeping that has to be done for breakpoints
3899    between runs.
3900
3901    Note: this function gets called at the end of a run (by
3902    generic_mourn_inferior) and when a run begins (by
3903    init_wait_for_inferior).  */
3904
3905
3906
3907 void
3908 breakpoint_init_inferior (enum inf_context context)
3909 {
3910   struct breakpoint *b, *b_tmp;
3911   struct bp_location *bl;
3912   int ix;
3913   struct program_space *pspace = current_program_space;
3914
3915   /* If breakpoint locations are shared across processes, then there's
3916      nothing to do.  */
3917   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3918     return;
3919
3920   mark_breakpoints_out ();
3921
3922   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3923   {
3924     if (b->loc && b->loc->pspace != pspace)
3925       continue;
3926
3927     switch (b->type)
3928       {
3929       case bp_call_dummy:
3930       case bp_longjmp_call_dummy:
3931
3932         /* If the call dummy breakpoint is at the entry point it will
3933            cause problems when the inferior is rerun, so we better get
3934            rid of it.  */
3935
3936       case bp_watchpoint_scope:
3937
3938         /* Also get rid of scope breakpoints.  */
3939
3940       case bp_shlib_event:
3941
3942         /* Also remove solib event breakpoints.  Their addresses may
3943            have changed since the last time we ran the program.
3944            Actually we may now be debugging against different target;
3945            and so the solib backend that installed this breakpoint may
3946            not be used in by the target.  E.g.,
3947
3948            (gdb) file prog-linux
3949            (gdb) run               # native linux target
3950            ...
3951            (gdb) kill
3952            (gdb) file prog-win.exe
3953            (gdb) tar rem :9999     # remote Windows gdbserver.
3954         */
3955
3956       case bp_step_resume:
3957
3958         /* Also remove step-resume breakpoints.  */
3959
3960       case bp_single_step:
3961
3962         /* Also remove single-step breakpoints.  */
3963
3964         delete_breakpoint (b);
3965         break;
3966
3967       case bp_watchpoint:
3968       case bp_hardware_watchpoint:
3969       case bp_read_watchpoint:
3970       case bp_access_watchpoint:
3971         {
3972           struct watchpoint *w = (struct watchpoint *) b;
3973
3974           /* Likewise for watchpoints on local expressions.  */
3975           if (w->exp_valid_block != NULL)
3976             delete_breakpoint (b);
3977           else
3978             {
3979               /* Get rid of existing locations, which are no longer
3980                  valid.  New ones will be created in
3981                  update_watchpoint, when the inferior is restarted.
3982                  The next update_global_location_list call will
3983                  garbage collect them.  */
3984               b->loc = NULL;
3985
3986               if (context == inf_starting)
3987                 {
3988                   /* Reset val field to force reread of starting value in
3989                      insert_breakpoints.  */
3990                   if (w->val)
3991                     value_free (w->val);
3992                   w->val = NULL;
3993                   w->val_valid = 0;
3994                 }
3995             }
3996         }
3997         break;
3998       default:
3999         break;
4000       }
4001   }
4002
4003   /* Get rid of the moribund locations.  */
4004   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4005     decref_bp_location (&bl);
4006   VEC_free (bp_location_p, moribund_locations);
4007 }
4008
4009 /* These functions concern about actual breakpoints inserted in the
4010    target --- to e.g. check if we need to do decr_pc adjustment or if
4011    we need to hop over the bkpt --- so we check for address space
4012    match, not program space.  */
4013
4014 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4015    exists at PC.  It returns ordinary_breakpoint_here if it's an
4016    ordinary breakpoint, or permanent_breakpoint_here if it's a
4017    permanent breakpoint.
4018    - When continuing from a location with an ordinary breakpoint, we
4019      actually single step once before calling insert_breakpoints.
4020    - When continuing from a location with a permanent breakpoint, we
4021      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4022      the target, to advance the PC past the breakpoint.  */
4023
4024 enum breakpoint_here
4025 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4026 {
4027   struct bp_location *bl, **blp_tmp;
4028   int any_breakpoint_here = 0;
4029
4030   ALL_BP_LOCATIONS (bl, blp_tmp)
4031     {
4032       if (bl->loc_type != bp_loc_software_breakpoint
4033           && bl->loc_type != bp_loc_hardware_breakpoint)
4034         continue;
4035
4036       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4037       if ((breakpoint_enabled (bl->owner)
4038            || bl->permanent)
4039           && breakpoint_location_address_match (bl, aspace, pc))
4040         {
4041           if (overlay_debugging 
4042               && section_is_overlay (bl->section)
4043               && !section_is_mapped (bl->section))
4044             continue;           /* unmapped overlay -- can't be a match */
4045           else if (bl->permanent)
4046             return permanent_breakpoint_here;
4047           else
4048             any_breakpoint_here = 1;
4049         }
4050     }
4051
4052   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4053 }
4054
4055 /* See breakpoint.h.  */
4056
4057 int
4058 breakpoint_in_range_p (const address_space *aspace,
4059                        CORE_ADDR addr, ULONGEST len)
4060 {
4061   struct bp_location *bl, **blp_tmp;
4062
4063   ALL_BP_LOCATIONS (bl, blp_tmp)
4064     {
4065       if (bl->loc_type != bp_loc_software_breakpoint
4066           && bl->loc_type != bp_loc_hardware_breakpoint)
4067         continue;
4068
4069       if ((breakpoint_enabled (bl->owner)
4070            || bl->permanent)
4071           && breakpoint_location_address_range_overlap (bl, aspace,
4072                                                         addr, len))
4073         {
4074           if (overlay_debugging
4075               && section_is_overlay (bl->section)
4076               && !section_is_mapped (bl->section))
4077             {
4078               /* Unmapped overlay -- can't be a match.  */
4079               continue;
4080             }
4081
4082           return 1;
4083         }
4084     }
4085
4086   return 0;
4087 }
4088
4089 /* Return true if there's a moribund breakpoint at PC.  */
4090
4091 int
4092 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4093 {
4094   struct bp_location *loc;
4095   int ix;
4096
4097   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4098     if (breakpoint_location_address_match (loc, aspace, pc))
4099       return 1;
4100
4101   return 0;
4102 }
4103
4104 /* Returns non-zero iff BL is inserted at PC, in address space
4105    ASPACE.  */
4106
4107 static int
4108 bp_location_inserted_here_p (struct bp_location *bl,
4109                              const address_space *aspace, CORE_ADDR pc)
4110 {
4111   if (bl->inserted
4112       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4113                                    aspace, pc))
4114     {
4115       if (overlay_debugging
4116           && section_is_overlay (bl->section)
4117           && !section_is_mapped (bl->section))
4118         return 0;               /* unmapped overlay -- can't be a match */
4119       else
4120         return 1;
4121     }
4122   return 0;
4123 }
4124
4125 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4126
4127 int
4128 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4129 {
4130   struct bp_location **blp, **blp_tmp = NULL;
4131
4132   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4133     {
4134       struct bp_location *bl = *blp;
4135
4136       if (bl->loc_type != bp_loc_software_breakpoint
4137           && bl->loc_type != bp_loc_hardware_breakpoint)
4138         continue;
4139
4140       if (bp_location_inserted_here_p (bl, aspace, pc))
4141         return 1;
4142     }
4143   return 0;
4144 }
4145
4146 /* This function returns non-zero iff there is a software breakpoint
4147    inserted at PC.  */
4148
4149 int
4150 software_breakpoint_inserted_here_p (const address_space *aspace,
4151                                      CORE_ADDR pc)
4152 {
4153   struct bp_location **blp, **blp_tmp = NULL;
4154
4155   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4156     {
4157       struct bp_location *bl = *blp;
4158
4159       if (bl->loc_type != bp_loc_software_breakpoint)
4160         continue;
4161
4162       if (bp_location_inserted_here_p (bl, aspace, pc))
4163         return 1;
4164     }
4165
4166   return 0;
4167 }
4168
4169 /* See breakpoint.h.  */
4170
4171 int
4172 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4173                                      CORE_ADDR pc)
4174 {
4175   struct bp_location **blp, **blp_tmp = NULL;
4176
4177   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4178     {
4179       struct bp_location *bl = *blp;
4180
4181       if (bl->loc_type != bp_loc_hardware_breakpoint)
4182         continue;
4183
4184       if (bp_location_inserted_here_p (bl, aspace, pc))
4185         return 1;
4186     }
4187
4188   return 0;
4189 }
4190
4191 int
4192 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4193                                        CORE_ADDR addr, ULONGEST len)
4194 {
4195   struct breakpoint *bpt;
4196
4197   ALL_BREAKPOINTS (bpt)
4198     {
4199       struct bp_location *loc;
4200
4201       if (bpt->type != bp_hardware_watchpoint
4202           && bpt->type != bp_access_watchpoint)
4203         continue;
4204
4205       if (!breakpoint_enabled (bpt))
4206         continue;
4207
4208       for (loc = bpt->loc; loc; loc = loc->next)
4209         if (loc->pspace->aspace == aspace && loc->inserted)
4210           {
4211             CORE_ADDR l, h;
4212
4213             /* Check for intersection.  */
4214             l = std::max<CORE_ADDR> (loc->address, addr);
4215             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4216             if (l < h)
4217               return 1;
4218           }
4219     }
4220   return 0;
4221 }
4222 \f
4223
4224 /* bpstat stuff.  External routines' interfaces are documented
4225    in breakpoint.h.  */
4226
4227 int
4228 is_catchpoint (struct breakpoint *ep)
4229 {
4230   return (ep->type == bp_catchpoint);
4231 }
4232
4233 /* Frees any storage that is part of a bpstat.  Does not walk the
4234    'next' chain.  */
4235
4236 bpstats::~bpstats ()
4237 {
4238   if (old_val != NULL)
4239     value_free (old_val);
4240   if (bp_location_at != NULL)
4241     decref_bp_location (&bp_location_at);
4242 }
4243
4244 /* Clear a bpstat so that it says we are not at any breakpoint.
4245    Also free any storage that is part of a bpstat.  */
4246
4247 void
4248 bpstat_clear (bpstat *bsp)
4249 {
4250   bpstat p;
4251   bpstat q;
4252
4253   if (bsp == 0)
4254     return;
4255   p = *bsp;
4256   while (p != NULL)
4257     {
4258       q = p->next;
4259       delete p;
4260       p = q;
4261     }
4262   *bsp = NULL;
4263 }
4264
4265 bpstats::bpstats (const bpstats &other)
4266   : next (NULL),
4267     bp_location_at (other.bp_location_at),
4268     breakpoint_at (other.breakpoint_at),
4269     commands (other.commands),
4270     old_val (other.old_val),
4271     print (other.print),
4272     stop (other.stop),
4273     print_it (other.print_it)
4274 {
4275   if (old_val != NULL)
4276     {
4277       old_val = value_copy (old_val);
4278       release_value (old_val);
4279     }
4280   incref_bp_location (bp_location_at);
4281 }
4282
4283 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4284    is part of the bpstat is copied as well.  */
4285
4286 bpstat
4287 bpstat_copy (bpstat bs)
4288 {
4289   bpstat p = NULL;
4290   bpstat tmp;
4291   bpstat retval = NULL;
4292
4293   if (bs == NULL)
4294     return bs;
4295
4296   for (; bs != NULL; bs = bs->next)
4297     {
4298       tmp = new bpstats (*bs);
4299
4300       if (p == NULL)
4301         /* This is the first thing in the chain.  */
4302         retval = tmp;
4303       else
4304         p->next = tmp;
4305       p = tmp;
4306     }
4307   p->next = NULL;
4308   return retval;
4309 }
4310
4311 /* Find the bpstat associated with this breakpoint.  */
4312
4313 bpstat
4314 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4315 {
4316   if (bsp == NULL)
4317     return NULL;
4318
4319   for (; bsp != NULL; bsp = bsp->next)
4320     {
4321       if (bsp->breakpoint_at == breakpoint)
4322         return bsp;
4323     }
4324   return NULL;
4325 }
4326
4327 /* See breakpoint.h.  */
4328
4329 int
4330 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4331 {
4332   for (; bsp != NULL; bsp = bsp->next)
4333     {
4334       if (bsp->breakpoint_at == NULL)
4335         {
4336           /* A moribund location can never explain a signal other than
4337              GDB_SIGNAL_TRAP.  */
4338           if (sig == GDB_SIGNAL_TRAP)
4339             return 1;
4340         }
4341       else
4342         {
4343           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4344                                                         sig))
4345             return 1;
4346         }
4347     }
4348
4349   return 0;
4350 }
4351
4352 /* Put in *NUM the breakpoint number of the first breakpoint we are
4353    stopped at.  *BSP upon return is a bpstat which points to the
4354    remaining breakpoints stopped at (but which is not guaranteed to be
4355    good for anything but further calls to bpstat_num).
4356
4357    Return 0 if passed a bpstat which does not indicate any breakpoints.
4358    Return -1 if stopped at a breakpoint that has been deleted since
4359    we set it.
4360    Return 1 otherwise.  */
4361
4362 int
4363 bpstat_num (bpstat *bsp, int *num)
4364 {
4365   struct breakpoint *b;
4366
4367   if ((*bsp) == NULL)
4368     return 0;                   /* No more breakpoint values */
4369
4370   /* We assume we'll never have several bpstats that correspond to a
4371      single breakpoint -- otherwise, this function might return the
4372      same number more than once and this will look ugly.  */
4373   b = (*bsp)->breakpoint_at;
4374   *bsp = (*bsp)->next;
4375   if (b == NULL)
4376     return -1;                  /* breakpoint that's been deleted since */
4377
4378   *num = b->number;             /* We have its number */
4379   return 1;
4380 }
4381
4382 /* See breakpoint.h.  */
4383
4384 void
4385 bpstat_clear_actions (void)
4386 {
4387   struct thread_info *tp;
4388   bpstat bs;
4389
4390   if (ptid_equal (inferior_ptid, null_ptid))
4391     return;
4392
4393   tp = find_thread_ptid (inferior_ptid);
4394   if (tp == NULL)
4395     return;
4396
4397   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4398     {
4399       bs->commands = NULL;
4400
4401       if (bs->old_val != NULL)
4402         {
4403           value_free (bs->old_val);
4404           bs->old_val = NULL;
4405         }
4406     }
4407 }
4408
4409 /* Called when a command is about to proceed the inferior.  */
4410
4411 static void
4412 breakpoint_about_to_proceed (void)
4413 {
4414   if (!ptid_equal (inferior_ptid, null_ptid))
4415     {
4416       struct thread_info *tp = inferior_thread ();
4417
4418       /* Allow inferior function calls in breakpoint commands to not
4419          interrupt the command list.  When the call finishes
4420          successfully, the inferior will be standing at the same
4421          breakpoint as if nothing happened.  */
4422       if (tp->control.in_infcall)
4423         return;
4424     }
4425
4426   breakpoint_proceeded = 1;
4427 }
4428
4429 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4430    or its equivalent.  */
4431
4432 static int
4433 command_line_is_silent (struct command_line *cmd)
4434 {
4435   return cmd && (strcmp ("silent", cmd->line) == 0);
4436 }
4437
4438 /* Execute all the commands associated with all the breakpoints at
4439    this location.  Any of these commands could cause the process to
4440    proceed beyond this point, etc.  We look out for such changes by
4441    checking the global "breakpoint_proceeded" after each command.
4442
4443    Returns true if a breakpoint command resumed the inferior.  In that
4444    case, it is the caller's responsibility to recall it again with the
4445    bpstat of the current thread.  */
4446
4447 static int
4448 bpstat_do_actions_1 (bpstat *bsp)
4449 {
4450   bpstat bs;
4451   int again = 0;
4452
4453   /* Avoid endless recursion if a `source' command is contained
4454      in bs->commands.  */
4455   if (executing_breakpoint_commands)
4456     return 0;
4457
4458   scoped_restore save_executing
4459     = make_scoped_restore (&executing_breakpoint_commands, 1);
4460
4461   scoped_restore preventer = prevent_dont_repeat ();
4462
4463   /* This pointer will iterate over the list of bpstat's.  */
4464   bs = *bsp;
4465
4466   breakpoint_proceeded = 0;
4467   for (; bs != NULL; bs = bs->next)
4468     {
4469       struct command_line *cmd = NULL;
4470
4471       /* Take ownership of the BSP's command tree, if it has one.
4472
4473          The command tree could legitimately contain commands like
4474          'step' and 'next', which call clear_proceed_status, which
4475          frees stop_bpstat's command tree.  To make sure this doesn't
4476          free the tree we're executing out from under us, we need to
4477          take ownership of the tree ourselves.  Since a given bpstat's
4478          commands are only executed once, we don't need to copy it; we
4479          can clear the pointer in the bpstat, and make sure we free
4480          the tree when we're done.  */
4481       counted_command_line ccmd = bs->commands;
4482       bs->commands = NULL;
4483       if (ccmd != NULL)
4484         cmd = ccmd.get ();
4485       if (command_line_is_silent (cmd))
4486         {
4487           /* The action has been already done by bpstat_stop_status.  */
4488           cmd = cmd->next;
4489         }
4490
4491       while (cmd != NULL)
4492         {
4493           execute_control_command (cmd);
4494
4495           if (breakpoint_proceeded)
4496             break;
4497           else
4498             cmd = cmd->next;
4499         }
4500
4501       if (breakpoint_proceeded)
4502         {
4503           if (current_ui->async)
4504             /* If we are in async mode, then the target might be still
4505                running, not stopped at any breakpoint, so nothing for
4506                us to do here -- just return to the event loop.  */
4507             ;
4508           else
4509             /* In sync mode, when execute_control_command returns
4510                we're already standing on the next breakpoint.
4511                Breakpoint commands for that stop were not run, since
4512                execute_command does not run breakpoint commands --
4513                only command_line_handler does, but that one is not
4514                involved in execution of breakpoint commands.  So, we
4515                can now execute breakpoint commands.  It should be
4516                noted that making execute_command do bpstat actions is
4517                not an option -- in this case we'll have recursive
4518                invocation of bpstat for each breakpoint with a
4519                command, and can easily blow up GDB stack.  Instead, we
4520                return true, which will trigger the caller to recall us
4521                with the new stop_bpstat.  */
4522             again = 1;
4523           break;
4524         }
4525     }
4526   return again;
4527 }
4528
4529 void
4530 bpstat_do_actions (void)
4531 {
4532   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4533
4534   /* Do any commands attached to breakpoint we are stopped at.  */
4535   while (!ptid_equal (inferior_ptid, null_ptid)
4536          && target_has_execution
4537          && !is_exited (inferior_ptid)
4538          && !is_executing (inferior_ptid))
4539     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4540        and only return when it is stopped at the next breakpoint, we
4541        keep doing breakpoint actions until it returns false to
4542        indicate the inferior was not resumed.  */
4543     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4544       break;
4545
4546   discard_cleanups (cleanup_if_error);
4547 }
4548
4549 /* Print out the (old or new) value associated with a watchpoint.  */
4550
4551 static void
4552 watchpoint_value_print (struct value *val, struct ui_file *stream)
4553 {
4554   if (val == NULL)
4555     fprintf_unfiltered (stream, _("<unreadable>"));
4556   else
4557     {
4558       struct value_print_options opts;
4559       get_user_print_options (&opts);
4560       value_print (val, stream, &opts);
4561     }
4562 }
4563
4564 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4565    debugging multiple threads.  */
4566
4567 void
4568 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4569 {
4570   if (uiout->is_mi_like_p ())
4571     return;
4572
4573   uiout->text ("\n");
4574
4575   if (show_thread_that_caused_stop ())
4576     {
4577       const char *name;
4578       struct thread_info *thr = inferior_thread ();
4579
4580       uiout->text ("Thread ");
4581       uiout->field_fmt ("thread-id", "%s", print_thread_id (thr));
4582
4583       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4584       if (name != NULL)
4585         {
4586           uiout->text (" \"");
4587           uiout->field_fmt ("name", "%s", name);
4588           uiout->text ("\"");
4589         }
4590
4591       uiout->text (" hit ");
4592     }
4593 }
4594
4595 /* Generic routine for printing messages indicating why we
4596    stopped.  The behavior of this function depends on the value
4597    'print_it' in the bpstat structure.  Under some circumstances we
4598    may decide not to print anything here and delegate the task to
4599    normal_stop().  */
4600
4601 static enum print_stop_action
4602 print_bp_stop_message (bpstat bs)
4603 {
4604   switch (bs->print_it)
4605     {
4606     case print_it_noop:
4607       /* Nothing should be printed for this bpstat entry.  */
4608       return PRINT_UNKNOWN;
4609       break;
4610
4611     case print_it_done:
4612       /* We still want to print the frame, but we already printed the
4613          relevant messages.  */
4614       return PRINT_SRC_AND_LOC;
4615       break;
4616
4617     case print_it_normal:
4618       {
4619         struct breakpoint *b = bs->breakpoint_at;
4620
4621         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4622            which has since been deleted.  */
4623         if (b == NULL)
4624           return PRINT_UNKNOWN;
4625
4626         /* Normal case.  Call the breakpoint's print_it method.  */
4627         return b->ops->print_it (bs);
4628       }
4629       break;
4630
4631     default:
4632       internal_error (__FILE__, __LINE__,
4633                       _("print_bp_stop_message: unrecognized enum value"));
4634       break;
4635     }
4636 }
4637
4638 /* A helper function that prints a shared library stopped event.  */
4639
4640 static void
4641 print_solib_event (int is_catchpoint)
4642 {
4643   int any_deleted
4644     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4645   int any_added
4646     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4647
4648   if (!is_catchpoint)
4649     {
4650       if (any_added || any_deleted)
4651         current_uiout->text (_("Stopped due to shared library event:\n"));
4652       else
4653         current_uiout->text (_("Stopped due to shared library event (no "
4654                                "libraries added or removed)\n"));
4655     }
4656
4657   if (current_uiout->is_mi_like_p ())
4658     current_uiout->field_string ("reason",
4659                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4660
4661   if (any_deleted)
4662     {
4663       char *name;
4664       int ix;
4665
4666       current_uiout->text (_("  Inferior unloaded "));
4667       ui_out_emit_list list_emitter (current_uiout, "removed");
4668       for (ix = 0;
4669            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4670                         ix, name);
4671            ++ix)
4672         {
4673           if (ix > 0)
4674             current_uiout->text ("    ");
4675           current_uiout->field_string ("library", name);
4676           current_uiout->text ("\n");
4677         }
4678     }
4679
4680   if (any_added)
4681     {
4682       struct so_list *iter;
4683       int ix;
4684
4685       current_uiout->text (_("  Inferior loaded "));
4686       ui_out_emit_list list_emitter (current_uiout, "added");
4687       for (ix = 0;
4688            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4689                         ix, iter);
4690            ++ix)
4691         {
4692           if (ix > 0)
4693             current_uiout->text ("    ");
4694           current_uiout->field_string ("library", iter->so_name);
4695           current_uiout->text ("\n");
4696         }
4697     }
4698 }
4699
4700 /* Print a message indicating what happened.  This is called from
4701    normal_stop().  The input to this routine is the head of the bpstat
4702    list - a list of the eventpoints that caused this stop.  KIND is
4703    the target_waitkind for the stopping event.  This
4704    routine calls the generic print routine for printing a message
4705    about reasons for stopping.  This will print (for example) the
4706    "Breakpoint n," part of the output.  The return value of this
4707    routine is one of:
4708
4709    PRINT_UNKNOWN: Means we printed nothing.
4710    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4711    code to print the location.  An example is 
4712    "Breakpoint 1, " which should be followed by
4713    the location.
4714    PRINT_SRC_ONLY: Means we printed something, but there is no need
4715    to also print the location part of the message.
4716    An example is the catch/throw messages, which
4717    don't require a location appended to the end.
4718    PRINT_NOTHING: We have done some printing and we don't need any 
4719    further info to be printed.  */
4720
4721 enum print_stop_action
4722 bpstat_print (bpstat bs, int kind)
4723 {
4724   enum print_stop_action val;
4725
4726   /* Maybe another breakpoint in the chain caused us to stop.
4727      (Currently all watchpoints go on the bpstat whether hit or not.
4728      That probably could (should) be changed, provided care is taken
4729      with respect to bpstat_explains_signal).  */
4730   for (; bs; bs = bs->next)
4731     {
4732       val = print_bp_stop_message (bs);
4733       if (val == PRINT_SRC_ONLY 
4734           || val == PRINT_SRC_AND_LOC 
4735           || val == PRINT_NOTHING)
4736         return val;
4737     }
4738
4739   /* If we had hit a shared library event breakpoint,
4740      print_bp_stop_message would print out this message.  If we hit an
4741      OS-level shared library event, do the same thing.  */
4742   if (kind == TARGET_WAITKIND_LOADED)
4743     {
4744       print_solib_event (0);
4745       return PRINT_NOTHING;
4746     }
4747
4748   /* We reached the end of the chain, or we got a null BS to start
4749      with and nothing was printed.  */
4750   return PRINT_UNKNOWN;
4751 }
4752
4753 /* Evaluate the boolean expression EXP and return the result.  */
4754
4755 static bool
4756 breakpoint_cond_eval (expression *exp)
4757 {
4758   struct value *mark = value_mark ();
4759   bool res = value_true (evaluate_expression (exp));
4760
4761   value_free_to_mark (mark);
4762   return res;
4763 }
4764
4765 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4766
4767 bpstats::bpstats (struct bp_location *bl, bpstat **bs_link_pointer)
4768   : next (NULL),
4769     bp_location_at (bl),
4770     breakpoint_at (bl->owner),
4771     commands (NULL),
4772     old_val (NULL),
4773     print (0),
4774     stop (0),
4775     print_it (print_it_normal)
4776 {
4777   incref_bp_location (bl);
4778   **bs_link_pointer = this;
4779   *bs_link_pointer = &next;
4780 }
4781
4782 bpstats::bpstats ()
4783   : next (NULL),
4784     bp_location_at (NULL),
4785     breakpoint_at (NULL),
4786     commands (NULL),
4787     old_val (NULL),
4788     print (0),
4789     stop (0),
4790     print_it (print_it_normal)
4791 {
4792 }
4793 \f
4794 /* The target has stopped with waitstatus WS.  Check if any hardware
4795    watchpoints have triggered, according to the target.  */
4796
4797 int
4798 watchpoints_triggered (struct target_waitstatus *ws)
4799 {
4800   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4801   CORE_ADDR addr;
4802   struct breakpoint *b;
4803
4804   if (!stopped_by_watchpoint)
4805     {
4806       /* We were not stopped by a watchpoint.  Mark all watchpoints
4807          as not triggered.  */
4808       ALL_BREAKPOINTS (b)
4809         if (is_hardware_watchpoint (b))
4810           {
4811             struct watchpoint *w = (struct watchpoint *) b;
4812
4813             w->watchpoint_triggered = watch_triggered_no;
4814           }
4815
4816       return 0;
4817     }
4818
4819   if (!target_stopped_data_address (&current_target, &addr))
4820     {
4821       /* We were stopped by a watchpoint, but we don't know where.
4822          Mark all watchpoints as unknown.  */
4823       ALL_BREAKPOINTS (b)
4824         if (is_hardware_watchpoint (b))
4825           {
4826             struct watchpoint *w = (struct watchpoint *) b;
4827
4828             w->watchpoint_triggered = watch_triggered_unknown;
4829           }
4830
4831       return 1;
4832     }
4833
4834   /* The target could report the data address.  Mark watchpoints
4835      affected by this data address as triggered, and all others as not
4836      triggered.  */
4837
4838   ALL_BREAKPOINTS (b)
4839     if (is_hardware_watchpoint (b))
4840       {
4841         struct watchpoint *w = (struct watchpoint *) b;
4842         struct bp_location *loc;
4843
4844         w->watchpoint_triggered = watch_triggered_no;
4845         for (loc = b->loc; loc; loc = loc->next)
4846           {
4847             if (is_masked_watchpoint (b))
4848               {
4849                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4850                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4851
4852                 if (newaddr == start)
4853                   {
4854                     w->watchpoint_triggered = watch_triggered_yes;
4855                     break;
4856                   }
4857               }
4858             /* Exact match not required.  Within range is sufficient.  */
4859             else if (target_watchpoint_addr_within_range (&current_target,
4860                                                          addr, loc->address,
4861                                                          loc->length))
4862               {
4863                 w->watchpoint_triggered = watch_triggered_yes;
4864                 break;
4865               }
4866           }
4867       }
4868
4869   return 1;
4870 }
4871
4872 /* Possible return values for watchpoint_check.  */
4873 enum wp_check_result
4874   {
4875     /* The watchpoint has been deleted.  */
4876     WP_DELETED = 1,
4877
4878     /* The value has changed.  */
4879     WP_VALUE_CHANGED = 2,
4880
4881     /* The value has not changed.  */
4882     WP_VALUE_NOT_CHANGED = 3,
4883
4884     /* Ignore this watchpoint, no matter if the value changed or not.  */
4885     WP_IGNORE = 4,
4886   };
4887
4888 #define BP_TEMPFLAG 1
4889 #define BP_HARDWAREFLAG 2
4890
4891 /* Evaluate watchpoint condition expression and check if its value
4892    changed.  */
4893
4894 static wp_check_result
4895 watchpoint_check (bpstat bs)
4896 {
4897   struct watchpoint *b;
4898   struct frame_info *fr;
4899   int within_current_scope;
4900
4901   /* BS is built from an existing struct breakpoint.  */
4902   gdb_assert (bs->breakpoint_at != NULL);
4903   b = (struct watchpoint *) bs->breakpoint_at;
4904
4905   /* If this is a local watchpoint, we only want to check if the
4906      watchpoint frame is in scope if the current thread is the thread
4907      that was used to create the watchpoint.  */
4908   if (!watchpoint_in_thread_scope (b))
4909     return WP_IGNORE;
4910
4911   if (b->exp_valid_block == NULL)
4912     within_current_scope = 1;
4913   else
4914     {
4915       struct frame_info *frame = get_current_frame ();
4916       struct gdbarch *frame_arch = get_frame_arch (frame);
4917       CORE_ADDR frame_pc = get_frame_pc (frame);
4918
4919       /* stack_frame_destroyed_p() returns a non-zero value if we're
4920          still in the function but the stack frame has already been
4921          invalidated.  Since we can't rely on the values of local
4922          variables after the stack has been destroyed, we are treating
4923          the watchpoint in that state as `not changed' without further
4924          checking.  Don't mark watchpoints as changed if the current
4925          frame is in an epilogue - even if they are in some other
4926          frame, our view of the stack is likely to be wrong and
4927          frame_find_by_id could error out.  */
4928       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
4929         return WP_IGNORE;
4930
4931       fr = frame_find_by_id (b->watchpoint_frame);
4932       within_current_scope = (fr != NULL);
4933
4934       /* If we've gotten confused in the unwinder, we might have
4935          returned a frame that can't describe this variable.  */
4936       if (within_current_scope)
4937         {
4938           struct symbol *function;
4939
4940           function = get_frame_function (fr);
4941           if (function == NULL
4942               || !contained_in (b->exp_valid_block,
4943                                 SYMBOL_BLOCK_VALUE (function)))
4944             within_current_scope = 0;
4945         }
4946
4947       if (within_current_scope)
4948         /* If we end up stopping, the current frame will get selected
4949            in normal_stop.  So this call to select_frame won't affect
4950            the user.  */
4951         select_frame (fr);
4952     }
4953
4954   if (within_current_scope)
4955     {
4956       /* We use value_{,free_to_}mark because it could be a *long*
4957          time before we return to the command level and call
4958          free_all_values.  We can't call free_all_values because we
4959          might be in the middle of evaluating a function call.  */
4960
4961       int pc = 0;
4962       struct value *mark;
4963       struct value *new_val;
4964
4965       if (is_masked_watchpoint (b))
4966         /* Since we don't know the exact trigger address (from
4967            stopped_data_address), just tell the user we've triggered
4968            a mask watchpoint.  */
4969         return WP_VALUE_CHANGED;
4970
4971       mark = value_mark ();
4972       fetch_subexp_value (b->exp.get (), &pc, &new_val, NULL, NULL, 0);
4973
4974       if (b->val_bitsize != 0)
4975         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
4976
4977       /* We use value_equal_contents instead of value_equal because
4978          the latter coerces an array to a pointer, thus comparing just
4979          the address of the array instead of its contents.  This is
4980          not what we want.  */
4981       if ((b->val != NULL) != (new_val != NULL)
4982           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4983         {
4984           if (new_val != NULL)
4985             {
4986               release_value (new_val);
4987               value_free_to_mark (mark);
4988             }
4989           bs->old_val = b->val;
4990           b->val = new_val;
4991           b->val_valid = 1;
4992           return WP_VALUE_CHANGED;
4993         }
4994       else
4995         {
4996           /* Nothing changed.  */
4997           value_free_to_mark (mark);
4998           return WP_VALUE_NOT_CHANGED;
4999         }
5000     }
5001   else
5002     {
5003       /* This seems like the only logical thing to do because
5004          if we temporarily ignored the watchpoint, then when
5005          we reenter the block in which it is valid it contains
5006          garbage (in the case of a function, it may have two
5007          garbage values, one before and one after the prologue).
5008          So we can't even detect the first assignment to it and
5009          watch after that (since the garbage may or may not equal
5010          the first value assigned).  */
5011       /* We print all the stop information in
5012          breakpoint_ops->print_it, but in this case, by the time we
5013          call breakpoint_ops->print_it this bp will be deleted
5014          already.  So we have no choice but print the information
5015          here.  */
5016
5017       SWITCH_THRU_ALL_UIS ()
5018         {
5019           struct ui_out *uiout = current_uiout;
5020
5021           if (uiout->is_mi_like_p ())
5022             uiout->field_string
5023               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5024           uiout->text ("\nWatchpoint ");
5025           uiout->field_int ("wpnum", b->number);
5026           uiout->text (" deleted because the program has left the block in\n"
5027                        "which its expression is valid.\n");
5028         }
5029
5030       /* Make sure the watchpoint's commands aren't executed.  */
5031       b->commands = NULL;
5032       watchpoint_del_at_next_stop (b);
5033
5034       return WP_DELETED;
5035     }
5036 }
5037
5038 /* Return true if it looks like target has stopped due to hitting
5039    breakpoint location BL.  This function does not check if we should
5040    stop, only if BL explains the stop.  */
5041
5042 static int
5043 bpstat_check_location (const struct bp_location *bl,
5044                        const address_space *aspace, CORE_ADDR bp_addr,
5045                        const struct target_waitstatus *ws)
5046 {
5047   struct breakpoint *b = bl->owner;
5048
5049   /* BL is from an existing breakpoint.  */
5050   gdb_assert (b != NULL);
5051
5052   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5053 }
5054
5055 /* Determine if the watched values have actually changed, and we
5056    should stop.  If not, set BS->stop to 0.  */
5057
5058 static void
5059 bpstat_check_watchpoint (bpstat bs)
5060 {
5061   const struct bp_location *bl;
5062   struct watchpoint *b;
5063
5064   /* BS is built for existing struct breakpoint.  */
5065   bl = bs->bp_location_at;
5066   gdb_assert (bl != NULL);
5067   b = (struct watchpoint *) bs->breakpoint_at;
5068   gdb_assert (b != NULL);
5069
5070     {
5071       int must_check_value = 0;
5072       
5073       if (b->type == bp_watchpoint)
5074         /* For a software watchpoint, we must always check the
5075            watched value.  */
5076         must_check_value = 1;
5077       else if (b->watchpoint_triggered == watch_triggered_yes)
5078         /* We have a hardware watchpoint (read, write, or access)
5079            and the target earlier reported an address watched by
5080            this watchpoint.  */
5081         must_check_value = 1;
5082       else if (b->watchpoint_triggered == watch_triggered_unknown
5083                && b->type == bp_hardware_watchpoint)
5084         /* We were stopped by a hardware watchpoint, but the target could
5085            not report the data address.  We must check the watchpoint's
5086            value.  Access and read watchpoints are out of luck; without
5087            a data address, we can't figure it out.  */
5088         must_check_value = 1;
5089
5090       if (must_check_value)
5091         {
5092           wp_check_result e;
5093
5094           TRY
5095             {
5096               e = watchpoint_check (bs);
5097             }
5098           CATCH (ex, RETURN_MASK_ALL)
5099             {
5100               exception_fprintf (gdb_stderr, ex,
5101                                  "Error evaluating expression "
5102                                  "for watchpoint %d\n",
5103                                  b->number);
5104
5105               SWITCH_THRU_ALL_UIS ()
5106                 {
5107                   printf_filtered (_("Watchpoint %d deleted.\n"),
5108                                    b->number);
5109                 }
5110               watchpoint_del_at_next_stop (b);
5111               e = WP_DELETED;
5112             }
5113           END_CATCH
5114
5115           switch (e)
5116             {
5117             case WP_DELETED:
5118               /* We've already printed what needs to be printed.  */
5119               bs->print_it = print_it_done;
5120               /* Stop.  */
5121               break;
5122             case WP_IGNORE:
5123               bs->print_it = print_it_noop;
5124               bs->stop = 0;
5125               break;
5126             case WP_VALUE_CHANGED:
5127               if (b->type == bp_read_watchpoint)
5128                 {
5129                   /* There are two cases to consider here:
5130
5131                      1. We're watching the triggered memory for reads.
5132                      In that case, trust the target, and always report
5133                      the watchpoint hit to the user.  Even though
5134                      reads don't cause value changes, the value may
5135                      have changed since the last time it was read, and
5136                      since we're not trapping writes, we will not see
5137                      those, and as such we should ignore our notion of
5138                      old value.
5139
5140                      2. We're watching the triggered memory for both
5141                      reads and writes.  There are two ways this may
5142                      happen:
5143
5144                      2.1. This is a target that can't break on data
5145                      reads only, but can break on accesses (reads or
5146                      writes), such as e.g., x86.  We detect this case
5147                      at the time we try to insert read watchpoints.
5148
5149                      2.2. Otherwise, the target supports read
5150                      watchpoints, but, the user set an access or write
5151                      watchpoint watching the same memory as this read
5152                      watchpoint.
5153
5154                      If we're watching memory writes as well as reads,
5155                      ignore watchpoint hits when we find that the
5156                      value hasn't changed, as reads don't cause
5157                      changes.  This still gives false positives when
5158                      the program writes the same value to memory as
5159                      what there was already in memory (we will confuse
5160                      it for a read), but it's much better than
5161                      nothing.  */
5162
5163                   int other_write_watchpoint = 0;
5164
5165                   if (bl->watchpoint_type == hw_read)
5166                     {
5167                       struct breakpoint *other_b;
5168
5169                       ALL_BREAKPOINTS (other_b)
5170                         if (other_b->type == bp_hardware_watchpoint
5171                             || other_b->type == bp_access_watchpoint)
5172                           {
5173                             struct watchpoint *other_w =
5174                               (struct watchpoint *) other_b;
5175
5176                             if (other_w->watchpoint_triggered
5177                                 == watch_triggered_yes)
5178                               {
5179                                 other_write_watchpoint = 1;
5180                                 break;
5181                               }
5182                           }
5183                     }
5184
5185                   if (other_write_watchpoint
5186                       || bl->watchpoint_type == hw_access)
5187                     {
5188                       /* We're watching the same memory for writes,
5189                          and the value changed since the last time we
5190                          updated it, so this trap must be for a write.
5191                          Ignore it.  */
5192                       bs->print_it = print_it_noop;
5193                       bs->stop = 0;
5194                     }
5195                 }
5196               break;
5197             case WP_VALUE_NOT_CHANGED:
5198               if (b->type == bp_hardware_watchpoint
5199                   || b->type == bp_watchpoint)
5200                 {
5201                   /* Don't stop: write watchpoints shouldn't fire if
5202                      the value hasn't changed.  */
5203                   bs->print_it = print_it_noop;
5204                   bs->stop = 0;
5205                 }
5206               /* Stop.  */
5207               break;
5208             default:
5209               /* Can't happen.  */
5210               break;
5211             }
5212         }
5213       else      /* must_check_value == 0 */
5214         {
5215           /* This is a case where some watchpoint(s) triggered, but
5216              not at the address of this watchpoint, or else no
5217              watchpoint triggered after all.  So don't print
5218              anything for this watchpoint.  */
5219           bs->print_it = print_it_noop;
5220           bs->stop = 0;
5221         }
5222     }
5223 }
5224
5225 /* For breakpoints that are currently marked as telling gdb to stop,
5226    check conditions (condition proper, frame, thread and ignore count)
5227    of breakpoint referred to by BS.  If we should not stop for this
5228    breakpoint, set BS->stop to 0.  */
5229
5230 static void
5231 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5232 {
5233   const struct bp_location *bl;
5234   struct breakpoint *b;
5235   /* Assume stop.  */
5236   bool condition_result = true;
5237   struct expression *cond;
5238
5239   gdb_assert (bs->stop);
5240
5241   /* BS is built for existing struct breakpoint.  */
5242   bl = bs->bp_location_at;
5243   gdb_assert (bl != NULL);
5244   b = bs->breakpoint_at;
5245   gdb_assert (b != NULL);
5246
5247   /* Even if the target evaluated the condition on its end and notified GDB, we
5248      need to do so again since GDB does not know if we stopped due to a
5249      breakpoint or a single step breakpoint.  */
5250
5251   if (frame_id_p (b->frame_id)
5252       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5253     {
5254       bs->stop = 0;
5255       return;
5256     }
5257
5258   /* If this is a thread/task-specific breakpoint, don't waste cpu
5259      evaluating the condition if this isn't the specified
5260      thread/task.  */
5261   if ((b->thread != -1 && b->thread != ptid_to_global_thread_id (ptid))
5262       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5263
5264     {
5265       bs->stop = 0;
5266       return;
5267     }
5268
5269   /* Evaluate extension language breakpoints that have a "stop" method
5270      implemented.  */
5271   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5272
5273   if (is_watchpoint (b))
5274     {
5275       struct watchpoint *w = (struct watchpoint *) b;
5276
5277       cond = w->cond_exp.get ();
5278     }
5279   else
5280     cond = bl->cond.get ();
5281
5282   if (cond && b->disposition != disp_del_at_next_stop)
5283     {
5284       int within_current_scope = 1;
5285       struct watchpoint * w;
5286
5287       /* We use value_mark and value_free_to_mark because it could
5288          be a long time before we return to the command level and
5289          call free_all_values.  We can't call free_all_values
5290          because we might be in the middle of evaluating a
5291          function call.  */
5292       struct value *mark = value_mark ();
5293
5294       if (is_watchpoint (b))
5295         w = (struct watchpoint *) b;
5296       else
5297         w = NULL;
5298
5299       /* Need to select the frame, with all that implies so that
5300          the conditions will have the right context.  Because we
5301          use the frame, we will not see an inlined function's
5302          variables when we arrive at a breakpoint at the start
5303          of the inlined function; the current frame will be the
5304          call site.  */
5305       if (w == NULL || w->cond_exp_valid_block == NULL)
5306         select_frame (get_current_frame ());
5307       else
5308         {
5309           struct frame_info *frame;
5310
5311           /* For local watchpoint expressions, which particular
5312              instance of a local is being watched matters, so we
5313              keep track of the frame to evaluate the expression
5314              in.  To evaluate the condition however, it doesn't
5315              really matter which instantiation of the function
5316              where the condition makes sense triggers the
5317              watchpoint.  This allows an expression like "watch
5318              global if q > 10" set in `func', catch writes to
5319              global on all threads that call `func', or catch
5320              writes on all recursive calls of `func' by a single
5321              thread.  We simply always evaluate the condition in
5322              the innermost frame that's executing where it makes
5323              sense to evaluate the condition.  It seems
5324              intuitive.  */
5325           frame = block_innermost_frame (w->cond_exp_valid_block);
5326           if (frame != NULL)
5327             select_frame (frame);
5328           else
5329             within_current_scope = 0;
5330         }
5331       if (within_current_scope)
5332         {
5333           TRY
5334             {
5335               condition_result = breakpoint_cond_eval (cond);
5336             }
5337           CATCH (ex, RETURN_MASK_ALL)
5338             {
5339               exception_fprintf (gdb_stderr, ex,
5340                                  "Error in testing breakpoint condition:\n");
5341             }
5342           END_CATCH
5343         }
5344       else
5345         {
5346           warning (_("Watchpoint condition cannot be tested "
5347                      "in the current scope"));
5348           /* If we failed to set the right context for this
5349              watchpoint, unconditionally report it.  */
5350         }
5351       /* FIXME-someday, should give breakpoint #.  */
5352       value_free_to_mark (mark);
5353     }
5354
5355   if (cond && !condition_result)
5356     {
5357       bs->stop = 0;
5358     }
5359   else if (b->ignore_count > 0)
5360     {
5361       b->ignore_count--;
5362       bs->stop = 0;
5363       /* Increase the hit count even though we don't stop.  */
5364       ++(b->hit_count);
5365       observer_notify_breakpoint_modified (b);
5366     }   
5367 }
5368
5369 /* Returns true if we need to track moribund locations of LOC's type
5370    on the current target.  */
5371
5372 static int
5373 need_moribund_for_location_type (struct bp_location *loc)
5374 {
5375   return ((loc->loc_type == bp_loc_software_breakpoint
5376            && !target_supports_stopped_by_sw_breakpoint ())
5377           || (loc->loc_type == bp_loc_hardware_breakpoint
5378               && !target_supports_stopped_by_hw_breakpoint ()));
5379 }
5380
5381
5382 /* Get a bpstat associated with having just stopped at address
5383    BP_ADDR in thread PTID.
5384
5385    Determine whether we stopped at a breakpoint, etc, or whether we
5386    don't understand this stop.  Result is a chain of bpstat's such
5387    that:
5388
5389    if we don't understand the stop, the result is a null pointer.
5390
5391    if we understand why we stopped, the result is not null.
5392
5393    Each element of the chain refers to a particular breakpoint or
5394    watchpoint at which we have stopped.  (We may have stopped for
5395    several reasons concurrently.)
5396
5397    Each element of the chain has valid next, breakpoint_at,
5398    commands, FIXME??? fields.  */
5399
5400 bpstat
5401 bpstat_stop_status (const address_space *aspace,
5402                     CORE_ADDR bp_addr, ptid_t ptid,
5403                     const struct target_waitstatus *ws)
5404 {
5405   struct breakpoint *b = NULL;
5406   struct bp_location *bl;
5407   struct bp_location *loc;
5408   /* First item of allocated bpstat's.  */
5409   bpstat bs_head = NULL, *bs_link = &bs_head;
5410   /* Pointer to the last thing in the chain currently.  */
5411   bpstat bs;
5412   int ix;
5413   int need_remove_insert;
5414   int removed_any;
5415
5416   /* First, build the bpstat chain with locations that explain a
5417      target stop, while being careful to not set the target running,
5418      as that may invalidate locations (in particular watchpoint
5419      locations are recreated).  Resuming will happen here with
5420      breakpoint conditions or watchpoint expressions that include
5421      inferior function calls.  */
5422
5423   ALL_BREAKPOINTS (b)
5424     {
5425       if (!breakpoint_enabled (b))
5426         continue;
5427
5428       for (bl = b->loc; bl != NULL; bl = bl->next)
5429         {
5430           /* For hardware watchpoints, we look only at the first
5431              location.  The watchpoint_check function will work on the
5432              entire expression, not the individual locations.  For
5433              read watchpoints, the watchpoints_triggered function has
5434              checked all locations already.  */
5435           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5436             break;
5437
5438           if (!bl->enabled || bl->shlib_disabled)
5439             continue;
5440
5441           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5442             continue;
5443
5444           /* Come here if it's a watchpoint, or if the break address
5445              matches.  */
5446
5447           bs = new bpstats (bl, &bs_link);      /* Alloc a bpstat to
5448                                                    explain stop.  */
5449
5450           /* Assume we stop.  Should we find a watchpoint that is not
5451              actually triggered, or if the condition of the breakpoint
5452              evaluates as false, we'll reset 'stop' to 0.  */
5453           bs->stop = 1;
5454           bs->print = 1;
5455
5456           /* If this is a scope breakpoint, mark the associated
5457              watchpoint as triggered so that we will handle the
5458              out-of-scope event.  We'll get to the watchpoint next
5459              iteration.  */
5460           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5461             {
5462               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5463
5464               w->watchpoint_triggered = watch_triggered_yes;
5465             }
5466         }
5467     }
5468
5469   /* Check if a moribund breakpoint explains the stop.  */
5470   if (!target_supports_stopped_by_sw_breakpoint ()
5471       || !target_supports_stopped_by_hw_breakpoint ())
5472     {
5473       for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5474         {
5475           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5476               && need_moribund_for_location_type (loc))
5477             {
5478               bs = new bpstats (loc, &bs_link);
5479               /* For hits of moribund locations, we should just proceed.  */
5480               bs->stop = 0;
5481               bs->print = 0;
5482               bs->print_it = print_it_noop;
5483             }
5484         }
5485     }
5486
5487   /* A bit of special processing for shlib breakpoints.  We need to
5488      process solib loading here, so that the lists of loaded and
5489      unloaded libraries are correct before we handle "catch load" and
5490      "catch unload".  */
5491   for (bs = bs_head; bs != NULL; bs = bs->next)
5492     {
5493       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5494         {
5495           handle_solib_event ();
5496           break;
5497         }
5498     }
5499
5500   /* Now go through the locations that caused the target to stop, and
5501      check whether we're interested in reporting this stop to higher
5502      layers, or whether we should resume the target transparently.  */
5503
5504   removed_any = 0;
5505
5506   for (bs = bs_head; bs != NULL; bs = bs->next)
5507     {
5508       if (!bs->stop)
5509         continue;
5510
5511       b = bs->breakpoint_at;
5512       b->ops->check_status (bs);
5513       if (bs->stop)
5514         {
5515           bpstat_check_breakpoint_conditions (bs, ptid);
5516
5517           if (bs->stop)
5518             {
5519               ++(b->hit_count);
5520               observer_notify_breakpoint_modified (b);
5521
5522               /* We will stop here.  */
5523               if (b->disposition == disp_disable)
5524                 {
5525                   --(b->enable_count);
5526                   if (b->enable_count <= 0)
5527                     b->enable_state = bp_disabled;
5528                   removed_any = 1;
5529                 }
5530               if (b->silent)
5531                 bs->print = 0;
5532               bs->commands = b->commands;
5533               if (command_line_is_silent (bs->commands
5534                                           ? bs->commands.get () : NULL))
5535                 bs->print = 0;
5536
5537               b->ops->after_condition_true (bs);
5538             }
5539
5540         }
5541
5542       /* Print nothing for this entry if we don't stop or don't
5543          print.  */
5544       if (!bs->stop || !bs->print)
5545         bs->print_it = print_it_noop;
5546     }
5547
5548   /* If we aren't stopping, the value of some hardware watchpoint may
5549      not have changed, but the intermediate memory locations we are
5550      watching may have.  Don't bother if we're stopping; this will get
5551      done later.  */
5552   need_remove_insert = 0;
5553   if (! bpstat_causes_stop (bs_head))
5554     for (bs = bs_head; bs != NULL; bs = bs->next)
5555       if (!bs->stop
5556           && bs->breakpoint_at
5557           && is_hardware_watchpoint (bs->breakpoint_at))
5558         {
5559           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5560
5561           update_watchpoint (w, 0 /* don't reparse.  */);
5562           need_remove_insert = 1;
5563         }
5564
5565   if (need_remove_insert)
5566     update_global_location_list (UGLL_MAY_INSERT);
5567   else if (removed_any)
5568     update_global_location_list (UGLL_DONT_INSERT);
5569
5570   return bs_head;
5571 }
5572
5573 static void
5574 handle_jit_event (void)
5575 {
5576   struct frame_info *frame;
5577   struct gdbarch *gdbarch;
5578
5579   if (debug_infrun)
5580     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5581
5582   /* Switch terminal for any messages produced by
5583      breakpoint_re_set.  */
5584   target_terminal::ours_for_output ();
5585
5586   frame = get_current_frame ();
5587   gdbarch = get_frame_arch (frame);
5588
5589   jit_event_handler (gdbarch);
5590
5591   target_terminal::inferior ();
5592 }
5593
5594 /* Prepare WHAT final decision for infrun.  */
5595
5596 /* Decide what infrun needs to do with this bpstat.  */
5597
5598 struct bpstat_what
5599 bpstat_what (bpstat bs_head)
5600 {
5601   struct bpstat_what retval;
5602   bpstat bs;
5603
5604   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5605   retval.call_dummy = STOP_NONE;
5606   retval.is_longjmp = 0;
5607
5608   for (bs = bs_head; bs != NULL; bs = bs->next)
5609     {
5610       /* Extract this BS's action.  After processing each BS, we check
5611          if its action overrides all we've seem so far.  */
5612       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5613       enum bptype bptype;
5614
5615       if (bs->breakpoint_at == NULL)
5616         {
5617           /* I suspect this can happen if it was a momentary
5618              breakpoint which has since been deleted.  */
5619           bptype = bp_none;
5620         }
5621       else
5622         bptype = bs->breakpoint_at->type;
5623
5624       switch (bptype)
5625         {
5626         case bp_none:
5627           break;
5628         case bp_breakpoint:
5629         case bp_hardware_breakpoint:
5630         case bp_single_step:
5631         case bp_until:
5632         case bp_finish:
5633         case bp_shlib_event:
5634           if (bs->stop)
5635             {
5636               if (bs->print)
5637                 this_action = BPSTAT_WHAT_STOP_NOISY;
5638               else
5639                 this_action = BPSTAT_WHAT_STOP_SILENT;
5640             }
5641           else
5642             this_action = BPSTAT_WHAT_SINGLE;
5643           break;
5644         case bp_watchpoint:
5645         case bp_hardware_watchpoint:
5646         case bp_read_watchpoint:
5647         case bp_access_watchpoint:
5648           if (bs->stop)
5649             {
5650               if (bs->print)
5651                 this_action = BPSTAT_WHAT_STOP_NOISY;
5652               else
5653                 this_action = BPSTAT_WHAT_STOP_SILENT;
5654             }
5655           else
5656             {
5657               /* There was a watchpoint, but we're not stopping.
5658                  This requires no further action.  */
5659             }
5660           break;
5661         case bp_longjmp:
5662         case bp_longjmp_call_dummy:
5663         case bp_exception:
5664           if (bs->stop)
5665             {
5666               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5667               retval.is_longjmp = bptype != bp_exception;
5668             }
5669           else
5670             this_action = BPSTAT_WHAT_SINGLE;
5671           break;
5672         case bp_longjmp_resume:
5673         case bp_exception_resume:
5674           if (bs->stop)
5675             {
5676               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5677               retval.is_longjmp = bptype == bp_longjmp_resume;
5678             }
5679           else
5680             this_action = BPSTAT_WHAT_SINGLE;
5681           break;
5682         case bp_step_resume:
5683           if (bs->stop)
5684             this_action = BPSTAT_WHAT_STEP_RESUME;
5685           else
5686             {
5687               /* It is for the wrong frame.  */
5688               this_action = BPSTAT_WHAT_SINGLE;
5689             }
5690           break;
5691         case bp_hp_step_resume:
5692           if (bs->stop)
5693             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5694           else
5695             {
5696               /* It is for the wrong frame.  */
5697               this_action = BPSTAT_WHAT_SINGLE;
5698             }
5699           break;
5700         case bp_watchpoint_scope:
5701         case bp_thread_event:
5702         case bp_overlay_event:
5703         case bp_longjmp_master:
5704         case bp_std_terminate_master:
5705         case bp_exception_master:
5706           this_action = BPSTAT_WHAT_SINGLE;
5707           break;
5708         case bp_catchpoint:
5709           if (bs->stop)
5710             {
5711               if (bs->print)
5712                 this_action = BPSTAT_WHAT_STOP_NOISY;
5713               else
5714                 this_action = BPSTAT_WHAT_STOP_SILENT;
5715             }
5716           else
5717             {
5718               /* There was a catchpoint, but we're not stopping.
5719                  This requires no further action.  */
5720             }
5721           break;
5722         case bp_jit_event:
5723           this_action = BPSTAT_WHAT_SINGLE;
5724           break;
5725         case bp_call_dummy:
5726           /* Make sure the action is stop (silent or noisy),
5727              so infrun.c pops the dummy frame.  */
5728           retval.call_dummy = STOP_STACK_DUMMY;
5729           this_action = BPSTAT_WHAT_STOP_SILENT;
5730           break;
5731         case bp_std_terminate:
5732           /* Make sure the action is stop (silent or noisy),
5733              so infrun.c pops the dummy frame.  */
5734           retval.call_dummy = STOP_STD_TERMINATE;
5735           this_action = BPSTAT_WHAT_STOP_SILENT;
5736           break;
5737         case bp_tracepoint:
5738         case bp_fast_tracepoint:
5739         case bp_static_tracepoint:
5740           /* Tracepoint hits should not be reported back to GDB, and
5741              if one got through somehow, it should have been filtered
5742              out already.  */
5743           internal_error (__FILE__, __LINE__,
5744                           _("bpstat_what: tracepoint encountered"));
5745           break;
5746         case bp_gnu_ifunc_resolver:
5747           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5748           this_action = BPSTAT_WHAT_SINGLE;
5749           break;
5750         case bp_gnu_ifunc_resolver_return:
5751           /* The breakpoint will be removed, execution will restart from the
5752              PC of the former breakpoint.  */
5753           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5754           break;
5755
5756         case bp_dprintf:
5757           if (bs->stop)
5758             this_action = BPSTAT_WHAT_STOP_SILENT;
5759           else
5760             this_action = BPSTAT_WHAT_SINGLE;
5761           break;
5762
5763         default:
5764           internal_error (__FILE__, __LINE__,
5765                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5766         }
5767
5768       retval.main_action = std::max (retval.main_action, this_action);
5769     }
5770
5771   return retval;
5772 }
5773
5774 void
5775 bpstat_run_callbacks (bpstat bs_head)
5776 {
5777   bpstat bs;
5778
5779   for (bs = bs_head; bs != NULL; bs = bs->next)
5780     {
5781       struct breakpoint *b = bs->breakpoint_at;
5782
5783       if (b == NULL)
5784         continue;
5785       switch (b->type)
5786         {
5787         case bp_jit_event:
5788           handle_jit_event ();
5789           break;
5790         case bp_gnu_ifunc_resolver:
5791           gnu_ifunc_resolver_stop (b);
5792           break;
5793         case bp_gnu_ifunc_resolver_return:
5794           gnu_ifunc_resolver_return_stop (b);
5795           break;
5796         }
5797     }
5798 }
5799
5800 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5801    without hardware support).  This isn't related to a specific bpstat,
5802    just to things like whether watchpoints are set.  */
5803
5804 int
5805 bpstat_should_step (void)
5806 {
5807   struct breakpoint *b;
5808
5809   ALL_BREAKPOINTS (b)
5810     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5811       return 1;
5812   return 0;
5813 }
5814
5815 int
5816 bpstat_causes_stop (bpstat bs)
5817 {
5818   for (; bs != NULL; bs = bs->next)
5819     if (bs->stop)
5820       return 1;
5821
5822   return 0;
5823 }
5824
5825 \f
5826
5827 /* Compute a string of spaces suitable to indent the next line
5828    so it starts at the position corresponding to the table column
5829    named COL_NAME in the currently active table of UIOUT.  */
5830
5831 static char *
5832 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5833 {
5834   static char wrap_indent[80];
5835   int i, total_width, width, align;
5836   const char *text;
5837
5838   total_width = 0;
5839   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
5840     {
5841       if (strcmp (text, col_name) == 0)
5842         {
5843           gdb_assert (total_width < sizeof wrap_indent);
5844           memset (wrap_indent, ' ', total_width);
5845           wrap_indent[total_width] = 0;
5846
5847           return wrap_indent;
5848         }
5849
5850       total_width += width + 1;
5851     }
5852
5853   return NULL;
5854 }
5855
5856 /* Determine if the locations of this breakpoint will have their conditions
5857    evaluated by the target, host or a mix of both.  Returns the following:
5858
5859     "host": Host evals condition.
5860     "host or target": Host or Target evals condition.
5861     "target": Target evals condition.
5862 */
5863
5864 static const char *
5865 bp_condition_evaluator (struct breakpoint *b)
5866 {
5867   struct bp_location *bl;
5868   char host_evals = 0;
5869   char target_evals = 0;
5870
5871   if (!b)
5872     return NULL;
5873
5874   if (!is_breakpoint (b))
5875     return NULL;
5876
5877   if (gdb_evaluates_breakpoint_condition_p ()
5878       || !target_supports_evaluation_of_breakpoint_conditions ())
5879     return condition_evaluation_host;
5880
5881   for (bl = b->loc; bl; bl = bl->next)
5882     {
5883       if (bl->cond_bytecode)
5884         target_evals++;
5885       else
5886         host_evals++;
5887     }
5888
5889   if (host_evals && target_evals)
5890     return condition_evaluation_both;
5891   else if (target_evals)
5892     return condition_evaluation_target;
5893   else
5894     return condition_evaluation_host;
5895 }
5896
5897 /* Determine the breakpoint location's condition evaluator.  This is
5898    similar to bp_condition_evaluator, but for locations.  */
5899
5900 static const char *
5901 bp_location_condition_evaluator (struct bp_location *bl)
5902 {
5903   if (bl && !is_breakpoint (bl->owner))
5904     return NULL;
5905
5906   if (gdb_evaluates_breakpoint_condition_p ()
5907       || !target_supports_evaluation_of_breakpoint_conditions ())
5908     return condition_evaluation_host;
5909
5910   if (bl && bl->cond_bytecode)
5911     return condition_evaluation_target;
5912   else
5913     return condition_evaluation_host;
5914 }
5915
5916 /* Print the LOC location out of the list of B->LOC locations.  */
5917
5918 static void
5919 print_breakpoint_location (struct breakpoint *b,
5920                            struct bp_location *loc)
5921 {
5922   struct ui_out *uiout = current_uiout;
5923
5924   scoped_restore_current_program_space restore_pspace;
5925
5926   if (loc != NULL && loc->shlib_disabled)
5927     loc = NULL;
5928
5929   if (loc != NULL)
5930     set_current_program_space (loc->pspace);
5931
5932   if (b->display_canonical)
5933     uiout->field_string ("what", event_location_to_string (b->location.get ()));
5934   else if (loc && loc->symtab)
5935     {
5936       const struct symbol *sym = loc->symbol;
5937
5938       if (sym == NULL)
5939         sym = find_pc_sect_function (loc->address, loc->section);
5940
5941       if (sym)
5942         {
5943           uiout->text ("in ");
5944           uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
5945           uiout->text (" ");
5946           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
5947           uiout->text ("at ");
5948         }
5949       uiout->field_string ("file",
5950                            symtab_to_filename_for_display (loc->symtab));
5951       uiout->text (":");
5952
5953       if (uiout->is_mi_like_p ())
5954         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
5955       
5956       uiout->field_int ("line", loc->line_number);
5957     }
5958   else if (loc)
5959     {
5960       string_file stb;
5961
5962       print_address_symbolic (loc->gdbarch, loc->address, &stb,
5963                               demangle, "");
5964       uiout->field_stream ("at", stb);
5965     }
5966   else
5967     {
5968       uiout->field_string ("pending",
5969                            event_location_to_string (b->location.get ()));
5970       /* If extra_string is available, it could be holding a condition
5971          or dprintf arguments.  In either case, make sure it is printed,
5972          too, but only for non-MI streams.  */
5973       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
5974         {
5975           if (b->type == bp_dprintf)
5976             uiout->text (",");
5977           else
5978             uiout->text (" ");
5979           uiout->text (b->extra_string);
5980         }
5981     }
5982
5983   if (loc && is_breakpoint (b)
5984       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5985       && bp_condition_evaluator (b) == condition_evaluation_both)
5986     {
5987       uiout->text (" (");
5988       uiout->field_string ("evaluated-by",
5989                            bp_location_condition_evaluator (loc));
5990       uiout->text (")");
5991     }
5992 }
5993
5994 static const char *
5995 bptype_string (enum bptype type)
5996 {
5997   struct ep_type_description
5998     {
5999       enum bptype type;
6000       const char *description;
6001     };
6002   static struct ep_type_description bptypes[] =
6003   {
6004     {bp_none, "?deleted?"},
6005     {bp_breakpoint, "breakpoint"},
6006     {bp_hardware_breakpoint, "hw breakpoint"},
6007     {bp_single_step, "sw single-step"},
6008     {bp_until, "until"},
6009     {bp_finish, "finish"},
6010     {bp_watchpoint, "watchpoint"},
6011     {bp_hardware_watchpoint, "hw watchpoint"},
6012     {bp_read_watchpoint, "read watchpoint"},
6013     {bp_access_watchpoint, "acc watchpoint"},
6014     {bp_longjmp, "longjmp"},
6015     {bp_longjmp_resume, "longjmp resume"},
6016     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6017     {bp_exception, "exception"},
6018     {bp_exception_resume, "exception resume"},
6019     {bp_step_resume, "step resume"},
6020     {bp_hp_step_resume, "high-priority step resume"},
6021     {bp_watchpoint_scope, "watchpoint scope"},
6022     {bp_call_dummy, "call dummy"},
6023     {bp_std_terminate, "std::terminate"},
6024     {bp_shlib_event, "shlib events"},
6025     {bp_thread_event, "thread events"},
6026     {bp_overlay_event, "overlay events"},
6027     {bp_longjmp_master, "longjmp master"},
6028     {bp_std_terminate_master, "std::terminate master"},
6029     {bp_exception_master, "exception master"},
6030     {bp_catchpoint, "catchpoint"},
6031     {bp_tracepoint, "tracepoint"},
6032     {bp_fast_tracepoint, "fast tracepoint"},
6033     {bp_static_tracepoint, "static tracepoint"},
6034     {bp_dprintf, "dprintf"},
6035     {bp_jit_event, "jit events"},
6036     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6037     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6038   };
6039
6040   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6041       || ((int) type != bptypes[(int) type].type))
6042     internal_error (__FILE__, __LINE__,
6043                     _("bptypes table does not describe type #%d."),
6044                     (int) type);
6045
6046   return bptypes[(int) type].description;
6047 }
6048
6049 /* For MI, output a field named 'thread-groups' with a list as the value.
6050    For CLI, prefix the list with the string 'inf'. */
6051
6052 static void
6053 output_thread_groups (struct ui_out *uiout,
6054                       const char *field_name,
6055                       VEC(int) *inf_num,
6056                       int mi_only)
6057 {
6058   int is_mi = uiout->is_mi_like_p ();
6059   int inf;
6060   int i;
6061
6062   /* For backward compatibility, don't display inferiors in CLI unless
6063      there are several.  Always display them for MI. */
6064   if (!is_mi && mi_only)
6065     return;
6066
6067   ui_out_emit_list list_emitter (uiout, field_name);
6068
6069   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6070     {
6071       if (is_mi)
6072         {
6073           char mi_group[10];
6074
6075           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6076           uiout->field_string (NULL, mi_group);
6077         }
6078       else
6079         {
6080           if (i == 0)
6081             uiout->text (" inf ");
6082           else
6083             uiout->text (", ");
6084         
6085           uiout->text (plongest (inf));
6086         }
6087     }
6088 }
6089
6090 /* Print B to gdb_stdout.  */
6091
6092 static void
6093 print_one_breakpoint_location (struct breakpoint *b,
6094                                struct bp_location *loc,
6095                                int loc_number,
6096                                struct bp_location **last_loc,
6097                                int allflag)
6098 {
6099   struct command_line *l;
6100   static char bpenables[] = "nynny";
6101
6102   struct ui_out *uiout = current_uiout;
6103   int header_of_multiple = 0;
6104   int part_of_multiple = (loc != NULL);
6105   struct value_print_options opts;
6106
6107   get_user_print_options (&opts);
6108
6109   gdb_assert (!loc || loc_number != 0);
6110   /* See comment in print_one_breakpoint concerning treatment of
6111      breakpoints with single disabled location.  */
6112   if (loc == NULL 
6113       && (b->loc != NULL 
6114           && (b->loc->next != NULL || !b->loc->enabled)))
6115     header_of_multiple = 1;
6116   if (loc == NULL)
6117     loc = b->loc;
6118
6119   annotate_record ();
6120
6121   /* 1 */
6122   annotate_field (0);
6123   if (part_of_multiple)
6124     {
6125       char *formatted;
6126       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6127       uiout->field_string ("number", formatted);
6128       xfree (formatted);
6129     }
6130   else
6131     {
6132       uiout->field_int ("number", b->number);
6133     }
6134
6135   /* 2 */
6136   annotate_field (1);
6137   if (part_of_multiple)
6138     uiout->field_skip ("type");
6139   else
6140     uiout->field_string ("type", bptype_string (b->type));
6141
6142   /* 3 */
6143   annotate_field (2);
6144   if (part_of_multiple)
6145     uiout->field_skip ("disp");
6146   else
6147     uiout->field_string ("disp", bpdisp_text (b->disposition));
6148
6149
6150   /* 4 */
6151   annotate_field (3);
6152   if (part_of_multiple)
6153     uiout->field_string ("enabled", loc->enabled ? "y" : "n");
6154   else
6155     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6156   uiout->spaces (2);
6157
6158   
6159   /* 5 and 6 */
6160   if (b->ops != NULL && b->ops->print_one != NULL)
6161     {
6162       /* Although the print_one can possibly print all locations,
6163          calling it here is not likely to get any nice result.  So,
6164          make sure there's just one location.  */
6165       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6166       b->ops->print_one (b, last_loc);
6167     }
6168   else
6169     switch (b->type)
6170       {
6171       case bp_none:
6172         internal_error (__FILE__, __LINE__,
6173                         _("print_one_breakpoint: bp_none encountered\n"));
6174         break;
6175
6176       case bp_watchpoint:
6177       case bp_hardware_watchpoint:
6178       case bp_read_watchpoint:
6179       case bp_access_watchpoint:
6180         {
6181           struct watchpoint *w = (struct watchpoint *) b;
6182
6183           /* Field 4, the address, is omitted (which makes the columns
6184              not line up too nicely with the headers, but the effect
6185              is relatively readable).  */
6186           if (opts.addressprint)
6187             uiout->field_skip ("addr");
6188           annotate_field (5);
6189           uiout->field_string ("what", w->exp_string);
6190         }
6191         break;
6192
6193       case bp_breakpoint:
6194       case bp_hardware_breakpoint:
6195       case bp_single_step:
6196       case bp_until:
6197       case bp_finish:
6198       case bp_longjmp:
6199       case bp_longjmp_resume:
6200       case bp_longjmp_call_dummy:
6201       case bp_exception:
6202       case bp_exception_resume:
6203       case bp_step_resume:
6204       case bp_hp_step_resume:
6205       case bp_watchpoint_scope:
6206       case bp_call_dummy:
6207       case bp_std_terminate:
6208       case bp_shlib_event:
6209       case bp_thread_event:
6210       case bp_overlay_event:
6211       case bp_longjmp_master:
6212       case bp_std_terminate_master:
6213       case bp_exception_master:
6214       case bp_tracepoint:
6215       case bp_fast_tracepoint:
6216       case bp_static_tracepoint:
6217       case bp_dprintf:
6218       case bp_jit_event:
6219       case bp_gnu_ifunc_resolver:
6220       case bp_gnu_ifunc_resolver_return:
6221         if (opts.addressprint)
6222           {
6223             annotate_field (4);
6224             if (header_of_multiple)
6225               uiout->field_string ("addr", "<MULTIPLE>");
6226             else if (b->loc == NULL || loc->shlib_disabled)
6227               uiout->field_string ("addr", "<PENDING>");
6228             else
6229               uiout->field_core_addr ("addr",
6230                                       loc->gdbarch, loc->address);
6231           }
6232         annotate_field (5);
6233         if (!header_of_multiple)
6234           print_breakpoint_location (b, loc);
6235         if (b->loc)
6236           *last_loc = b->loc;
6237         break;
6238       }
6239
6240
6241   if (loc != NULL && !header_of_multiple)
6242     {
6243       struct inferior *inf;
6244       VEC(int) *inf_num = NULL;
6245       int mi_only = 1;
6246
6247       ALL_INFERIORS (inf)
6248         {
6249           if (inf->pspace == loc->pspace)
6250             VEC_safe_push (int, inf_num, inf->num);
6251         }
6252
6253         /* For backward compatibility, don't display inferiors in CLI unless
6254            there are several.  Always display for MI. */
6255         if (allflag
6256             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6257                 && (number_of_program_spaces () > 1
6258                     || number_of_inferiors () > 1)
6259                 /* LOC is for existing B, it cannot be in
6260                    moribund_locations and thus having NULL OWNER.  */
6261                 && loc->owner->type != bp_catchpoint))
6262         mi_only = 0;
6263       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6264       VEC_free (int, inf_num);
6265     }
6266
6267   if (!part_of_multiple)
6268     {
6269       if (b->thread != -1)
6270         {
6271           /* FIXME: This seems to be redundant and lost here; see the
6272              "stop only in" line a little further down.  */
6273           uiout->text (" thread ");
6274           uiout->field_int ("thread", b->thread);
6275         }
6276       else if (b->task != 0)
6277         {
6278           uiout->text (" task ");
6279           uiout->field_int ("task", b->task);
6280         }
6281     }
6282
6283   uiout->text ("\n");
6284
6285   if (!part_of_multiple)
6286     b->ops->print_one_detail (b, uiout);
6287
6288   if (part_of_multiple && frame_id_p (b->frame_id))
6289     {
6290       annotate_field (6);
6291       uiout->text ("\tstop only in stack frame at ");
6292       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6293          the frame ID.  */
6294       uiout->field_core_addr ("frame",
6295                               b->gdbarch, b->frame_id.stack_addr);
6296       uiout->text ("\n");
6297     }
6298   
6299   if (!part_of_multiple && b->cond_string)
6300     {
6301       annotate_field (7);
6302       if (is_tracepoint (b))
6303         uiout->text ("\ttrace only if ");
6304       else
6305         uiout->text ("\tstop only if ");
6306       uiout->field_string ("cond", b->cond_string);
6307
6308       /* Print whether the target is doing the breakpoint's condition
6309          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6310       if (is_breakpoint (b)
6311           && breakpoint_condition_evaluation_mode ()
6312           == condition_evaluation_target)
6313         {
6314           uiout->text (" (");
6315           uiout->field_string ("evaluated-by",
6316                                bp_condition_evaluator (b));
6317           uiout->text (" evals)");
6318         }
6319       uiout->text ("\n");
6320     }
6321
6322   if (!part_of_multiple && b->thread != -1)
6323     {
6324       /* FIXME should make an annotation for this.  */
6325       uiout->text ("\tstop only in thread ");
6326       if (uiout->is_mi_like_p ())
6327         uiout->field_int ("thread", b->thread);
6328       else
6329         {
6330           struct thread_info *thr = find_thread_global_id (b->thread);
6331
6332           uiout->field_string ("thread", print_thread_id (thr));
6333         }
6334       uiout->text ("\n");
6335     }
6336   
6337   if (!part_of_multiple)
6338     {
6339       if (b->hit_count)
6340         {
6341           /* FIXME should make an annotation for this.  */
6342           if (is_catchpoint (b))
6343             uiout->text ("\tcatchpoint");
6344           else if (is_tracepoint (b))
6345             uiout->text ("\ttracepoint");
6346           else
6347             uiout->text ("\tbreakpoint");
6348           uiout->text (" already hit ");
6349           uiout->field_int ("times", b->hit_count);
6350           if (b->hit_count == 1)
6351             uiout->text (" time\n");
6352           else
6353             uiout->text (" times\n");
6354         }
6355       else
6356         {
6357           /* Output the count also if it is zero, but only if this is mi.  */
6358           if (uiout->is_mi_like_p ())
6359             uiout->field_int ("times", b->hit_count);
6360         }
6361     }
6362
6363   if (!part_of_multiple && b->ignore_count)
6364     {
6365       annotate_field (8);
6366       uiout->text ("\tignore next ");
6367       uiout->field_int ("ignore", b->ignore_count);
6368       uiout->text (" hits\n");
6369     }
6370
6371   /* Note that an enable count of 1 corresponds to "enable once"
6372      behavior, which is reported by the combination of enablement and
6373      disposition, so we don't need to mention it here.  */
6374   if (!part_of_multiple && b->enable_count > 1)
6375     {
6376       annotate_field (8);
6377       uiout->text ("\tdisable after ");
6378       /* Tweak the wording to clarify that ignore and enable counts
6379          are distinct, and have additive effect.  */
6380       if (b->ignore_count)
6381         uiout->text ("additional ");
6382       else
6383         uiout->text ("next ");
6384       uiout->field_int ("enable", b->enable_count);
6385       uiout->text (" hits\n");
6386     }
6387
6388   if (!part_of_multiple && is_tracepoint (b))
6389     {
6390       struct tracepoint *tp = (struct tracepoint *) b;
6391
6392       if (tp->traceframe_usage)
6393         {
6394           uiout->text ("\ttrace buffer usage ");
6395           uiout->field_int ("traceframe-usage", tp->traceframe_usage);
6396           uiout->text (" bytes\n");
6397         }
6398     }
6399
6400   l = b->commands ? b->commands.get () : NULL;
6401   if (!part_of_multiple && l)
6402     {
6403       annotate_field (9);
6404       ui_out_emit_tuple tuple_emitter (uiout, "script");
6405       print_command_lines (uiout, l, 4);
6406     }
6407
6408   if (is_tracepoint (b))
6409     {
6410       struct tracepoint *t = (struct tracepoint *) b;
6411
6412       if (!part_of_multiple && t->pass_count)
6413         {
6414           annotate_field (10);
6415           uiout->text ("\tpass count ");
6416           uiout->field_int ("pass", t->pass_count);
6417           uiout->text (" \n");
6418         }
6419
6420       /* Don't display it when tracepoint or tracepoint location is
6421          pending.   */
6422       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6423         {
6424           annotate_field (11);
6425
6426           if (uiout->is_mi_like_p ())
6427             uiout->field_string ("installed",
6428                                  loc->inserted ? "y" : "n");
6429           else
6430             {
6431               if (loc->inserted)
6432                 uiout->text ("\t");
6433               else
6434                 uiout->text ("\tnot ");
6435               uiout->text ("installed on target\n");
6436             }
6437         }
6438     }
6439
6440   if (uiout->is_mi_like_p () && !part_of_multiple)
6441     {
6442       if (is_watchpoint (b))
6443         {
6444           struct watchpoint *w = (struct watchpoint *) b;
6445
6446           uiout->field_string ("original-location", w->exp_string);
6447         }
6448       else if (b->location != NULL
6449                && event_location_to_string (b->location.get ()) != NULL)
6450         uiout->field_string ("original-location",
6451                              event_location_to_string (b->location.get ()));
6452     }
6453 }
6454
6455 static void
6456 print_one_breakpoint (struct breakpoint *b,
6457                       struct bp_location **last_loc, 
6458                       int allflag)
6459 {
6460   struct ui_out *uiout = current_uiout;
6461
6462   {
6463     ui_out_emit_tuple tuple_emitter (uiout, "bkpt");
6464
6465     print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6466   }
6467
6468   /* If this breakpoint has custom print function,
6469      it's already printed.  Otherwise, print individual
6470      locations, if any.  */
6471   if (b->ops == NULL || b->ops->print_one == NULL)
6472     {
6473       /* If breakpoint has a single location that is disabled, we
6474          print it as if it had several locations, since otherwise it's
6475          hard to represent "breakpoint enabled, location disabled"
6476          situation.
6477
6478          Note that while hardware watchpoints have several locations
6479          internally, that's not a property exposed to user.  */
6480       if (b->loc 
6481           && !is_hardware_watchpoint (b)
6482           && (b->loc->next || !b->loc->enabled))
6483         {
6484           struct bp_location *loc;
6485           int n = 1;
6486
6487           for (loc = b->loc; loc; loc = loc->next, ++n)
6488             {
6489               ui_out_emit_tuple tuple_emitter (uiout, NULL);
6490               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6491             }
6492         }
6493     }
6494 }
6495
6496 static int
6497 breakpoint_address_bits (struct breakpoint *b)
6498 {
6499   int print_address_bits = 0;
6500   struct bp_location *loc;
6501
6502   /* Software watchpoints that aren't watching memory don't have an
6503      address to print.  */
6504   if (is_no_memory_software_watchpoint (b))
6505     return 0;
6506
6507   for (loc = b->loc; loc; loc = loc->next)
6508     {
6509       int addr_bit;
6510
6511       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6512       if (addr_bit > print_address_bits)
6513         print_address_bits = addr_bit;
6514     }
6515
6516   return print_address_bits;
6517 }
6518
6519 /* See breakpoint.h.  */
6520
6521 void
6522 print_breakpoint (breakpoint *b)
6523 {
6524   struct bp_location *dummy_loc = NULL;
6525   print_one_breakpoint (b, &dummy_loc, 0);
6526 }
6527
6528 /* Return true if this breakpoint was set by the user, false if it is
6529    internal or momentary.  */
6530
6531 int
6532 user_breakpoint_p (struct breakpoint *b)
6533 {
6534   return b->number > 0;
6535 }
6536
6537 /* See breakpoint.h.  */
6538
6539 int
6540 pending_breakpoint_p (struct breakpoint *b)
6541 {
6542   return b->loc == NULL;
6543 }
6544
6545 /* Print information on user settable breakpoint (watchpoint, etc)
6546    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6547    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6548    FILTER is non-NULL, call it on each breakpoint and only include the
6549    ones for which it returns non-zero.  Return the total number of
6550    breakpoints listed.  */
6551
6552 static int
6553 breakpoint_1 (const char *args, int allflag, 
6554               int (*filter) (const struct breakpoint *))
6555 {
6556   struct breakpoint *b;
6557   struct bp_location *last_loc = NULL;
6558   int nr_printable_breakpoints;
6559   struct value_print_options opts;
6560   int print_address_bits = 0;
6561   int print_type_col_width = 14;
6562   struct ui_out *uiout = current_uiout;
6563
6564   get_user_print_options (&opts);
6565
6566   /* Compute the number of rows in the table, as well as the size
6567      required for address fields.  */
6568   nr_printable_breakpoints = 0;
6569   ALL_BREAKPOINTS (b)
6570     {
6571       /* If we have a filter, only list the breakpoints it accepts.  */
6572       if (filter && !filter (b))
6573         continue;
6574
6575       /* If we have an "args" string, it is a list of breakpoints to 
6576          accept.  Skip the others.  */
6577       if (args != NULL && *args != '\0')
6578         {
6579           if (allflag && parse_and_eval_long (args) != b->number)
6580             continue;
6581           if (!allflag && !number_is_in_list (args, b->number))
6582             continue;
6583         }
6584
6585       if (allflag || user_breakpoint_p (b))
6586         {
6587           int addr_bit, type_len;
6588
6589           addr_bit = breakpoint_address_bits (b);
6590           if (addr_bit > print_address_bits)
6591             print_address_bits = addr_bit;
6592
6593           type_len = strlen (bptype_string (b->type));
6594           if (type_len > print_type_col_width)
6595             print_type_col_width = type_len;
6596
6597           nr_printable_breakpoints++;
6598         }
6599     }
6600
6601   {
6602     ui_out_emit_table table_emitter (uiout,
6603                                      opts.addressprint ? 6 : 5,
6604                                      nr_printable_breakpoints,
6605                                      "BreakpointTable");
6606
6607     if (nr_printable_breakpoints > 0)
6608       annotate_breakpoints_headers ();
6609     if (nr_printable_breakpoints > 0)
6610       annotate_field (0);
6611     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6612     if (nr_printable_breakpoints > 0)
6613       annotate_field (1);
6614     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6615     if (nr_printable_breakpoints > 0)
6616       annotate_field (2);
6617     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6618     if (nr_printable_breakpoints > 0)
6619       annotate_field (3);
6620     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6621     if (opts.addressprint)
6622       {
6623         if (nr_printable_breakpoints > 0)
6624           annotate_field (4);
6625         if (print_address_bits <= 32)
6626           uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6627         else
6628           uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6629       }
6630     if (nr_printable_breakpoints > 0)
6631       annotate_field (5);
6632     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6633     uiout->table_body ();
6634     if (nr_printable_breakpoints > 0)
6635       annotate_breakpoints_table ();
6636
6637     ALL_BREAKPOINTS (b)
6638       {
6639         QUIT;
6640         /* If we have a filter, only list the breakpoints it accepts.  */
6641         if (filter && !filter (b))
6642           continue;
6643
6644         /* If we have an "args" string, it is a list of breakpoints to 
6645            accept.  Skip the others.  */
6646
6647         if (args != NULL && *args != '\0')
6648           {
6649             if (allflag)        /* maintenance info breakpoint */
6650               {
6651                 if (parse_and_eval_long (args) != b->number)
6652                   continue;
6653               }
6654             else                /* all others */
6655               {
6656                 if (!number_is_in_list (args, b->number))
6657                   continue;
6658               }
6659           }
6660         /* We only print out user settable breakpoints unless the
6661            allflag is set.  */
6662         if (allflag || user_breakpoint_p (b))
6663           print_one_breakpoint (b, &last_loc, allflag);
6664       }
6665   }
6666
6667   if (nr_printable_breakpoints == 0)
6668     {
6669       /* If there's a filter, let the caller decide how to report
6670          empty list.  */
6671       if (!filter)
6672         {
6673           if (args == NULL || *args == '\0')
6674             uiout->message ("No breakpoints or watchpoints.\n");
6675           else
6676             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6677                             args);
6678         }
6679     }
6680   else
6681     {
6682       if (last_loc && !server_command)
6683         set_next_address (last_loc->gdbarch, last_loc->address);
6684     }
6685
6686   /* FIXME?  Should this be moved up so that it is only called when
6687      there have been breakpoints? */
6688   annotate_breakpoints_table_end ();
6689
6690   return nr_printable_breakpoints;
6691 }
6692
6693 /* Display the value of default-collect in a way that is generally
6694    compatible with the breakpoint list.  */
6695
6696 static void
6697 default_collect_info (void)
6698 {
6699   struct ui_out *uiout = current_uiout;
6700
6701   /* If it has no value (which is frequently the case), say nothing; a
6702      message like "No default-collect." gets in user's face when it's
6703      not wanted.  */
6704   if (!*default_collect)
6705     return;
6706
6707   /* The following phrase lines up nicely with per-tracepoint collect
6708      actions.  */
6709   uiout->text ("default collect ");
6710   uiout->field_string ("default-collect", default_collect);
6711   uiout->text (" \n");
6712 }
6713   
6714 static void
6715 info_breakpoints_command (char *args, int from_tty)
6716 {
6717   breakpoint_1 (args, 0, NULL);
6718
6719   default_collect_info ();
6720 }
6721
6722 static void
6723 info_watchpoints_command (char *args, int from_tty)
6724 {
6725   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6726   struct ui_out *uiout = current_uiout;
6727
6728   if (num_printed == 0)
6729     {
6730       if (args == NULL || *args == '\0')
6731         uiout->message ("No watchpoints.\n");
6732       else
6733         uiout->message ("No watchpoint matching '%s'.\n", args);
6734     }
6735 }
6736
6737 static void
6738 maintenance_info_breakpoints (const char *args, int from_tty)
6739 {
6740   breakpoint_1 (args, 1, NULL);
6741
6742   default_collect_info ();
6743 }
6744
6745 static int
6746 breakpoint_has_pc (struct breakpoint *b,
6747                    struct program_space *pspace,
6748                    CORE_ADDR pc, struct obj_section *section)
6749 {
6750   struct bp_location *bl = b->loc;
6751
6752   for (; bl; bl = bl->next)
6753     {
6754       if (bl->pspace == pspace
6755           && bl->address == pc
6756           && (!overlay_debugging || bl->section == section))
6757         return 1;         
6758     }
6759   return 0;
6760 }
6761
6762 /* Print a message describing any user-breakpoints set at PC.  This
6763    concerns with logical breakpoints, so we match program spaces, not
6764    address spaces.  */
6765
6766 static void
6767 describe_other_breakpoints (struct gdbarch *gdbarch,
6768                             struct program_space *pspace, CORE_ADDR pc,
6769                             struct obj_section *section, int thread)
6770 {
6771   int others = 0;
6772   struct breakpoint *b;
6773
6774   ALL_BREAKPOINTS (b)
6775     others += (user_breakpoint_p (b)
6776                && breakpoint_has_pc (b, pspace, pc, section));
6777   if (others > 0)
6778     {
6779       if (others == 1)
6780         printf_filtered (_("Note: breakpoint "));
6781       else /* if (others == ???) */
6782         printf_filtered (_("Note: breakpoints "));
6783       ALL_BREAKPOINTS (b)
6784         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6785           {
6786             others--;
6787             printf_filtered ("%d", b->number);
6788             if (b->thread == -1 && thread != -1)
6789               printf_filtered (" (all threads)");
6790             else if (b->thread != -1)
6791               printf_filtered (" (thread %d)", b->thread);
6792             printf_filtered ("%s%s ",
6793                              ((b->enable_state == bp_disabled
6794                                || b->enable_state == bp_call_disabled)
6795                               ? " (disabled)"
6796                               : ""),
6797                              (others > 1) ? "," 
6798                              : ((others == 1) ? " and" : ""));
6799           }
6800       printf_filtered (_("also set at pc "));
6801       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6802       printf_filtered (".\n");
6803     }
6804 }
6805 \f
6806
6807 /* Return true iff it is meaningful to use the address member of
6808    BPT locations.  For some breakpoint types, the locations' address members
6809    are irrelevant and it makes no sense to attempt to compare them to other
6810    addresses (or use them for any other purpose either).
6811
6812    More specifically, each of the following breakpoint types will
6813    always have a zero valued location address and we don't want to mark
6814    breakpoints of any of these types to be a duplicate of an actual
6815    breakpoint location at address zero:
6816
6817       bp_watchpoint
6818       bp_catchpoint
6819
6820 */
6821
6822 static int
6823 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6824 {
6825   enum bptype type = bpt->type;
6826
6827   return (type != bp_watchpoint && type != bp_catchpoint);
6828 }
6829
6830 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6831    true if LOC1 and LOC2 represent the same watchpoint location.  */
6832
6833 static int
6834 watchpoint_locations_match (struct bp_location *loc1, 
6835                             struct bp_location *loc2)
6836 {
6837   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6838   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6839
6840   /* Both of them must exist.  */
6841   gdb_assert (w1 != NULL);
6842   gdb_assert (w2 != NULL);
6843
6844   /* If the target can evaluate the condition expression in hardware,
6845      then we we need to insert both watchpoints even if they are at
6846      the same place.  Otherwise the watchpoint will only trigger when
6847      the condition of whichever watchpoint was inserted evaluates to
6848      true, not giving a chance for GDB to check the condition of the
6849      other watchpoint.  */
6850   if ((w1->cond_exp
6851        && target_can_accel_watchpoint_condition (loc1->address, 
6852                                                  loc1->length,
6853                                                  loc1->watchpoint_type,
6854                                                  w1->cond_exp.get ()))
6855       || (w2->cond_exp
6856           && target_can_accel_watchpoint_condition (loc2->address, 
6857                                                     loc2->length,
6858                                                     loc2->watchpoint_type,
6859                                                     w2->cond_exp.get ())))
6860     return 0;
6861
6862   /* Note that this checks the owner's type, not the location's.  In
6863      case the target does not support read watchpoints, but does
6864      support access watchpoints, we'll have bp_read_watchpoint
6865      watchpoints with hw_access locations.  Those should be considered
6866      duplicates of hw_read locations.  The hw_read locations will
6867      become hw_access locations later.  */
6868   return (loc1->owner->type == loc2->owner->type
6869           && loc1->pspace->aspace == loc2->pspace->aspace
6870           && loc1->address == loc2->address
6871           && loc1->length == loc2->length);
6872 }
6873
6874 /* See breakpoint.h.  */
6875
6876 int
6877 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
6878                           const address_space *aspace2, CORE_ADDR addr2)
6879 {
6880   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6881            || aspace1 == aspace2)
6882           && addr1 == addr2);
6883 }
6884
6885 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6886    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6887    matches ASPACE2.  On targets that have global breakpoints, the address
6888    space doesn't really matter.  */
6889
6890 static int
6891 breakpoint_address_match_range (const address_space *aspace1,
6892                                 CORE_ADDR addr1,
6893                                 int len1, const address_space *aspace2,
6894                                 CORE_ADDR addr2)
6895 {
6896   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6897            || aspace1 == aspace2)
6898           && addr2 >= addr1 && addr2 < addr1 + len1);
6899 }
6900
6901 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6902    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6903    matches the breakpoint's address space.  On targets that have global
6904    breakpoints, the address space doesn't really matter.  */
6905
6906 static int
6907 breakpoint_location_address_match (struct bp_location *bl,
6908                                    const address_space *aspace,
6909                                    CORE_ADDR addr)
6910 {
6911   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6912                                     aspace, addr)
6913           || (bl->length
6914               && breakpoint_address_match_range (bl->pspace->aspace,
6915                                                  bl->address, bl->length,
6916                                                  aspace, addr)));
6917 }
6918
6919 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
6920    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
6921    match happens only if ASPACE matches the breakpoint's address
6922    space.  On targets that have global breakpoints, the address space
6923    doesn't really matter.  */
6924
6925 static int
6926 breakpoint_location_address_range_overlap (struct bp_location *bl,
6927                                            const address_space *aspace,
6928                                            CORE_ADDR addr, int len)
6929 {
6930   if (gdbarch_has_global_breakpoints (target_gdbarch ())
6931       || bl->pspace->aspace == aspace)
6932     {
6933       int bl_len = bl->length != 0 ? bl->length : 1;
6934
6935       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
6936         return 1;
6937     }
6938   return 0;
6939 }
6940
6941 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6942    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6943    true, otherwise returns false.  */
6944
6945 static int
6946 tracepoint_locations_match (struct bp_location *loc1,
6947                             struct bp_location *loc2)
6948 {
6949   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6950     /* Since tracepoint locations are never duplicated with others', tracepoint
6951        locations at the same address of different tracepoints are regarded as
6952        different locations.  */
6953     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6954   else
6955     return 0;
6956 }
6957
6958 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6959    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6960    represent the same location.  */
6961
6962 static int
6963 breakpoint_locations_match (struct bp_location *loc1, 
6964                             struct bp_location *loc2)
6965 {
6966   int hw_point1, hw_point2;
6967
6968   /* Both of them must not be in moribund_locations.  */
6969   gdb_assert (loc1->owner != NULL);
6970   gdb_assert (loc2->owner != NULL);
6971
6972   hw_point1 = is_hardware_watchpoint (loc1->owner);
6973   hw_point2 = is_hardware_watchpoint (loc2->owner);
6974
6975   if (hw_point1 != hw_point2)
6976     return 0;
6977   else if (hw_point1)
6978     return watchpoint_locations_match (loc1, loc2);
6979   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6980     return tracepoint_locations_match (loc1, loc2);
6981   else
6982     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6983     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6984                                      loc2->pspace->aspace, loc2->address)
6985             && loc1->length == loc2->length);
6986 }
6987
6988 static void
6989 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6990                                int bnum, int have_bnum)
6991 {
6992   /* The longest string possibly returned by hex_string_custom
6993      is 50 chars.  These must be at least that big for safety.  */
6994   char astr1[64];
6995   char astr2[64];
6996
6997   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6998   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6999   if (have_bnum)
7000     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7001              bnum, astr1, astr2);
7002   else
7003     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7004 }
7005
7006 /* Adjust a breakpoint's address to account for architectural
7007    constraints on breakpoint placement.  Return the adjusted address.
7008    Note: Very few targets require this kind of adjustment.  For most
7009    targets, this function is simply the identity function.  */
7010
7011 static CORE_ADDR
7012 adjust_breakpoint_address (struct gdbarch *gdbarch,
7013                            CORE_ADDR bpaddr, enum bptype bptype)
7014 {
7015   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7016     {
7017       /* Very few targets need any kind of breakpoint adjustment.  */
7018       return bpaddr;
7019     }
7020   else if (bptype == bp_watchpoint
7021            || bptype == bp_hardware_watchpoint
7022            || bptype == bp_read_watchpoint
7023            || bptype == bp_access_watchpoint
7024            || bptype == bp_catchpoint)
7025     {
7026       /* Watchpoints and the various bp_catch_* eventpoints should not
7027          have their addresses modified.  */
7028       return bpaddr;
7029     }
7030   else if (bptype == bp_single_step)
7031     {
7032       /* Single-step breakpoints should not have their addresses
7033          modified.  If there's any architectural constrain that
7034          applies to this address, then it should have already been
7035          taken into account when the breakpoint was created in the
7036          first place.  If we didn't do this, stepping through e.g.,
7037          Thumb-2 IT blocks would break.  */
7038       return bpaddr;
7039     }
7040   else
7041     {
7042       CORE_ADDR adjusted_bpaddr;
7043
7044       /* Some targets have architectural constraints on the placement
7045          of breakpoint instructions.  Obtain the adjusted address.  */
7046       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7047
7048       /* An adjusted breakpoint address can significantly alter
7049          a user's expectations.  Print a warning if an adjustment
7050          is required.  */
7051       if (adjusted_bpaddr != bpaddr)
7052         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7053
7054       return adjusted_bpaddr;
7055     }
7056 }
7057
7058 bp_location::bp_location (const bp_location_ops *ops, breakpoint *owner)
7059 {
7060   bp_location *loc = this;
7061
7062   gdb_assert (ops != NULL);
7063
7064   loc->ops = ops;
7065   loc->owner = owner;
7066   loc->cond_bytecode = NULL;
7067   loc->shlib_disabled = 0;
7068   loc->enabled = 1;
7069
7070   switch (owner->type)
7071     {
7072     case bp_breakpoint:
7073     case bp_single_step:
7074     case bp_until:
7075     case bp_finish:
7076     case bp_longjmp:
7077     case bp_longjmp_resume:
7078     case bp_longjmp_call_dummy:
7079     case bp_exception:
7080     case bp_exception_resume:
7081     case bp_step_resume:
7082     case bp_hp_step_resume:
7083     case bp_watchpoint_scope:
7084     case bp_call_dummy:
7085     case bp_std_terminate:
7086     case bp_shlib_event:
7087     case bp_thread_event:
7088     case bp_overlay_event:
7089     case bp_jit_event:
7090     case bp_longjmp_master:
7091     case bp_std_terminate_master:
7092     case bp_exception_master:
7093     case bp_gnu_ifunc_resolver:
7094     case bp_gnu_ifunc_resolver_return:
7095     case bp_dprintf:
7096       loc->loc_type = bp_loc_software_breakpoint;
7097       mark_breakpoint_location_modified (loc);
7098       break;
7099     case bp_hardware_breakpoint:
7100       loc->loc_type = bp_loc_hardware_breakpoint;
7101       mark_breakpoint_location_modified (loc);
7102       break;
7103     case bp_hardware_watchpoint:
7104     case bp_read_watchpoint:
7105     case bp_access_watchpoint:
7106       loc->loc_type = bp_loc_hardware_watchpoint;
7107       break;
7108     case bp_watchpoint:
7109     case bp_catchpoint:
7110     case bp_tracepoint:
7111     case bp_fast_tracepoint:
7112     case bp_static_tracepoint:
7113       loc->loc_type = bp_loc_other;
7114       break;
7115     default:
7116       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7117     }
7118
7119   loc->refc = 1;
7120 }
7121
7122 /* Allocate a struct bp_location.  */
7123
7124 static struct bp_location *
7125 allocate_bp_location (struct breakpoint *bpt)
7126 {
7127   return bpt->ops->allocate_location (bpt);
7128 }
7129
7130 static void
7131 free_bp_location (struct bp_location *loc)
7132 {
7133   loc->ops->dtor (loc);
7134   delete loc;
7135 }
7136
7137 /* Increment reference count.  */
7138
7139 static void
7140 incref_bp_location (struct bp_location *bl)
7141 {
7142   ++bl->refc;
7143 }
7144
7145 /* Decrement reference count.  If the reference count reaches 0,
7146    destroy the bp_location.  Sets *BLP to NULL.  */
7147
7148 static void
7149 decref_bp_location (struct bp_location **blp)
7150 {
7151   gdb_assert ((*blp)->refc > 0);
7152
7153   if (--(*blp)->refc == 0)
7154     free_bp_location (*blp);
7155   *blp = NULL;
7156 }
7157
7158 /* Add breakpoint B at the end of the global breakpoint chain.  */
7159
7160 static breakpoint *
7161 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7162 {
7163   struct breakpoint *b1;
7164   struct breakpoint *result = b.get ();
7165
7166   /* Add this breakpoint to the end of the chain so that a list of
7167      breakpoints will come out in order of increasing numbers.  */
7168
7169   b1 = breakpoint_chain;
7170   if (b1 == 0)
7171     breakpoint_chain = b.release ();
7172   else
7173     {
7174       while (b1->next)
7175         b1 = b1->next;
7176       b1->next = b.release ();
7177     }
7178
7179   return result;
7180 }
7181
7182 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7183
7184 static void
7185 init_raw_breakpoint_without_location (struct breakpoint *b,
7186                                       struct gdbarch *gdbarch,
7187                                       enum bptype bptype,
7188                                       const struct breakpoint_ops *ops)
7189 {
7190   gdb_assert (ops != NULL);
7191
7192   b->ops = ops;
7193   b->type = bptype;
7194   b->gdbarch = gdbarch;
7195   b->language = current_language->la_language;
7196   b->input_radix = input_radix;
7197   b->related_breakpoint = b;
7198 }
7199
7200 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7201    that has type BPTYPE and has no locations as yet.  */
7202
7203 static struct breakpoint *
7204 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7205                                      enum bptype bptype,
7206                                      const struct breakpoint_ops *ops)
7207 {
7208   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7209
7210   init_raw_breakpoint_without_location (b.get (), gdbarch, bptype, ops);
7211   return add_to_breakpoint_chain (std::move (b));
7212 }
7213
7214 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7215    resolutions should be made as the user specified the location explicitly
7216    enough.  */
7217
7218 static void
7219 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7220 {
7221   gdb_assert (loc->owner != NULL);
7222
7223   if (loc->owner->type == bp_breakpoint
7224       || loc->owner->type == bp_hardware_breakpoint
7225       || is_tracepoint (loc->owner))
7226     {
7227       int is_gnu_ifunc;
7228       const char *function_name;
7229       CORE_ADDR func_addr;
7230
7231       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7232                                           &func_addr, NULL, &is_gnu_ifunc);
7233
7234       if (is_gnu_ifunc && !explicit_loc)
7235         {
7236           struct breakpoint *b = loc->owner;
7237
7238           gdb_assert (loc->pspace == current_program_space);
7239           if (gnu_ifunc_resolve_name (function_name,
7240                                       &loc->requested_address))
7241             {
7242               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7243               loc->address = adjust_breakpoint_address (loc->gdbarch,
7244                                                         loc->requested_address,
7245                                                         b->type);
7246             }
7247           else if (b->type == bp_breakpoint && b->loc == loc
7248                    && loc->next == NULL && b->related_breakpoint == b)
7249             {
7250               /* Create only the whole new breakpoint of this type but do not
7251                  mess more complicated breakpoints with multiple locations.  */
7252               b->type = bp_gnu_ifunc_resolver;
7253               /* Remember the resolver's address for use by the return
7254                  breakpoint.  */
7255               loc->related_address = func_addr;
7256             }
7257         }
7258
7259       if (function_name)
7260         loc->function_name = xstrdup (function_name);
7261     }
7262 }
7263
7264 /* Attempt to determine architecture of location identified by SAL.  */
7265 struct gdbarch *
7266 get_sal_arch (struct symtab_and_line sal)
7267 {
7268   if (sal.section)
7269     return get_objfile_arch (sal.section->objfile);
7270   if (sal.symtab)
7271     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7272
7273   return NULL;
7274 }
7275
7276 /* Low level routine for partially initializing a breakpoint of type
7277    BPTYPE.  The newly created breakpoint's address, section, source
7278    file name, and line number are provided by SAL.
7279
7280    It is expected that the caller will complete the initialization of
7281    the newly created breakpoint struct as well as output any status
7282    information regarding the creation of a new breakpoint.  */
7283
7284 static void
7285 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7286                      struct symtab_and_line sal, enum bptype bptype,
7287                      const struct breakpoint_ops *ops)
7288 {
7289   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7290
7291   add_location_to_breakpoint (b, &sal);
7292
7293   if (bptype != bp_catchpoint)
7294     gdb_assert (sal.pspace != NULL);
7295
7296   /* Store the program space that was used to set the breakpoint,
7297      except for ordinary breakpoints, which are independent of the
7298      program space.  */
7299   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7300     b->pspace = sal.pspace;
7301 }
7302
7303 /* set_raw_breakpoint is a low level routine for allocating and
7304    partially initializing a breakpoint of type BPTYPE.  The newly
7305    created breakpoint's address, section, source file name, and line
7306    number are provided by SAL.  The newly created and partially
7307    initialized breakpoint is added to the breakpoint chain and
7308    is also returned as the value of this function.
7309
7310    It is expected that the caller will complete the initialization of
7311    the newly created breakpoint struct as well as output any status
7312    information regarding the creation of a new breakpoint.  In
7313    particular, set_raw_breakpoint does NOT set the breakpoint
7314    number!  Care should be taken to not allow an error to occur
7315    prior to completing the initialization of the breakpoint.  If this
7316    should happen, a bogus breakpoint will be left on the chain.  */
7317
7318 struct breakpoint *
7319 set_raw_breakpoint (struct gdbarch *gdbarch,
7320                     struct symtab_and_line sal, enum bptype bptype,
7321                     const struct breakpoint_ops *ops)
7322 {
7323   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7324
7325   init_raw_breakpoint (b.get (), gdbarch, sal, bptype, ops);
7326   return add_to_breakpoint_chain (std::move (b));
7327 }
7328
7329 /* Call this routine when stepping and nexting to enable a breakpoint
7330    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7331    initiated the operation.  */
7332
7333 void
7334 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7335 {
7336   struct breakpoint *b, *b_tmp;
7337   int thread = tp->global_num;
7338
7339   /* To avoid having to rescan all objfile symbols at every step,
7340      we maintain a list of continually-inserted but always disabled
7341      longjmp "master" breakpoints.  Here, we simply create momentary
7342      clones of those and enable them for the requested thread.  */
7343   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7344     if (b->pspace == current_program_space
7345         && (b->type == bp_longjmp_master
7346             || b->type == bp_exception_master))
7347       {
7348         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7349         struct breakpoint *clone;
7350
7351         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7352            after their removal.  */
7353         clone = momentary_breakpoint_from_master (b, type,
7354                                                   &momentary_breakpoint_ops, 1);
7355         clone->thread = thread;
7356       }
7357
7358   tp->initiating_frame = frame;
7359 }
7360
7361 /* Delete all longjmp breakpoints from THREAD.  */
7362 void
7363 delete_longjmp_breakpoint (int thread)
7364 {
7365   struct breakpoint *b, *b_tmp;
7366
7367   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7368     if (b->type == bp_longjmp || b->type == bp_exception)
7369       {
7370         if (b->thread == thread)
7371           delete_breakpoint (b);
7372       }
7373 }
7374
7375 void
7376 delete_longjmp_breakpoint_at_next_stop (int thread)
7377 {
7378   struct breakpoint *b, *b_tmp;
7379
7380   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7381     if (b->type == bp_longjmp || b->type == bp_exception)
7382       {
7383         if (b->thread == thread)
7384           b->disposition = disp_del_at_next_stop;
7385       }
7386 }
7387
7388 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7389    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7390    pointer to any of them.  Return NULL if this system cannot place longjmp
7391    breakpoints.  */
7392
7393 struct breakpoint *
7394 set_longjmp_breakpoint_for_call_dummy (void)
7395 {
7396   struct breakpoint *b, *retval = NULL;
7397
7398   ALL_BREAKPOINTS (b)
7399     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7400       {
7401         struct breakpoint *new_b;
7402
7403         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7404                                                   &momentary_breakpoint_ops,
7405                                                   1);
7406         new_b->thread = ptid_to_global_thread_id (inferior_ptid);
7407
7408         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7409
7410         gdb_assert (new_b->related_breakpoint == new_b);
7411         if (retval == NULL)
7412           retval = new_b;
7413         new_b->related_breakpoint = retval;
7414         while (retval->related_breakpoint != new_b->related_breakpoint)
7415           retval = retval->related_breakpoint;
7416         retval->related_breakpoint = new_b;
7417       }
7418
7419   return retval;
7420 }
7421
7422 /* Verify all existing dummy frames and their associated breakpoints for
7423    TP.  Remove those which can no longer be found in the current frame
7424    stack.
7425
7426    You should call this function only at places where it is safe to currently
7427    unwind the whole stack.  Failed stack unwind would discard live dummy
7428    frames.  */
7429
7430 void
7431 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7432 {
7433   struct breakpoint *b, *b_tmp;
7434
7435   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7436     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7437       {
7438         struct breakpoint *dummy_b = b->related_breakpoint;
7439
7440         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7441           dummy_b = dummy_b->related_breakpoint;
7442         if (dummy_b->type != bp_call_dummy
7443             || frame_find_by_id (dummy_b->frame_id) != NULL)
7444           continue;
7445         
7446         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7447
7448         while (b->related_breakpoint != b)
7449           {
7450             if (b_tmp == b->related_breakpoint)
7451               b_tmp = b->related_breakpoint->next;
7452             delete_breakpoint (b->related_breakpoint);
7453           }
7454         delete_breakpoint (b);
7455       }
7456 }
7457
7458 void
7459 enable_overlay_breakpoints (void)
7460 {
7461   struct breakpoint *b;
7462
7463   ALL_BREAKPOINTS (b)
7464     if (b->type == bp_overlay_event)
7465     {
7466       b->enable_state = bp_enabled;
7467       update_global_location_list (UGLL_MAY_INSERT);
7468       overlay_events_enabled = 1;
7469     }
7470 }
7471
7472 void
7473 disable_overlay_breakpoints (void)
7474 {
7475   struct breakpoint *b;
7476
7477   ALL_BREAKPOINTS (b)
7478     if (b->type == bp_overlay_event)
7479     {
7480       b->enable_state = bp_disabled;
7481       update_global_location_list (UGLL_DONT_INSERT);
7482       overlay_events_enabled = 0;
7483     }
7484 }
7485
7486 /* Set an active std::terminate breakpoint for each std::terminate
7487    master breakpoint.  */
7488 void
7489 set_std_terminate_breakpoint (void)
7490 {
7491   struct breakpoint *b, *b_tmp;
7492
7493   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7494     if (b->pspace == current_program_space
7495         && b->type == bp_std_terminate_master)
7496       {
7497         momentary_breakpoint_from_master (b, bp_std_terminate,
7498                                           &momentary_breakpoint_ops, 1);
7499       }
7500 }
7501
7502 /* Delete all the std::terminate breakpoints.  */
7503 void
7504 delete_std_terminate_breakpoint (void)
7505 {
7506   struct breakpoint *b, *b_tmp;
7507
7508   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7509     if (b->type == bp_std_terminate)
7510       delete_breakpoint (b);
7511 }
7512
7513 struct breakpoint *
7514 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7515 {
7516   struct breakpoint *b;
7517
7518   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7519                                   &internal_breakpoint_ops);
7520
7521   b->enable_state = bp_enabled;
7522   /* location has to be used or breakpoint_re_set will delete me.  */
7523   b->location = new_address_location (b->loc->address, NULL, 0);
7524
7525   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7526
7527   return b;
7528 }
7529
7530 struct lang_and_radix
7531   {
7532     enum language lang;
7533     int radix;
7534   };
7535
7536 /* Create a breakpoint for JIT code registration and unregistration.  */
7537
7538 struct breakpoint *
7539 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7540 {
7541   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7542                                      &internal_breakpoint_ops);
7543 }
7544
7545 /* Remove JIT code registration and unregistration breakpoint(s).  */
7546
7547 void
7548 remove_jit_event_breakpoints (void)
7549 {
7550   struct breakpoint *b, *b_tmp;
7551
7552   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7553     if (b->type == bp_jit_event
7554         && b->loc->pspace == current_program_space)
7555       delete_breakpoint (b);
7556 }
7557
7558 void
7559 remove_solib_event_breakpoints (void)
7560 {
7561   struct breakpoint *b, *b_tmp;
7562
7563   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7564     if (b->type == bp_shlib_event
7565         && b->loc->pspace == current_program_space)
7566       delete_breakpoint (b);
7567 }
7568
7569 /* See breakpoint.h.  */
7570
7571 void
7572 remove_solib_event_breakpoints_at_next_stop (void)
7573 {
7574   struct breakpoint *b, *b_tmp;
7575
7576   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7577     if (b->type == bp_shlib_event
7578         && b->loc->pspace == current_program_space)
7579       b->disposition = disp_del_at_next_stop;
7580 }
7581
7582 /* Helper for create_solib_event_breakpoint /
7583    create_and_insert_solib_event_breakpoint.  Allows specifying which
7584    INSERT_MODE to pass through to update_global_location_list.  */
7585
7586 static struct breakpoint *
7587 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7588                                  enum ugll_insert_mode insert_mode)
7589 {
7590   struct breakpoint *b;
7591
7592   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7593                                   &internal_breakpoint_ops);
7594   update_global_location_list_nothrow (insert_mode);
7595   return b;
7596 }
7597
7598 struct breakpoint *
7599 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7600 {
7601   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7602 }
7603
7604 /* See breakpoint.h.  */
7605
7606 struct breakpoint *
7607 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7608 {
7609   struct breakpoint *b;
7610
7611   /* Explicitly tell update_global_location_list to insert
7612      locations.  */
7613   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7614   if (!b->loc->inserted)
7615     {
7616       delete_breakpoint (b);
7617       return NULL;
7618     }
7619   return b;
7620 }
7621
7622 /* Disable any breakpoints that are on code in shared libraries.  Only
7623    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7624
7625 void
7626 disable_breakpoints_in_shlibs (void)
7627 {
7628   struct bp_location *loc, **locp_tmp;
7629
7630   ALL_BP_LOCATIONS (loc, locp_tmp)
7631   {
7632     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7633     struct breakpoint *b = loc->owner;
7634
7635     /* We apply the check to all breakpoints, including disabled for
7636        those with loc->duplicate set.  This is so that when breakpoint
7637        becomes enabled, or the duplicate is removed, gdb will try to
7638        insert all breakpoints.  If we don't set shlib_disabled here,
7639        we'll try to insert those breakpoints and fail.  */
7640     if (((b->type == bp_breakpoint)
7641          || (b->type == bp_jit_event)
7642          || (b->type == bp_hardware_breakpoint)
7643          || (is_tracepoint (b)))
7644         && loc->pspace == current_program_space
7645         && !loc->shlib_disabled
7646         && solib_name_from_address (loc->pspace, loc->address)
7647         )
7648       {
7649         loc->shlib_disabled = 1;
7650       }
7651   }
7652 }
7653
7654 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7655    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7656    disabled ones can just stay disabled.  */
7657
7658 static void
7659 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7660 {
7661   struct bp_location *loc, **locp_tmp;
7662   int disabled_shlib_breaks = 0;
7663
7664   ALL_BP_LOCATIONS (loc, locp_tmp)
7665   {
7666     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7667     struct breakpoint *b = loc->owner;
7668
7669     if (solib->pspace == loc->pspace
7670         && !loc->shlib_disabled
7671         && (((b->type == bp_breakpoint
7672               || b->type == bp_jit_event
7673               || b->type == bp_hardware_breakpoint)
7674              && (loc->loc_type == bp_loc_hardware_breakpoint
7675                  || loc->loc_type == bp_loc_software_breakpoint))
7676             || is_tracepoint (b))
7677         && solib_contains_address_p (solib, loc->address))
7678       {
7679         loc->shlib_disabled = 1;
7680         /* At this point, we cannot rely on remove_breakpoint
7681            succeeding so we must mark the breakpoint as not inserted
7682            to prevent future errors occurring in remove_breakpoints.  */
7683         loc->inserted = 0;
7684
7685         /* This may cause duplicate notifications for the same breakpoint.  */
7686         observer_notify_breakpoint_modified (b);
7687
7688         if (!disabled_shlib_breaks)
7689           {
7690             target_terminal::ours_for_output ();
7691             warning (_("Temporarily disabling breakpoints "
7692                        "for unloaded shared library \"%s\""),
7693                      solib->so_name);
7694           }
7695         disabled_shlib_breaks = 1;
7696       }
7697   }
7698 }
7699
7700 /* Disable any breakpoints and tracepoints in OBJFILE upon
7701    notification of free_objfile.  Only apply to enabled breakpoints,
7702    disabled ones can just stay disabled.  */
7703
7704 static void
7705 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7706 {
7707   struct breakpoint *b;
7708
7709   if (objfile == NULL)
7710     return;
7711
7712   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7713      managed by the user with add-symbol-file/remove-symbol-file.
7714      Similarly to how breakpoints in shared libraries are handled in
7715      response to "nosharedlibrary", mark breakpoints in such modules
7716      shlib_disabled so they end up uninserted on the next global
7717      location list update.  Shared libraries not loaded by the user
7718      aren't handled here -- they're already handled in
7719      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7720      solib_unloaded observer.  We skip objfiles that are not
7721      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7722      main objfile).  */
7723   if ((objfile->flags & OBJF_SHARED) == 0
7724       || (objfile->flags & OBJF_USERLOADED) == 0)
7725     return;
7726
7727   ALL_BREAKPOINTS (b)
7728     {
7729       struct bp_location *loc;
7730       int bp_modified = 0;
7731
7732       if (!is_breakpoint (b) && !is_tracepoint (b))
7733         continue;
7734
7735       for (loc = b->loc; loc != NULL; loc = loc->next)
7736         {
7737           CORE_ADDR loc_addr = loc->address;
7738
7739           if (loc->loc_type != bp_loc_hardware_breakpoint
7740               && loc->loc_type != bp_loc_software_breakpoint)
7741             continue;
7742
7743           if (loc->shlib_disabled != 0)
7744             continue;
7745
7746           if (objfile->pspace != loc->pspace)
7747             continue;
7748
7749           if (loc->loc_type != bp_loc_hardware_breakpoint
7750               && loc->loc_type != bp_loc_software_breakpoint)
7751             continue;
7752
7753           if (is_addr_in_objfile (loc_addr, objfile))
7754             {
7755               loc->shlib_disabled = 1;
7756               /* At this point, we don't know whether the object was
7757                  unmapped from the inferior or not, so leave the
7758                  inserted flag alone.  We'll handle failure to
7759                  uninsert quietly, in case the object was indeed
7760                  unmapped.  */
7761
7762               mark_breakpoint_location_modified (loc);
7763
7764               bp_modified = 1;
7765             }
7766         }
7767
7768       if (bp_modified)
7769         observer_notify_breakpoint_modified (b);
7770     }
7771 }
7772
7773 /* FORK & VFORK catchpoints.  */
7774
7775 /* An instance of this type is used to represent a fork or vfork
7776    catchpoint.  A breakpoint is really of this type iff its ops pointer points
7777    to CATCH_FORK_BREAKPOINT_OPS.  */
7778
7779 struct fork_catchpoint : public breakpoint
7780 {
7781   /* Process id of a child process whose forking triggered this
7782      catchpoint.  This field is only valid immediately after this
7783      catchpoint has triggered.  */
7784   ptid_t forked_inferior_pid;
7785 };
7786
7787 /* Implement the "insert" breakpoint_ops method for fork
7788    catchpoints.  */
7789
7790 static int
7791 insert_catch_fork (struct bp_location *bl)
7792 {
7793   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7794 }
7795
7796 /* Implement the "remove" breakpoint_ops method for fork
7797    catchpoints.  */
7798
7799 static int
7800 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
7801 {
7802   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7803 }
7804
7805 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7806    catchpoints.  */
7807
7808 static int
7809 breakpoint_hit_catch_fork (const struct bp_location *bl,
7810                            const address_space *aspace, CORE_ADDR bp_addr,
7811                            const struct target_waitstatus *ws)
7812 {
7813   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7814
7815   if (ws->kind != TARGET_WAITKIND_FORKED)
7816     return 0;
7817
7818   c->forked_inferior_pid = ws->value.related_pid;
7819   return 1;
7820 }
7821
7822 /* Implement the "print_it" breakpoint_ops method for fork
7823    catchpoints.  */
7824
7825 static enum print_stop_action
7826 print_it_catch_fork (bpstat bs)
7827 {
7828   struct ui_out *uiout = current_uiout;
7829   struct breakpoint *b = bs->breakpoint_at;
7830   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7831
7832   annotate_catchpoint (b->number);
7833   maybe_print_thread_hit_breakpoint (uiout);
7834   if (b->disposition == disp_del)
7835     uiout->text ("Temporary catchpoint ");
7836   else
7837     uiout->text ("Catchpoint ");
7838   if (uiout->is_mi_like_p ())
7839     {
7840       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
7841       uiout->field_string ("disp", bpdisp_text (b->disposition));
7842     }
7843   uiout->field_int ("bkptno", b->number);
7844   uiout->text (" (forked process ");
7845   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
7846   uiout->text ("), ");
7847   return PRINT_SRC_AND_LOC;
7848 }
7849
7850 /* Implement the "print_one" breakpoint_ops method for fork
7851    catchpoints.  */
7852
7853 static void
7854 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7855 {
7856   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7857   struct value_print_options opts;
7858   struct ui_out *uiout = current_uiout;
7859
7860   get_user_print_options (&opts);
7861
7862   /* Field 4, the address, is omitted (which makes the columns not
7863      line up too nicely with the headers, but the effect is relatively
7864      readable).  */
7865   if (opts.addressprint)
7866     uiout->field_skip ("addr");
7867   annotate_field (5);
7868   uiout->text ("fork");
7869   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7870     {
7871       uiout->text (", process ");
7872       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
7873       uiout->spaces (1);
7874     }
7875
7876   if (uiout->is_mi_like_p ())
7877     uiout->field_string ("catch-type", "fork");
7878 }
7879
7880 /* Implement the "print_mention" breakpoint_ops method for fork
7881    catchpoints.  */
7882
7883 static void
7884 print_mention_catch_fork (struct breakpoint *b)
7885 {
7886   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7887 }
7888
7889 /* Implement the "print_recreate" breakpoint_ops method for fork
7890    catchpoints.  */
7891
7892 static void
7893 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7894 {
7895   fprintf_unfiltered (fp, "catch fork");
7896   print_recreate_thread (b, fp);
7897 }
7898
7899 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7900
7901 static struct breakpoint_ops catch_fork_breakpoint_ops;
7902
7903 /* Implement the "insert" breakpoint_ops method for vfork
7904    catchpoints.  */
7905
7906 static int
7907 insert_catch_vfork (struct bp_location *bl)
7908 {
7909   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7910 }
7911
7912 /* Implement the "remove" breakpoint_ops method for vfork
7913    catchpoints.  */
7914
7915 static int
7916 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
7917 {
7918   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7919 }
7920
7921 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7922    catchpoints.  */
7923
7924 static int
7925 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7926                             const address_space *aspace, CORE_ADDR bp_addr,
7927                             const struct target_waitstatus *ws)
7928 {
7929   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7930
7931   if (ws->kind != TARGET_WAITKIND_VFORKED)
7932     return 0;
7933
7934   c->forked_inferior_pid = ws->value.related_pid;
7935   return 1;
7936 }
7937
7938 /* Implement the "print_it" breakpoint_ops method for vfork
7939    catchpoints.  */
7940
7941 static enum print_stop_action
7942 print_it_catch_vfork (bpstat bs)
7943 {
7944   struct ui_out *uiout = current_uiout;
7945   struct breakpoint *b = bs->breakpoint_at;
7946   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7947
7948   annotate_catchpoint (b->number);
7949   maybe_print_thread_hit_breakpoint (uiout);
7950   if (b->disposition == disp_del)
7951     uiout->text ("Temporary catchpoint ");
7952   else
7953     uiout->text ("Catchpoint ");
7954   if (uiout->is_mi_like_p ())
7955     {
7956       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
7957       uiout->field_string ("disp", bpdisp_text (b->disposition));
7958     }
7959   uiout->field_int ("bkptno", b->number);
7960   uiout->text (" (vforked process ");
7961   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
7962   uiout->text ("), ");
7963   return PRINT_SRC_AND_LOC;
7964 }
7965
7966 /* Implement the "print_one" breakpoint_ops method for vfork
7967    catchpoints.  */
7968
7969 static void
7970 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7971 {
7972   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7973   struct value_print_options opts;
7974   struct ui_out *uiout = current_uiout;
7975
7976   get_user_print_options (&opts);
7977   /* Field 4, the address, is omitted (which makes the columns not
7978      line up too nicely with the headers, but the effect is relatively
7979      readable).  */
7980   if (opts.addressprint)
7981     uiout->field_skip ("addr");
7982   annotate_field (5);
7983   uiout->text ("vfork");
7984   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7985     {
7986       uiout->text (", process ");
7987       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
7988       uiout->spaces (1);
7989     }
7990
7991   if (uiout->is_mi_like_p ())
7992     uiout->field_string ("catch-type", "vfork");
7993 }
7994
7995 /* Implement the "print_mention" breakpoint_ops method for vfork
7996    catchpoints.  */
7997
7998 static void
7999 print_mention_catch_vfork (struct breakpoint *b)
8000 {
8001   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8002 }
8003
8004 /* Implement the "print_recreate" breakpoint_ops method for vfork
8005    catchpoints.  */
8006
8007 static void
8008 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8009 {
8010   fprintf_unfiltered (fp, "catch vfork");
8011   print_recreate_thread (b, fp);
8012 }
8013
8014 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8015
8016 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8017
8018 /* An instance of this type is used to represent an solib catchpoint.
8019    A breakpoint is really of this type iff its ops pointer points to
8020    CATCH_SOLIB_BREAKPOINT_OPS.  */
8021
8022 struct solib_catchpoint : public breakpoint
8023 {
8024   ~solib_catchpoint () override;
8025
8026   /* True for "catch load", false for "catch unload".  */
8027   unsigned char is_load;
8028
8029   /* Regular expression to match, if any.  COMPILED is only valid when
8030      REGEX is non-NULL.  */
8031   char *regex;
8032   std::unique_ptr<compiled_regex> compiled;
8033 };
8034
8035 solib_catchpoint::~solib_catchpoint ()
8036 {
8037   xfree (this->regex);
8038 }
8039
8040 static int
8041 insert_catch_solib (struct bp_location *ignore)
8042 {
8043   return 0;
8044 }
8045
8046 static int
8047 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
8048 {
8049   return 0;
8050 }
8051
8052 static int
8053 breakpoint_hit_catch_solib (const struct bp_location *bl,
8054                             const address_space *aspace,
8055                             CORE_ADDR bp_addr,
8056                             const struct target_waitstatus *ws)
8057 {
8058   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8059   struct breakpoint *other;
8060
8061   if (ws->kind == TARGET_WAITKIND_LOADED)
8062     return 1;
8063
8064   ALL_BREAKPOINTS (other)
8065   {
8066     struct bp_location *other_bl;
8067
8068     if (other == bl->owner)
8069       continue;
8070
8071     if (other->type != bp_shlib_event)
8072       continue;
8073
8074     if (self->pspace != NULL && other->pspace != self->pspace)
8075       continue;
8076
8077     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8078       {
8079         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8080           return 1;
8081       }
8082   }
8083
8084   return 0;
8085 }
8086
8087 static void
8088 check_status_catch_solib (struct bpstats *bs)
8089 {
8090   struct solib_catchpoint *self
8091     = (struct solib_catchpoint *) bs->breakpoint_at;
8092   int ix;
8093
8094   if (self->is_load)
8095     {
8096       struct so_list *iter;
8097
8098       for (ix = 0;
8099            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8100                         ix, iter);
8101            ++ix)
8102         {
8103           if (!self->regex
8104               || self->compiled->exec (iter->so_name, 0, NULL, 0) == 0)
8105             return;
8106         }
8107     }
8108   else
8109     {
8110       char *iter;
8111
8112       for (ix = 0;
8113            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8114                         ix, iter);
8115            ++ix)
8116         {
8117           if (!self->regex
8118               || self->compiled->exec (iter, 0, NULL, 0) == 0)
8119             return;
8120         }
8121     }
8122
8123   bs->stop = 0;
8124   bs->print_it = print_it_noop;
8125 }
8126
8127 static enum print_stop_action
8128 print_it_catch_solib (bpstat bs)
8129 {
8130   struct breakpoint *b = bs->breakpoint_at;
8131   struct ui_out *uiout = current_uiout;
8132
8133   annotate_catchpoint (b->number);
8134   maybe_print_thread_hit_breakpoint (uiout);
8135   if (b->disposition == disp_del)
8136     uiout->text ("Temporary catchpoint ");
8137   else
8138     uiout->text ("Catchpoint ");
8139   uiout->field_int ("bkptno", b->number);
8140   uiout->text ("\n");
8141   if (uiout->is_mi_like_p ())
8142     uiout->field_string ("disp", bpdisp_text (b->disposition));
8143   print_solib_event (1);
8144   return PRINT_SRC_AND_LOC;
8145 }
8146
8147 static void
8148 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8149 {
8150   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8151   struct value_print_options opts;
8152   struct ui_out *uiout = current_uiout;
8153   char *msg;
8154
8155   get_user_print_options (&opts);
8156   /* Field 4, the address, is omitted (which makes the columns not
8157      line up too nicely with the headers, but the effect is relatively
8158      readable).  */
8159   if (opts.addressprint)
8160     {
8161       annotate_field (4);
8162       uiout->field_skip ("addr");
8163     }
8164
8165   annotate_field (5);
8166   if (self->is_load)
8167     {
8168       if (self->regex)
8169         msg = xstrprintf (_("load of library matching %s"), self->regex);
8170       else
8171         msg = xstrdup (_("load of library"));
8172     }
8173   else
8174     {
8175       if (self->regex)
8176         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8177       else
8178         msg = xstrdup (_("unload of library"));
8179     }
8180   uiout->field_string ("what", msg);
8181   xfree (msg);
8182
8183   if (uiout->is_mi_like_p ())
8184     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8185 }
8186
8187 static void
8188 print_mention_catch_solib (struct breakpoint *b)
8189 {
8190   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8191
8192   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8193                    self->is_load ? "load" : "unload");
8194 }
8195
8196 static void
8197 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8198 {
8199   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8200
8201   fprintf_unfiltered (fp, "%s %s",
8202                       b->disposition == disp_del ? "tcatch" : "catch",
8203                       self->is_load ? "load" : "unload");
8204   if (self->regex)
8205     fprintf_unfiltered (fp, " %s", self->regex);
8206   fprintf_unfiltered (fp, "\n");
8207 }
8208
8209 static struct breakpoint_ops catch_solib_breakpoint_ops;
8210
8211 /* Shared helper function (MI and CLI) for creating and installing
8212    a shared object event catchpoint.  If IS_LOAD is non-zero then
8213    the events to be caught are load events, otherwise they are
8214    unload events.  If IS_TEMP is non-zero the catchpoint is a
8215    temporary one.  If ENABLED is non-zero the catchpoint is
8216    created in an enabled state.  */
8217
8218 void
8219 add_solib_catchpoint (const char *arg, int is_load, int is_temp, int enabled)
8220 {
8221   struct gdbarch *gdbarch = get_current_arch ();
8222
8223   if (!arg)
8224     arg = "";
8225   arg = skip_spaces (arg);
8226
8227   std::unique_ptr<solib_catchpoint> c (new solib_catchpoint ());
8228
8229   if (*arg != '\0')
8230     {
8231       c->compiled.reset (new compiled_regex (arg, REG_NOSUB,
8232                                              _("Invalid regexp")));
8233       c->regex = xstrdup (arg);
8234     }
8235
8236   c->is_load = is_load;
8237   init_catchpoint (c.get (), gdbarch, is_temp, NULL,
8238                    &catch_solib_breakpoint_ops);
8239
8240   c->enable_state = enabled ? bp_enabled : bp_disabled;
8241
8242   install_breakpoint (0, std::move (c), 1);
8243 }
8244
8245 /* A helper function that does all the work for "catch load" and
8246    "catch unload".  */
8247
8248 static void
8249 catch_load_or_unload (char *arg, int from_tty, int is_load,
8250                       struct cmd_list_element *command)
8251 {
8252   int tempflag;
8253   const int enabled = 1;
8254
8255   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8256
8257   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8258 }
8259
8260 static void
8261 catch_load_command_1 (char *arg, int from_tty,
8262                       struct cmd_list_element *command)
8263 {
8264   catch_load_or_unload (arg, from_tty, 1, command);
8265 }
8266
8267 static void
8268 catch_unload_command_1 (char *arg, int from_tty,
8269                         struct cmd_list_element *command)
8270 {
8271   catch_load_or_unload (arg, from_tty, 0, command);
8272 }
8273
8274 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8275    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8276    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8277    the breakpoint_ops structure associated to the catchpoint.  */
8278
8279 void
8280 init_catchpoint (struct breakpoint *b,
8281                  struct gdbarch *gdbarch, int tempflag,
8282                  const char *cond_string,
8283                  const struct breakpoint_ops *ops)
8284 {
8285   symtab_and_line sal;
8286   sal.pspace = current_program_space;
8287
8288   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8289
8290   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8291   b->disposition = tempflag ? disp_del : disp_donttouch;
8292 }
8293
8294 void
8295 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8296 {
8297   breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8298   set_breakpoint_number (internal, b);
8299   if (is_tracepoint (b))
8300     set_tracepoint_count (breakpoint_count);
8301   if (!internal)
8302     mention (b);
8303   observer_notify_breakpoint_created (b);
8304
8305   if (update_gll)
8306     update_global_location_list (UGLL_MAY_INSERT);
8307 }
8308
8309 static void
8310 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8311                                     int tempflag, const char *cond_string,
8312                                     const struct breakpoint_ops *ops)
8313 {
8314   std::unique_ptr<fork_catchpoint> c (new fork_catchpoint ());
8315
8316   init_catchpoint (c.get (), gdbarch, tempflag, cond_string, ops);
8317
8318   c->forked_inferior_pid = null_ptid;
8319
8320   install_breakpoint (0, std::move (c), 1);
8321 }
8322
8323 /* Exec catchpoints.  */
8324
8325 /* An instance of this type is used to represent an exec catchpoint.
8326    A breakpoint is really of this type iff its ops pointer points to
8327    CATCH_EXEC_BREAKPOINT_OPS.  */
8328
8329 struct exec_catchpoint : public breakpoint
8330 {
8331   ~exec_catchpoint () override;
8332
8333   /* Filename of a program whose exec triggered this catchpoint.
8334      This field is only valid immediately after this catchpoint has
8335      triggered.  */
8336   char *exec_pathname;
8337 };
8338
8339 /* Exec catchpoint destructor.  */
8340
8341 exec_catchpoint::~exec_catchpoint ()
8342 {
8343   xfree (this->exec_pathname);
8344 }
8345
8346 static int
8347 insert_catch_exec (struct bp_location *bl)
8348 {
8349   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8350 }
8351
8352 static int
8353 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8354 {
8355   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8356 }
8357
8358 static int
8359 breakpoint_hit_catch_exec (const struct bp_location *bl,
8360                            const address_space *aspace, CORE_ADDR bp_addr,
8361                            const struct target_waitstatus *ws)
8362 {
8363   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8364
8365   if (ws->kind != TARGET_WAITKIND_EXECD)
8366     return 0;
8367
8368   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8369   return 1;
8370 }
8371
8372 static enum print_stop_action
8373 print_it_catch_exec (bpstat bs)
8374 {
8375   struct ui_out *uiout = current_uiout;
8376   struct breakpoint *b = bs->breakpoint_at;
8377   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8378
8379   annotate_catchpoint (b->number);
8380   maybe_print_thread_hit_breakpoint (uiout);
8381   if (b->disposition == disp_del)
8382     uiout->text ("Temporary catchpoint ");
8383   else
8384     uiout->text ("Catchpoint ");
8385   if (uiout->is_mi_like_p ())
8386     {
8387       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8388       uiout->field_string ("disp", bpdisp_text (b->disposition));
8389     }
8390   uiout->field_int ("bkptno", b->number);
8391   uiout->text (" (exec'd ");
8392   uiout->field_string ("new-exec", c->exec_pathname);
8393   uiout->text ("), ");
8394
8395   return PRINT_SRC_AND_LOC;
8396 }
8397
8398 static void
8399 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8400 {
8401   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8402   struct value_print_options opts;
8403   struct ui_out *uiout = current_uiout;
8404
8405   get_user_print_options (&opts);
8406
8407   /* Field 4, the address, is omitted (which makes the columns
8408      not line up too nicely with the headers, but the effect
8409      is relatively readable).  */
8410   if (opts.addressprint)
8411     uiout->field_skip ("addr");
8412   annotate_field (5);
8413   uiout->text ("exec");
8414   if (c->exec_pathname != NULL)
8415     {
8416       uiout->text (", program \"");
8417       uiout->field_string ("what", c->exec_pathname);
8418       uiout->text ("\" ");
8419     }
8420
8421   if (uiout->is_mi_like_p ())
8422     uiout->field_string ("catch-type", "exec");
8423 }
8424
8425 static void
8426 print_mention_catch_exec (struct breakpoint *b)
8427 {
8428   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8429 }
8430
8431 /* Implement the "print_recreate" breakpoint_ops method for exec
8432    catchpoints.  */
8433
8434 static void
8435 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8436 {
8437   fprintf_unfiltered (fp, "catch exec");
8438   print_recreate_thread (b, fp);
8439 }
8440
8441 static struct breakpoint_ops catch_exec_breakpoint_ops;
8442
8443 static int
8444 hw_breakpoint_used_count (void)
8445 {
8446   int i = 0;
8447   struct breakpoint *b;
8448   struct bp_location *bl;
8449
8450   ALL_BREAKPOINTS (b)
8451   {
8452     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8453       for (bl = b->loc; bl; bl = bl->next)
8454         {
8455           /* Special types of hardware breakpoints may use more than
8456              one register.  */
8457           i += b->ops->resources_needed (bl);
8458         }
8459   }
8460
8461   return i;
8462 }
8463
8464 /* Returns the resources B would use if it were a hardware
8465    watchpoint.  */
8466
8467 static int
8468 hw_watchpoint_use_count (struct breakpoint *b)
8469 {
8470   int i = 0;
8471   struct bp_location *bl;
8472
8473   if (!breakpoint_enabled (b))
8474     return 0;
8475
8476   for (bl = b->loc; bl; bl = bl->next)
8477     {
8478       /* Special types of hardware watchpoints may use more than
8479          one register.  */
8480       i += b->ops->resources_needed (bl);
8481     }
8482
8483   return i;
8484 }
8485
8486 /* Returns the sum the used resources of all hardware watchpoints of
8487    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8488    the sum of the used resources of all hardware watchpoints of other
8489    types _not_ TYPE.  */
8490
8491 static int
8492 hw_watchpoint_used_count_others (struct breakpoint *except,
8493                                  enum bptype type, int *other_type_used)
8494 {
8495   int i = 0;
8496   struct breakpoint *b;
8497
8498   *other_type_used = 0;
8499   ALL_BREAKPOINTS (b)
8500     {
8501       if (b == except)
8502         continue;
8503       if (!breakpoint_enabled (b))
8504         continue;
8505
8506       if (b->type == type)
8507         i += hw_watchpoint_use_count (b);
8508       else if (is_hardware_watchpoint (b))
8509         *other_type_used = 1;
8510     }
8511
8512   return i;
8513 }
8514
8515 void
8516 disable_watchpoints_before_interactive_call_start (void)
8517 {
8518   struct breakpoint *b;
8519
8520   ALL_BREAKPOINTS (b)
8521   {
8522     if (is_watchpoint (b) && breakpoint_enabled (b))
8523       {
8524         b->enable_state = bp_call_disabled;
8525         update_global_location_list (UGLL_DONT_INSERT);
8526       }
8527   }
8528 }
8529
8530 void
8531 enable_watchpoints_after_interactive_call_stop (void)
8532 {
8533   struct breakpoint *b;
8534
8535   ALL_BREAKPOINTS (b)
8536   {
8537     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8538       {
8539         b->enable_state = bp_enabled;
8540         update_global_location_list (UGLL_MAY_INSERT);
8541       }
8542   }
8543 }
8544
8545 void
8546 disable_breakpoints_before_startup (void)
8547 {
8548   current_program_space->executing_startup = 1;
8549   update_global_location_list (UGLL_DONT_INSERT);
8550 }
8551
8552 void
8553 enable_breakpoints_after_startup (void)
8554 {
8555   current_program_space->executing_startup = 0;
8556   breakpoint_re_set ();
8557 }
8558
8559 /* Create a new single-step breakpoint for thread THREAD, with no
8560    locations.  */
8561
8562 static struct breakpoint *
8563 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8564 {
8565   std::unique_ptr<breakpoint> b (new breakpoint ());
8566
8567   init_raw_breakpoint_without_location (b.get (), gdbarch, bp_single_step,
8568                                         &momentary_breakpoint_ops);
8569
8570   b->disposition = disp_donttouch;
8571   b->frame_id = null_frame_id;
8572
8573   b->thread = thread;
8574   gdb_assert (b->thread != 0);
8575
8576   return add_to_breakpoint_chain (std::move (b));
8577 }
8578
8579 /* Set a momentary breakpoint of type TYPE at address specified by
8580    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8581    frame.  */
8582
8583 breakpoint_up
8584 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8585                           struct frame_id frame_id, enum bptype type)
8586 {
8587   struct breakpoint *b;
8588
8589   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8590      tail-called one.  */
8591   gdb_assert (!frame_id_artificial_p (frame_id));
8592
8593   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8594   b->enable_state = bp_enabled;
8595   b->disposition = disp_donttouch;
8596   b->frame_id = frame_id;
8597
8598   /* If we're debugging a multi-threaded program, then we want
8599      momentary breakpoints to be active in only a single thread of
8600      control.  */
8601   if (in_thread_list (inferior_ptid))
8602     b->thread = ptid_to_global_thread_id (inferior_ptid);
8603
8604   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8605
8606   return breakpoint_up (b);
8607 }
8608
8609 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8610    The new breakpoint will have type TYPE, use OPS as its
8611    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8612
8613 static struct breakpoint *
8614 momentary_breakpoint_from_master (struct breakpoint *orig,
8615                                   enum bptype type,
8616                                   const struct breakpoint_ops *ops,
8617                                   int loc_enabled)
8618 {
8619   struct breakpoint *copy;
8620
8621   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8622   copy->loc = allocate_bp_location (copy);
8623   set_breakpoint_location_function (copy->loc, 1);
8624
8625   copy->loc->gdbarch = orig->loc->gdbarch;
8626   copy->loc->requested_address = orig->loc->requested_address;
8627   copy->loc->address = orig->loc->address;
8628   copy->loc->section = orig->loc->section;
8629   copy->loc->pspace = orig->loc->pspace;
8630   copy->loc->probe = orig->loc->probe;
8631   copy->loc->line_number = orig->loc->line_number;
8632   copy->loc->symtab = orig->loc->symtab;
8633   copy->loc->enabled = loc_enabled;
8634   copy->frame_id = orig->frame_id;
8635   copy->thread = orig->thread;
8636   copy->pspace = orig->pspace;
8637
8638   copy->enable_state = bp_enabled;
8639   copy->disposition = disp_donttouch;
8640   copy->number = internal_breakpoint_number--;
8641
8642   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8643   return copy;
8644 }
8645
8646 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8647    ORIG is NULL.  */
8648
8649 struct breakpoint *
8650 clone_momentary_breakpoint (struct breakpoint *orig)
8651 {
8652   /* If there's nothing to clone, then return nothing.  */
8653   if (orig == NULL)
8654     return NULL;
8655
8656   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8657 }
8658
8659 breakpoint_up
8660 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8661                                 enum bptype type)
8662 {
8663   struct symtab_and_line sal;
8664
8665   sal = find_pc_line (pc, 0);
8666   sal.pc = pc;
8667   sal.section = find_pc_overlay (pc);
8668   sal.explicit_pc = 1;
8669
8670   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8671 }
8672 \f
8673
8674 /* Tell the user we have just set a breakpoint B.  */
8675
8676 static void
8677 mention (struct breakpoint *b)
8678 {
8679   b->ops->print_mention (b);
8680   if (current_uiout->is_mi_like_p ())
8681     return;
8682   printf_filtered ("\n");
8683 }
8684 \f
8685
8686 static int bp_loc_is_permanent (struct bp_location *loc);
8687
8688 static struct bp_location *
8689 add_location_to_breakpoint (struct breakpoint *b,
8690                             const struct symtab_and_line *sal)
8691 {
8692   struct bp_location *loc, **tmp;
8693   CORE_ADDR adjusted_address;
8694   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8695
8696   if (loc_gdbarch == NULL)
8697     loc_gdbarch = b->gdbarch;
8698
8699   /* Adjust the breakpoint's address prior to allocating a location.
8700      Once we call allocate_bp_location(), that mostly uninitialized
8701      location will be placed on the location chain.  Adjustment of the
8702      breakpoint may cause target_read_memory() to be called and we do
8703      not want its scan of the location chain to find a breakpoint and
8704      location that's only been partially initialized.  */
8705   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8706                                                 sal->pc, b->type);
8707
8708   /* Sort the locations by their ADDRESS.  */
8709   loc = allocate_bp_location (b);
8710   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8711        tmp = &((*tmp)->next))
8712     ;
8713   loc->next = *tmp;
8714   *tmp = loc;
8715
8716   loc->requested_address = sal->pc;
8717   loc->address = adjusted_address;
8718   loc->pspace = sal->pspace;
8719   loc->probe.probe = sal->probe;
8720   loc->probe.objfile = sal->objfile;
8721   gdb_assert (loc->pspace != NULL);
8722   loc->section = sal->section;
8723   loc->gdbarch = loc_gdbarch;
8724   loc->line_number = sal->line;
8725   loc->symtab = sal->symtab;
8726   loc->symbol = sal->symbol;
8727
8728   set_breakpoint_location_function (loc,
8729                                     sal->explicit_pc || sal->explicit_line);
8730
8731   /* While by definition, permanent breakpoints are already present in the
8732      code, we don't mark the location as inserted.  Normally one would expect
8733      that GDB could rely on that breakpoint instruction to stop the program,
8734      thus removing the need to insert its own breakpoint, except that executing
8735      the breakpoint instruction can kill the target instead of reporting a
8736      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8737      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8738      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8739      breakpoint be inserted normally results in QEMU knowing about the GDB
8740      breakpoint, and thus trap before the breakpoint instruction is executed.
8741      (If GDB later needs to continue execution past the permanent breakpoint,
8742      it manually increments the PC, thus avoiding executing the breakpoint
8743      instruction.)  */
8744   if (bp_loc_is_permanent (loc))
8745     loc->permanent = 1;
8746
8747   return loc;
8748 }
8749 \f
8750
8751 /* See breakpoint.h.  */
8752
8753 int
8754 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
8755 {
8756   int len;
8757   CORE_ADDR addr;
8758   const gdb_byte *bpoint;
8759   gdb_byte *target_mem;
8760
8761   addr = address;
8762   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
8763
8764   /* Software breakpoints unsupported?  */
8765   if (bpoint == NULL)
8766     return 0;
8767
8768   target_mem = (gdb_byte *) alloca (len);
8769
8770   /* Enable the automatic memory restoration from breakpoints while
8771      we read the memory.  Otherwise we could say about our temporary
8772      breakpoints they are permanent.  */
8773   scoped_restore restore_memory
8774     = make_scoped_restore_show_memory_breakpoints (0);
8775
8776   if (target_read_memory (address, target_mem, len) == 0
8777       && memcmp (target_mem, bpoint, len) == 0)
8778     return 1;
8779
8780   return 0;
8781 }
8782
8783 /* Return 1 if LOC is pointing to a permanent breakpoint,
8784    return 0 otherwise.  */
8785
8786 static int
8787 bp_loc_is_permanent (struct bp_location *loc)
8788 {
8789   gdb_assert (loc != NULL);
8790
8791   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
8792      attempt to read from the addresses the locations of these breakpoint types
8793      point to.  program_breakpoint_here_p, below, will attempt to read
8794      memory.  */
8795   if (!breakpoint_address_is_meaningful (loc->owner))
8796     return 0;
8797
8798   scoped_restore_current_pspace_and_thread restore_pspace_thread;
8799   switch_to_program_space_and_thread (loc->pspace);
8800   return program_breakpoint_here_p (loc->gdbarch, loc->address);
8801 }
8802
8803 /* Build a command list for the dprintf corresponding to the current
8804    settings of the dprintf style options.  */
8805
8806 static void
8807 update_dprintf_command_list (struct breakpoint *b)
8808 {
8809   char *dprintf_args = b->extra_string;
8810   char *printf_line = NULL;
8811
8812   if (!dprintf_args)
8813     return;
8814
8815   dprintf_args = skip_spaces (dprintf_args);
8816
8817   /* Allow a comma, as it may have terminated a location, but don't
8818      insist on it.  */
8819   if (*dprintf_args == ',')
8820     ++dprintf_args;
8821   dprintf_args = skip_spaces (dprintf_args);
8822
8823   if (*dprintf_args != '"')
8824     error (_("Bad format string, missing '\"'."));
8825
8826   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8827     printf_line = xstrprintf ("printf %s", dprintf_args);
8828   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8829     {
8830       if (!dprintf_function)
8831         error (_("No function supplied for dprintf call"));
8832
8833       if (dprintf_channel && strlen (dprintf_channel) > 0)
8834         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8835                                   dprintf_function,
8836                                   dprintf_channel,
8837                                   dprintf_args);
8838       else
8839         printf_line = xstrprintf ("call (void) %s (%s)",
8840                                   dprintf_function,
8841                                   dprintf_args);
8842     }
8843   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8844     {
8845       if (target_can_run_breakpoint_commands ())
8846         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8847       else
8848         {
8849           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8850           printf_line = xstrprintf ("printf %s", dprintf_args);
8851         }
8852     }
8853   else
8854     internal_error (__FILE__, __LINE__,
8855                     _("Invalid dprintf style."));
8856
8857   gdb_assert (printf_line != NULL);
8858   /* Manufacture a printf sequence.  */
8859   {
8860     struct command_line *printf_cmd_line = XNEW (struct command_line);
8861
8862     printf_cmd_line->control_type = simple_control;
8863     printf_cmd_line->body_count = 0;
8864     printf_cmd_line->body_list = NULL;
8865     printf_cmd_line->next = NULL;
8866     printf_cmd_line->line = printf_line;
8867
8868     breakpoint_set_commands (b, command_line_up (printf_cmd_line));
8869   }
8870 }
8871
8872 /* Update all dprintf commands, making their command lists reflect
8873    current style settings.  */
8874
8875 static void
8876 update_dprintf_commands (char *args, int from_tty,
8877                          struct cmd_list_element *c)
8878 {
8879   struct breakpoint *b;
8880
8881   ALL_BREAKPOINTS (b)
8882     {
8883       if (b->type == bp_dprintf)
8884         update_dprintf_command_list (b);
8885     }
8886 }
8887
8888 /* Create a breakpoint with SAL as location.  Use LOCATION
8889    as a description of the location, and COND_STRING
8890    as condition expression.  If LOCATION is NULL then create an
8891    "address location" from the address in the SAL.  */
8892
8893 static void
8894 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8895                      gdb::array_view<const symtab_and_line> sals,
8896                      event_location_up &&location,
8897                      gdb::unique_xmalloc_ptr<char> filter,
8898                      gdb::unique_xmalloc_ptr<char> cond_string,
8899                      gdb::unique_xmalloc_ptr<char> extra_string,
8900                      enum bptype type, enum bpdisp disposition,
8901                      int thread, int task, int ignore_count,
8902                      const struct breakpoint_ops *ops, int from_tty,
8903                      int enabled, int internal, unsigned flags,
8904                      int display_canonical)
8905 {
8906   int i;
8907
8908   if (type == bp_hardware_breakpoint)
8909     {
8910       int target_resources_ok;
8911
8912       i = hw_breakpoint_used_count ();
8913       target_resources_ok =
8914         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8915                                             i + 1, 0);
8916       if (target_resources_ok == 0)
8917         error (_("No hardware breakpoint support in the target."));
8918       else if (target_resources_ok < 0)
8919         error (_("Hardware breakpoints used exceeds limit."));
8920     }
8921
8922   gdb_assert (!sals.empty ());
8923
8924   for (const auto &sal : sals)
8925     {
8926       struct bp_location *loc;
8927
8928       if (from_tty)
8929         {
8930           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8931           if (!loc_gdbarch)
8932             loc_gdbarch = gdbarch;
8933
8934           describe_other_breakpoints (loc_gdbarch,
8935                                       sal.pspace, sal.pc, sal.section, thread);
8936         }
8937
8938       if (&sal == &sals[0])
8939         {
8940           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8941           b->thread = thread;
8942           b->task = task;
8943
8944           b->cond_string = cond_string.release ();
8945           b->extra_string = extra_string.release ();
8946           b->ignore_count = ignore_count;
8947           b->enable_state = enabled ? bp_enabled : bp_disabled;
8948           b->disposition = disposition;
8949
8950           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8951             b->loc->inserted = 1;
8952
8953           if (type == bp_static_tracepoint)
8954             {
8955               struct tracepoint *t = (struct tracepoint *) b;
8956               struct static_tracepoint_marker marker;
8957
8958               if (strace_marker_p (b))
8959                 {
8960                   /* We already know the marker exists, otherwise, we
8961                      wouldn't see a sal for it.  */
8962                   const char *p
8963                     = &event_location_to_string (b->location.get ())[3];
8964                   const char *endp;
8965                   char *marker_str;
8966
8967                   p = skip_spaces (p);
8968
8969                   endp = skip_to_space (p);
8970
8971                   marker_str = savestring (p, endp - p);
8972                   t->static_trace_marker_id = marker_str;
8973
8974                   printf_filtered (_("Probed static tracepoint "
8975                                      "marker \"%s\"\n"),
8976                                    t->static_trace_marker_id);
8977                 }
8978               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8979                 {
8980                   t->static_trace_marker_id = xstrdup (marker.str_id);
8981                   release_static_tracepoint_marker (&marker);
8982
8983                   printf_filtered (_("Probed static tracepoint "
8984                                      "marker \"%s\"\n"),
8985                                    t->static_trace_marker_id);
8986                 }
8987               else
8988                 warning (_("Couldn't determine the static "
8989                            "tracepoint marker to probe"));
8990             }
8991
8992           loc = b->loc;
8993         }
8994       else
8995         {
8996           loc = add_location_to_breakpoint (b, &sal);
8997           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8998             loc->inserted = 1;
8999         }
9000
9001       if (b->cond_string)
9002         {
9003           const char *arg = b->cond_string;
9004
9005           loc->cond = parse_exp_1 (&arg, loc->address,
9006                                    block_for_pc (loc->address), 0);
9007           if (*arg)
9008               error (_("Garbage '%s' follows condition"), arg);
9009         }
9010
9011       /* Dynamic printf requires and uses additional arguments on the
9012          command line, otherwise it's an error.  */
9013       if (type == bp_dprintf)
9014         {
9015           if (b->extra_string)
9016             update_dprintf_command_list (b);
9017           else
9018             error (_("Format string required"));
9019         }
9020       else if (b->extra_string)
9021         error (_("Garbage '%s' at end of command"), b->extra_string);
9022     }
9023
9024   b->display_canonical = display_canonical;
9025   if (location != NULL)
9026     b->location = std::move (location);
9027   else
9028     b->location = new_address_location (b->loc->address, NULL, 0);
9029   b->filter = filter.release ();
9030 }
9031
9032 static void
9033 create_breakpoint_sal (struct gdbarch *gdbarch,
9034                        gdb::array_view<const symtab_and_line> sals,
9035                        event_location_up &&location,
9036                        gdb::unique_xmalloc_ptr<char> filter,
9037                        gdb::unique_xmalloc_ptr<char> cond_string,
9038                        gdb::unique_xmalloc_ptr<char> extra_string,
9039                        enum bptype type, enum bpdisp disposition,
9040                        int thread, int task, int ignore_count,
9041                        const struct breakpoint_ops *ops, int from_tty,
9042                        int enabled, int internal, unsigned flags,
9043                        int display_canonical)
9044 {
9045   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (type);
9046
9047   init_breakpoint_sal (b.get (), gdbarch,
9048                        sals, std::move (location),
9049                        std::move (filter),
9050                        std::move (cond_string),
9051                        std::move (extra_string),
9052                        type, disposition,
9053                        thread, task, ignore_count,
9054                        ops, from_tty,
9055                        enabled, internal, flags,
9056                        display_canonical);
9057
9058   install_breakpoint (internal, std::move (b), 0);
9059 }
9060
9061 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9062    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9063    value.  COND_STRING, if not NULL, specified the condition to be
9064    used for all breakpoints.  Essentially the only case where
9065    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9066    function.  In that case, it's still not possible to specify
9067    separate conditions for different overloaded functions, so
9068    we take just a single condition string.
9069    
9070    NOTE: If the function succeeds, the caller is expected to cleanup
9071    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9072    array contents).  If the function fails (error() is called), the
9073    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9074    COND and SALS arrays and each of those arrays contents.  */
9075
9076 static void
9077 create_breakpoints_sal (struct gdbarch *gdbarch,
9078                         struct linespec_result *canonical,
9079                         gdb::unique_xmalloc_ptr<char> cond_string,
9080                         gdb::unique_xmalloc_ptr<char> extra_string,
9081                         enum bptype type, enum bpdisp disposition,
9082                         int thread, int task, int ignore_count,
9083                         const struct breakpoint_ops *ops, int from_tty,
9084                         int enabled, int internal, unsigned flags)
9085 {
9086   if (canonical->pre_expanded)
9087     gdb_assert (canonical->lsals.size () == 1);
9088
9089   for (const auto &lsal : canonical->lsals)
9090     {
9091       /* Note that 'location' can be NULL in the case of a plain
9092          'break', without arguments.  */
9093       event_location_up location
9094         = (canonical->location != NULL
9095            ? copy_event_location (canonical->location.get ()) : NULL);
9096       gdb::unique_xmalloc_ptr<char> filter_string
9097         (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
9098
9099       create_breakpoint_sal (gdbarch, lsal.sals,
9100                              std::move (location),
9101                              std::move (filter_string),
9102                              std::move (cond_string),
9103                              std::move (extra_string),
9104                              type, disposition,
9105                              thread, task, ignore_count, ops,
9106                              from_tty, enabled, internal, flags,
9107                              canonical->special_display);
9108     }
9109 }
9110
9111 /* Parse LOCATION which is assumed to be a SAL specification possibly
9112    followed by conditionals.  On return, SALS contains an array of SAL
9113    addresses found.  LOCATION points to the end of the SAL (for
9114    linespec locations).
9115
9116    The array and the line spec strings are allocated on the heap, it is
9117    the caller's responsibility to free them.  */
9118
9119 static void
9120 parse_breakpoint_sals (const struct event_location *location,
9121                        struct linespec_result *canonical)
9122 {
9123   struct symtab_and_line cursal;
9124
9125   if (event_location_type (location) == LINESPEC_LOCATION)
9126     {
9127       const char *address = get_linespec_location (location);
9128
9129       if (address == NULL)
9130         {
9131           /* The last displayed codepoint, if it's valid, is our default
9132              breakpoint address.  */
9133           if (last_displayed_sal_is_valid ())
9134             {
9135               /* Set sal's pspace, pc, symtab, and line to the values
9136                  corresponding to the last call to print_frame_info.
9137                  Be sure to reinitialize LINE with NOTCURRENT == 0
9138                  as the breakpoint line number is inappropriate otherwise.
9139                  find_pc_line would adjust PC, re-set it back.  */
9140               symtab_and_line sal = get_last_displayed_sal ();
9141               CORE_ADDR pc = sal.pc;
9142
9143               sal = find_pc_line (pc, 0);
9144
9145               /* "break" without arguments is equivalent to "break *PC"
9146                  where PC is the last displayed codepoint's address.  So
9147                  make sure to set sal.explicit_pc to prevent GDB from
9148                  trying to expand the list of sals to include all other
9149                  instances with the same symtab and line.  */
9150               sal.pc = pc;
9151               sal.explicit_pc = 1;
9152
9153               struct linespec_sals lsal;
9154               lsal.sals = {sal};
9155               lsal.canonical = NULL;
9156
9157               canonical->lsals.push_back (std::move (lsal));
9158               return;
9159             }
9160           else
9161             error (_("No default breakpoint address now."));
9162         }
9163     }
9164
9165   /* Force almost all breakpoints to be in terms of the
9166      current_source_symtab (which is decode_line_1's default).
9167      This should produce the results we want almost all of the
9168      time while leaving default_breakpoint_* alone.
9169
9170      ObjC: However, don't match an Objective-C method name which
9171      may have a '+' or '-' succeeded by a '['.  */
9172   cursal = get_current_source_symtab_and_line ();
9173   if (last_displayed_sal_is_valid ())
9174     {
9175       const char *address = NULL;
9176
9177       if (event_location_type (location) == LINESPEC_LOCATION)
9178         address = get_linespec_location (location);
9179
9180       if (!cursal.symtab
9181           || (address != NULL
9182               && strchr ("+-", address[0]) != NULL
9183               && address[1] != '['))
9184         {
9185           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9186                             get_last_displayed_symtab (),
9187                             get_last_displayed_line (),
9188                             canonical, NULL, NULL);
9189           return;
9190         }
9191     }
9192
9193   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9194                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9195 }
9196
9197
9198 /* Convert each SAL into a real PC.  Verify that the PC can be
9199    inserted as a breakpoint.  If it can't throw an error.  */
9200
9201 static void
9202 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
9203 {    
9204   for (auto &sal : sals)
9205     resolve_sal_pc (&sal);
9206 }
9207
9208 /* Fast tracepoints may have restrictions on valid locations.  For
9209    instance, a fast tracepoint using a jump instead of a trap will
9210    likely have to overwrite more bytes than a trap would, and so can
9211    only be placed where the instruction is longer than the jump, or a
9212    multi-instruction sequence does not have a jump into the middle of
9213    it, etc.  */
9214
9215 static void
9216 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9217                             gdb::array_view<const symtab_and_line> sals)
9218 {
9219   int rslt;
9220   char *msg;
9221   struct cleanup *old_chain;
9222
9223   for (const auto &sal : sals)
9224     {
9225       struct gdbarch *sarch;
9226
9227       sarch = get_sal_arch (sal);
9228       /* We fall back to GDBARCH if there is no architecture
9229          associated with SAL.  */
9230       if (sarch == NULL)
9231         sarch = gdbarch;
9232       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg);
9233       old_chain = make_cleanup (xfree, msg);
9234
9235       if (!rslt)
9236         error (_("May not have a fast tracepoint at %s%s"),
9237                paddress (sarch, sal.pc), (msg ? msg : ""));
9238
9239       do_cleanups (old_chain);
9240     }
9241 }
9242
9243 /* Given TOK, a string specification of condition and thread, as
9244    accepted by the 'break' command, extract the condition
9245    string and thread number and set *COND_STRING and *THREAD.
9246    PC identifies the context at which the condition should be parsed.
9247    If no condition is found, *COND_STRING is set to NULL.
9248    If no thread is found, *THREAD is set to -1.  */
9249
9250 static void
9251 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9252                            char **cond_string, int *thread, int *task,
9253                            char **rest)
9254 {
9255   *cond_string = NULL;
9256   *thread = -1;
9257   *task = 0;
9258   *rest = NULL;
9259
9260   while (tok && *tok)
9261     {
9262       const char *end_tok;
9263       int toklen;
9264       const char *cond_start = NULL;
9265       const char *cond_end = NULL;
9266
9267       tok = skip_spaces (tok);
9268
9269       if ((*tok == '"' || *tok == ',') && rest)
9270         {
9271           *rest = savestring (tok, strlen (tok));
9272           return;
9273         }
9274
9275       end_tok = skip_to_space (tok);
9276
9277       toklen = end_tok - tok;
9278
9279       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9280         {
9281           tok = cond_start = end_tok + 1;
9282           parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9283           cond_end = tok;
9284           *cond_string = savestring (cond_start, cond_end - cond_start);
9285         }
9286       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9287         {
9288           const char *tmptok;
9289           struct thread_info *thr;
9290
9291           tok = end_tok + 1;
9292           thr = parse_thread_id (tok, &tmptok);
9293           if (tok == tmptok)
9294             error (_("Junk after thread keyword."));
9295           *thread = thr->global_num;
9296           tok = tmptok;
9297         }
9298       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9299         {
9300           char *tmptok;
9301
9302           tok = end_tok + 1;
9303           *task = strtol (tok, &tmptok, 0);
9304           if (tok == tmptok)
9305             error (_("Junk after task keyword."));
9306           if (!valid_task_id (*task))
9307             error (_("Unknown task %d."), *task);
9308           tok = tmptok;
9309         }
9310       else if (rest)
9311         {
9312           *rest = savestring (tok, strlen (tok));
9313           return;
9314         }
9315       else
9316         error (_("Junk at end of arguments."));
9317     }
9318 }
9319
9320 /* Decode a static tracepoint marker spec.  */
9321
9322 static std::vector<symtab_and_line>
9323 decode_static_tracepoint_spec (const char **arg_p)
9324 {
9325   VEC(static_tracepoint_marker_p) *markers = NULL;
9326   const char *p = &(*arg_p)[3];
9327   const char *endp;
9328   int i;
9329
9330   p = skip_spaces (p);
9331
9332   endp = skip_to_space (p);
9333
9334   std::string marker_str (p, endp - p);
9335
9336   markers = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
9337   if (VEC_empty(static_tracepoint_marker_p, markers))
9338     error (_("No known static tracepoint marker named %s"),
9339            marker_str.c_str ());
9340
9341   std::vector<symtab_and_line> sals;
9342   sals.reserve (VEC_length(static_tracepoint_marker_p, markers));
9343
9344   for (i = 0; i < VEC_length(static_tracepoint_marker_p, markers); i++)
9345     {
9346       struct static_tracepoint_marker *marker;
9347
9348       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9349
9350       symtab_and_line sal = find_pc_line (marker->address, 0);
9351       sal.pc = marker->address;
9352       sals.push_back (sal);
9353
9354       release_static_tracepoint_marker (marker);
9355     }
9356
9357   *arg_p = endp;
9358   return sals;
9359 }
9360
9361 /* See breakpoint.h.  */
9362
9363 int
9364 create_breakpoint (struct gdbarch *gdbarch,
9365                    const struct event_location *location,
9366                    const char *cond_string,
9367                    int thread, const char *extra_string,
9368                    int parse_extra,
9369                    int tempflag, enum bptype type_wanted,
9370                    int ignore_count,
9371                    enum auto_boolean pending_break_support,
9372                    const struct breakpoint_ops *ops,
9373                    int from_tty, int enabled, int internal,
9374                    unsigned flags)
9375 {
9376   struct linespec_result canonical;
9377   struct cleanup *bkpt_chain = NULL;
9378   int pending = 0;
9379   int task = 0;
9380   int prev_bkpt_count = breakpoint_count;
9381
9382   gdb_assert (ops != NULL);
9383
9384   /* If extra_string isn't useful, set it to NULL.  */
9385   if (extra_string != NULL && *extra_string == '\0')
9386     extra_string = NULL;
9387
9388   TRY
9389     {
9390       ops->create_sals_from_location (location, &canonical, type_wanted);
9391     }
9392   CATCH (e, RETURN_MASK_ERROR)
9393     {
9394       /* If caller is interested in rc value from parse, set
9395          value.  */
9396       if (e.error == NOT_FOUND_ERROR)
9397         {
9398           /* If pending breakpoint support is turned off, throw
9399              error.  */
9400
9401           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9402             throw_exception (e);
9403
9404           exception_print (gdb_stderr, e);
9405
9406           /* If pending breakpoint support is auto query and the user
9407              selects no, then simply return the error code.  */
9408           if (pending_break_support == AUTO_BOOLEAN_AUTO
9409               && !nquery (_("Make %s pending on future shared library load? "),
9410                           bptype_string (type_wanted)))
9411             return 0;
9412
9413           /* At this point, either the user was queried about setting
9414              a pending breakpoint and selected yes, or pending
9415              breakpoint behavior is on and thus a pending breakpoint
9416              is defaulted on behalf of the user.  */
9417           pending = 1;
9418         }
9419       else
9420         throw_exception (e);
9421     }
9422   END_CATCH
9423
9424   if (!pending && canonical.lsals.empty ())
9425     return 0;
9426
9427   /* ----------------------------- SNIP -----------------------------
9428      Anything added to the cleanup chain beyond this point is assumed
9429      to be part of a breakpoint.  If the breakpoint create succeeds
9430      then the memory is not reclaimed.  */
9431   bkpt_chain = make_cleanup (null_cleanup, 0);
9432
9433   /* Resolve all line numbers to PC's and verify that the addresses
9434      are ok for the target.  */
9435   if (!pending)
9436     {
9437       for (auto &lsal : canonical.lsals)
9438         breakpoint_sals_to_pc (lsal.sals);
9439     }
9440
9441   /* Fast tracepoints may have additional restrictions on location.  */
9442   if (!pending && type_wanted == bp_fast_tracepoint)
9443     {
9444       for (const auto &lsal : canonical.lsals)
9445         check_fast_tracepoint_sals (gdbarch, lsal.sals);
9446     }
9447
9448   /* Verify that condition can be parsed, before setting any
9449      breakpoints.  Allocate a separate condition expression for each
9450      breakpoint.  */
9451   if (!pending)
9452     {
9453       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9454       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9455
9456       if (parse_extra)
9457         {
9458           char *rest;
9459           char *cond;
9460
9461           const linespec_sals &lsal = canonical.lsals[0];
9462
9463           /* Here we only parse 'arg' to separate condition
9464              from thread number, so parsing in context of first
9465              sal is OK.  When setting the breakpoint we'll
9466              re-parse it in context of each sal.  */
9467
9468           find_condition_and_thread (extra_string, lsal.sals[0].pc,
9469                                      &cond, &thread, &task, &rest);
9470           cond_string_copy.reset (cond);
9471           extra_string_copy.reset (rest);
9472         }
9473       else
9474         {
9475           if (type_wanted != bp_dprintf
9476               && extra_string != NULL && *extra_string != '\0')
9477                 error (_("Garbage '%s' at end of location"), extra_string);
9478
9479           /* Create a private copy of condition string.  */
9480           if (cond_string)
9481             cond_string_copy.reset (xstrdup (cond_string));
9482           /* Create a private copy of any extra string.  */
9483           if (extra_string)
9484             extra_string_copy.reset (xstrdup (extra_string));
9485         }
9486
9487       ops->create_breakpoints_sal (gdbarch, &canonical,
9488                                    std::move (cond_string_copy),
9489                                    std::move (extra_string_copy),
9490                                    type_wanted,
9491                                    tempflag ? disp_del : disp_donttouch,
9492                                    thread, task, ignore_count, ops,
9493                                    from_tty, enabled, internal, flags);
9494     }
9495   else
9496     {
9497       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (type_wanted);
9498
9499       init_raw_breakpoint_without_location (b.get (), gdbarch, type_wanted, ops);
9500       b->location = copy_event_location (location);
9501
9502       if (parse_extra)
9503         b->cond_string = NULL;
9504       else
9505         {
9506           /* Create a private copy of condition string.  */
9507           b->cond_string = cond_string != NULL ? xstrdup (cond_string) : NULL;
9508           b->thread = thread;
9509         }
9510
9511       /* Create a private copy of any extra string.  */
9512       b->extra_string = extra_string != NULL ? xstrdup (extra_string) : NULL;
9513       b->ignore_count = ignore_count;
9514       b->disposition = tempflag ? disp_del : disp_donttouch;
9515       b->condition_not_parsed = 1;
9516       b->enable_state = enabled ? bp_enabled : bp_disabled;
9517       if ((type_wanted != bp_breakpoint
9518            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9519         b->pspace = current_program_space;
9520
9521       install_breakpoint (internal, std::move (b), 0);
9522     }
9523   
9524   if (canonical.lsals.size () > 1)
9525     {
9526       warning (_("Multiple breakpoints were set.\nUse the "
9527                  "\"delete\" command to delete unwanted breakpoints."));
9528       prev_breakpoint_count = prev_bkpt_count;
9529     }
9530
9531   /* That's it.  Discard the cleanups for data inserted into the
9532      breakpoint.  */
9533   discard_cleanups (bkpt_chain);
9534
9535   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9536   update_global_location_list (UGLL_MAY_INSERT);
9537
9538   return 1;
9539 }
9540
9541 /* Set a breakpoint.
9542    ARG is a string describing breakpoint address,
9543    condition, and thread.
9544    FLAG specifies if a breakpoint is hardware on,
9545    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9546    and BP_TEMPFLAG.  */
9547
9548 static void
9549 break_command_1 (const char *arg, int flag, int from_tty)
9550 {
9551   int tempflag = flag & BP_TEMPFLAG;
9552   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9553                              ? bp_hardware_breakpoint
9554                              : bp_breakpoint);
9555   struct breakpoint_ops *ops;
9556
9557   event_location_up location = string_to_event_location (&arg, current_language);
9558
9559   /* Matching breakpoints on probes.  */
9560   if (location != NULL
9561       && event_location_type (location.get ()) == PROBE_LOCATION)
9562     ops = &bkpt_probe_breakpoint_ops;
9563   else
9564     ops = &bkpt_breakpoint_ops;
9565
9566   create_breakpoint (get_current_arch (),
9567                      location.get (),
9568                      NULL, 0, arg, 1 /* parse arg */,
9569                      tempflag, type_wanted,
9570                      0 /* Ignore count */,
9571                      pending_break_support,
9572                      ops,
9573                      from_tty,
9574                      1 /* enabled */,
9575                      0 /* internal */,
9576                      0);
9577 }
9578
9579 /* Helper function for break_command_1 and disassemble_command.  */
9580
9581 void
9582 resolve_sal_pc (struct symtab_and_line *sal)
9583 {
9584   CORE_ADDR pc;
9585
9586   if (sal->pc == 0 && sal->symtab != NULL)
9587     {
9588       if (!find_line_pc (sal->symtab, sal->line, &pc))
9589         error (_("No line %d in file \"%s\"."),
9590                sal->line, symtab_to_filename_for_display (sal->symtab));
9591       sal->pc = pc;
9592
9593       /* If this SAL corresponds to a breakpoint inserted using a line
9594          number, then skip the function prologue if necessary.  */
9595       if (sal->explicit_line)
9596         skip_prologue_sal (sal);
9597     }
9598
9599   if (sal->section == 0 && sal->symtab != NULL)
9600     {
9601       const struct blockvector *bv;
9602       const struct block *b;
9603       struct symbol *sym;
9604
9605       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9606                                     SYMTAB_COMPUNIT (sal->symtab));
9607       if (bv != NULL)
9608         {
9609           sym = block_linkage_function (b);
9610           if (sym != NULL)
9611             {
9612               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9613               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9614                                                  sym);
9615             }
9616           else
9617             {
9618               /* It really is worthwhile to have the section, so we'll
9619                  just have to look harder. This case can be executed
9620                  if we have line numbers but no functions (as can
9621                  happen in assembly source).  */
9622
9623               scoped_restore_current_pspace_and_thread restore_pspace_thread;
9624               switch_to_program_space_and_thread (sal->pspace);
9625
9626               bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9627               if (msym.minsym)
9628                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9629             }
9630         }
9631     }
9632 }
9633
9634 void
9635 break_command (char *arg, int from_tty)
9636 {
9637   break_command_1 (arg, 0, from_tty);
9638 }
9639
9640 void
9641 tbreak_command (char *arg, int from_tty)
9642 {
9643   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9644 }
9645
9646 static void
9647 hbreak_command (char *arg, int from_tty)
9648 {
9649   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9650 }
9651
9652 static void
9653 thbreak_command (char *arg, int from_tty)
9654 {
9655   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9656 }
9657
9658 static void
9659 stop_command (const char *arg, int from_tty)
9660 {
9661   printf_filtered (_("Specify the type of breakpoint to set.\n\
9662 Usage: stop in <function | address>\n\
9663        stop at <line>\n"));
9664 }
9665
9666 static void
9667 stopin_command (const char *arg, int from_tty)
9668 {
9669   int badInput = 0;
9670
9671   if (arg == (char *) NULL)
9672     badInput = 1;
9673   else if (*arg != '*')
9674     {
9675       const char *argptr = arg;
9676       int hasColon = 0;
9677
9678       /* Look for a ':'.  If this is a line number specification, then
9679          say it is bad, otherwise, it should be an address or
9680          function/method name.  */
9681       while (*argptr && !hasColon)
9682         {
9683           hasColon = (*argptr == ':');
9684           argptr++;
9685         }
9686
9687       if (hasColon)
9688         badInput = (*argptr != ':');    /* Not a class::method */
9689       else
9690         badInput = isdigit (*arg);      /* a simple line number */
9691     }
9692
9693   if (badInput)
9694     printf_filtered (_("Usage: stop in <function | address>\n"));
9695   else
9696     break_command_1 (arg, 0, from_tty);
9697 }
9698
9699 static void
9700 stopat_command (const char *arg, int from_tty)
9701 {
9702   int badInput = 0;
9703
9704   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9705     badInput = 1;
9706   else
9707     {
9708       const char *argptr = arg;
9709       int hasColon = 0;
9710
9711       /* Look for a ':'.  If there is a '::' then get out, otherwise
9712          it is probably a line number.  */
9713       while (*argptr && !hasColon)
9714         {
9715           hasColon = (*argptr == ':');
9716           argptr++;
9717         }
9718
9719       if (hasColon)
9720         badInput = (*argptr == ':');    /* we have class::method */
9721       else
9722         badInput = !isdigit (*arg);     /* not a line number */
9723     }
9724
9725   if (badInput)
9726     printf_filtered (_("Usage: stop at <line>\n"));
9727   else
9728     break_command_1 (arg, 0, from_tty);
9729 }
9730
9731 /* The dynamic printf command is mostly like a regular breakpoint, but
9732    with a prewired command list consisting of a single output command,
9733    built from extra arguments supplied on the dprintf command
9734    line.  */
9735
9736 static void
9737 dprintf_command (char *arg_in, int from_tty)
9738 {
9739   const char *arg = arg_in;
9740   event_location_up location = string_to_event_location (&arg, current_language);
9741
9742   /* If non-NULL, ARG should have been advanced past the location;
9743      the next character must be ','.  */
9744   if (arg != NULL)
9745     {
9746       if (arg[0] != ',' || arg[1] == '\0')
9747         error (_("Format string required"));
9748       else
9749         {
9750           /* Skip the comma.  */
9751           ++arg;
9752         }
9753     }
9754
9755   create_breakpoint (get_current_arch (),
9756                      location.get (),
9757                      NULL, 0, arg, 1 /* parse arg */,
9758                      0, bp_dprintf,
9759                      0 /* Ignore count */,
9760                      pending_break_support,
9761                      &dprintf_breakpoint_ops,
9762                      from_tty,
9763                      1 /* enabled */,
9764                      0 /* internal */,
9765                      0);
9766 }
9767
9768 static void
9769 agent_printf_command (char *arg, int from_tty)
9770 {
9771   error (_("May only run agent-printf on the target"));
9772 }
9773
9774 /* Implement the "breakpoint_hit" breakpoint_ops method for
9775    ranged breakpoints.  */
9776
9777 static int
9778 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9779                                   const address_space *aspace,
9780                                   CORE_ADDR bp_addr,
9781                                   const struct target_waitstatus *ws)
9782 {
9783   if (ws->kind != TARGET_WAITKIND_STOPPED
9784       || ws->value.sig != GDB_SIGNAL_TRAP)
9785     return 0;
9786
9787   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9788                                          bl->length, aspace, bp_addr);
9789 }
9790
9791 /* Implement the "resources_needed" breakpoint_ops method for
9792    ranged breakpoints.  */
9793
9794 static int
9795 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9796 {
9797   return target_ranged_break_num_registers ();
9798 }
9799
9800 /* Implement the "print_it" breakpoint_ops method for
9801    ranged breakpoints.  */
9802
9803 static enum print_stop_action
9804 print_it_ranged_breakpoint (bpstat bs)
9805 {
9806   struct breakpoint *b = bs->breakpoint_at;
9807   struct bp_location *bl = b->loc;
9808   struct ui_out *uiout = current_uiout;
9809
9810   gdb_assert (b->type == bp_hardware_breakpoint);
9811
9812   /* Ranged breakpoints have only one location.  */
9813   gdb_assert (bl && bl->next == NULL);
9814
9815   annotate_breakpoint (b->number);
9816
9817   maybe_print_thread_hit_breakpoint (uiout);
9818
9819   if (b->disposition == disp_del)
9820     uiout->text ("Temporary ranged breakpoint ");
9821   else
9822     uiout->text ("Ranged breakpoint ");
9823   if (uiout->is_mi_like_p ())
9824     {
9825       uiout->field_string ("reason",
9826                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9827       uiout->field_string ("disp", bpdisp_text (b->disposition));
9828     }
9829   uiout->field_int ("bkptno", b->number);
9830   uiout->text (", ");
9831
9832   return PRINT_SRC_AND_LOC;
9833 }
9834
9835 /* Implement the "print_one" breakpoint_ops method for
9836    ranged breakpoints.  */
9837
9838 static void
9839 print_one_ranged_breakpoint (struct breakpoint *b,
9840                              struct bp_location **last_loc)
9841 {
9842   struct bp_location *bl = b->loc;
9843   struct value_print_options opts;
9844   struct ui_out *uiout = current_uiout;
9845
9846   /* Ranged breakpoints have only one location.  */
9847   gdb_assert (bl && bl->next == NULL);
9848
9849   get_user_print_options (&opts);
9850
9851   if (opts.addressprint)
9852     /* We don't print the address range here, it will be printed later
9853        by print_one_detail_ranged_breakpoint.  */
9854     uiout->field_skip ("addr");
9855   annotate_field (5);
9856   print_breakpoint_location (b, bl);
9857   *last_loc = bl;
9858 }
9859
9860 /* Implement the "print_one_detail" breakpoint_ops method for
9861    ranged breakpoints.  */
9862
9863 static void
9864 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9865                                     struct ui_out *uiout)
9866 {
9867   CORE_ADDR address_start, address_end;
9868   struct bp_location *bl = b->loc;
9869   string_file stb;
9870
9871   gdb_assert (bl);
9872
9873   address_start = bl->address;
9874   address_end = address_start + bl->length - 1;
9875
9876   uiout->text ("\taddress range: ");
9877   stb.printf ("[%s, %s]",
9878               print_core_address (bl->gdbarch, address_start),
9879               print_core_address (bl->gdbarch, address_end));
9880   uiout->field_stream ("addr", stb);
9881   uiout->text ("\n");
9882 }
9883
9884 /* Implement the "print_mention" breakpoint_ops method for
9885    ranged breakpoints.  */
9886
9887 static void
9888 print_mention_ranged_breakpoint (struct breakpoint *b)
9889 {
9890   struct bp_location *bl = b->loc;
9891   struct ui_out *uiout = current_uiout;
9892
9893   gdb_assert (bl);
9894   gdb_assert (b->type == bp_hardware_breakpoint);
9895
9896   if (uiout->is_mi_like_p ())
9897     return;
9898
9899   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9900                    b->number, paddress (bl->gdbarch, bl->address),
9901                    paddress (bl->gdbarch, bl->address + bl->length - 1));
9902 }
9903
9904 /* Implement the "print_recreate" breakpoint_ops method for
9905    ranged breakpoints.  */
9906
9907 static void
9908 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9909 {
9910   fprintf_unfiltered (fp, "break-range %s, %s",
9911                       event_location_to_string (b->location.get ()),
9912                       event_location_to_string (b->location_range_end.get ()));
9913   print_recreate_thread (b, fp);
9914 }
9915
9916 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9917
9918 static struct breakpoint_ops ranged_breakpoint_ops;
9919
9920 /* Find the address where the end of the breakpoint range should be
9921    placed, given the SAL of the end of the range.  This is so that if
9922    the user provides a line number, the end of the range is set to the
9923    last instruction of the given line.  */
9924
9925 static CORE_ADDR
9926 find_breakpoint_range_end (struct symtab_and_line sal)
9927 {
9928   CORE_ADDR end;
9929
9930   /* If the user provided a PC value, use it.  Otherwise,
9931      find the address of the end of the given location.  */
9932   if (sal.explicit_pc)
9933     end = sal.pc;
9934   else
9935     {
9936       int ret;
9937       CORE_ADDR start;
9938
9939       ret = find_line_pc_range (sal, &start, &end);
9940       if (!ret)
9941         error (_("Could not find location of the end of the range."));
9942
9943       /* find_line_pc_range returns the start of the next line.  */
9944       end--;
9945     }
9946
9947   return end;
9948 }
9949
9950 /* Implement the "break-range" CLI command.  */
9951
9952 static void
9953 break_range_command (char *arg_in, int from_tty)
9954 {
9955   const char *arg = arg_in;
9956   const char *arg_start;
9957   struct linespec_result canonical_start, canonical_end;
9958   int bp_count, can_use_bp, length;
9959   CORE_ADDR end;
9960   struct breakpoint *b;
9961
9962   /* We don't support software ranged breakpoints.  */
9963   if (target_ranged_break_num_registers () < 0)
9964     error (_("This target does not support hardware ranged breakpoints."));
9965
9966   bp_count = hw_breakpoint_used_count ();
9967   bp_count += target_ranged_break_num_registers ();
9968   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9969                                                    bp_count, 0);
9970   if (can_use_bp < 0)
9971     error (_("Hardware breakpoints used exceeds limit."));
9972
9973   arg = skip_spaces (arg);
9974   if (arg == NULL || arg[0] == '\0')
9975     error(_("No address range specified."));
9976
9977   arg_start = arg;
9978   event_location_up start_location = string_to_event_location (&arg,
9979                                                                current_language);
9980   parse_breakpoint_sals (start_location.get (), &canonical_start);
9981
9982   if (arg[0] != ',')
9983     error (_("Too few arguments."));
9984   else if (canonical_start.lsals.empty ())
9985     error (_("Could not find location of the beginning of the range."));
9986
9987   const linespec_sals &lsal_start = canonical_start.lsals[0];
9988
9989   if (canonical_start.lsals.size () > 1
9990       || lsal_start.sals.size () != 1)
9991     error (_("Cannot create a ranged breakpoint with multiple locations."));
9992
9993   const symtab_and_line &sal_start = lsal_start.sals[0];
9994   std::string addr_string_start (arg_start, arg - arg_start);
9995
9996   arg++;        /* Skip the comma.  */
9997   arg = skip_spaces (arg);
9998
9999   /* Parse the end location.  */
10000
10001   arg_start = arg;
10002
10003   /* We call decode_line_full directly here instead of using
10004      parse_breakpoint_sals because we need to specify the start location's
10005      symtab and line as the default symtab and line for the end of the
10006      range.  This makes it possible to have ranges like "foo.c:27, +14",
10007      where +14 means 14 lines from the start location.  */
10008   event_location_up end_location = string_to_event_location (&arg,
10009                                                              current_language);
10010   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
10011                     sal_start.symtab, sal_start.line,
10012                     &canonical_end, NULL, NULL);
10013
10014   if (canonical_end.lsals.empty ())
10015     error (_("Could not find location of the end of the range."));
10016
10017   const linespec_sals &lsal_end = canonical_end.lsals[0];
10018   if (canonical_end.lsals.size () > 1
10019       || lsal_end.sals.size () != 1)
10020     error (_("Cannot create a ranged breakpoint with multiple locations."));
10021
10022   const symtab_and_line &sal_end = lsal_end.sals[0];
10023
10024   end = find_breakpoint_range_end (sal_end);
10025   if (sal_start.pc > end)
10026     error (_("Invalid address range, end precedes start."));
10027
10028   length = end - sal_start.pc + 1;
10029   if (length < 0)
10030     /* Length overflowed.  */
10031     error (_("Address range too large."));
10032   else if (length == 1)
10033     {
10034       /* This range is simple enough to be handled by
10035          the `hbreak' command.  */
10036       hbreak_command (&addr_string_start[0], 1);
10037
10038       return;
10039     }
10040
10041   /* Now set up the breakpoint.  */
10042   b = set_raw_breakpoint (get_current_arch (), sal_start,
10043                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10044   set_breakpoint_count (breakpoint_count + 1);
10045   b->number = breakpoint_count;
10046   b->disposition = disp_donttouch;
10047   b->location = std::move (start_location);
10048   b->location_range_end = std::move (end_location);
10049   b->loc->length = length;
10050
10051   mention (b);
10052   observer_notify_breakpoint_created (b);
10053   update_global_location_list (UGLL_MAY_INSERT);
10054 }
10055
10056 /*  Return non-zero if EXP is verified as constant.  Returned zero
10057     means EXP is variable.  Also the constant detection may fail for
10058     some constant expressions and in such case still falsely return
10059     zero.  */
10060
10061 static int
10062 watchpoint_exp_is_const (const struct expression *exp)
10063 {
10064   int i = exp->nelts;
10065
10066   while (i > 0)
10067     {
10068       int oplenp, argsp;
10069
10070       /* We are only interested in the descriptor of each element.  */
10071       operator_length (exp, i, &oplenp, &argsp);
10072       i -= oplenp;
10073
10074       switch (exp->elts[i].opcode)
10075         {
10076         case BINOP_ADD:
10077         case BINOP_SUB:
10078         case BINOP_MUL:
10079         case BINOP_DIV:
10080         case BINOP_REM:
10081         case BINOP_MOD:
10082         case BINOP_LSH:
10083         case BINOP_RSH:
10084         case BINOP_LOGICAL_AND:
10085         case BINOP_LOGICAL_OR:
10086         case BINOP_BITWISE_AND:
10087         case BINOP_BITWISE_IOR:
10088         case BINOP_BITWISE_XOR:
10089         case BINOP_EQUAL:
10090         case BINOP_NOTEQUAL:
10091         case BINOP_LESS:
10092         case BINOP_GTR:
10093         case BINOP_LEQ:
10094         case BINOP_GEQ:
10095         case BINOP_REPEAT:
10096         case BINOP_COMMA:
10097         case BINOP_EXP:
10098         case BINOP_MIN:
10099         case BINOP_MAX:
10100         case BINOP_INTDIV:
10101         case BINOP_CONCAT:
10102         case TERNOP_COND:
10103         case TERNOP_SLICE:
10104
10105         case OP_LONG:
10106         case OP_FLOAT:
10107         case OP_LAST:
10108         case OP_COMPLEX:
10109         case OP_STRING:
10110         case OP_ARRAY:
10111         case OP_TYPE:
10112         case OP_TYPEOF:
10113         case OP_DECLTYPE:
10114         case OP_TYPEID:
10115         case OP_NAME:
10116         case OP_OBJC_NSSTRING:
10117
10118         case UNOP_NEG:
10119         case UNOP_LOGICAL_NOT:
10120         case UNOP_COMPLEMENT:
10121         case UNOP_ADDR:
10122         case UNOP_HIGH:
10123         case UNOP_CAST:
10124
10125         case UNOP_CAST_TYPE:
10126         case UNOP_REINTERPRET_CAST:
10127         case UNOP_DYNAMIC_CAST:
10128           /* Unary, binary and ternary operators: We have to check
10129              their operands.  If they are constant, then so is the
10130              result of that operation.  For instance, if A and B are
10131              determined to be constants, then so is "A + B".
10132
10133              UNOP_IND is one exception to the rule above, because the
10134              value of *ADDR is not necessarily a constant, even when
10135              ADDR is.  */
10136           break;
10137
10138         case OP_VAR_VALUE:
10139           /* Check whether the associated symbol is a constant.
10140
10141              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10142              possible that a buggy compiler could mark a variable as
10143              constant even when it is not, and TYPE_CONST would return
10144              true in this case, while SYMBOL_CLASS wouldn't.
10145
10146              We also have to check for function symbols because they
10147              are always constant.  */
10148           {
10149             struct symbol *s = exp->elts[i + 2].symbol;
10150
10151             if (SYMBOL_CLASS (s) != LOC_BLOCK
10152                 && SYMBOL_CLASS (s) != LOC_CONST
10153                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10154               return 0;
10155             break;
10156           }
10157
10158         /* The default action is to return 0 because we are using
10159            the optimistic approach here: If we don't know something,
10160            then it is not a constant.  */
10161         default:
10162           return 0;
10163         }
10164     }
10165
10166   return 1;
10167 }
10168
10169 /* Watchpoint destructor.  */
10170
10171 watchpoint::~watchpoint ()
10172 {
10173   xfree (this->exp_string);
10174   xfree (this->exp_string_reparse);
10175   value_free (this->val);
10176 }
10177
10178 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10179
10180 static void
10181 re_set_watchpoint (struct breakpoint *b)
10182 {
10183   struct watchpoint *w = (struct watchpoint *) b;
10184
10185   /* Watchpoint can be either on expression using entirely global
10186      variables, or it can be on local variables.
10187
10188      Watchpoints of the first kind are never auto-deleted, and even
10189      persist across program restarts.  Since they can use variables
10190      from shared libraries, we need to reparse expression as libraries
10191      are loaded and unloaded.
10192
10193      Watchpoints on local variables can also change meaning as result
10194      of solib event.  For example, if a watchpoint uses both a local
10195      and a global variables in expression, it's a local watchpoint,
10196      but unloading of a shared library will make the expression
10197      invalid.  This is not a very common use case, but we still
10198      re-evaluate expression, to avoid surprises to the user.
10199
10200      Note that for local watchpoints, we re-evaluate it only if
10201      watchpoints frame id is still valid.  If it's not, it means the
10202      watchpoint is out of scope and will be deleted soon.  In fact,
10203      I'm not sure we'll ever be called in this case.
10204
10205      If a local watchpoint's frame id is still valid, then
10206      w->exp_valid_block is likewise valid, and we can safely use it.
10207
10208      Don't do anything about disabled watchpoints, since they will be
10209      reevaluated again when enabled.  */
10210   update_watchpoint (w, 1 /* reparse */);
10211 }
10212
10213 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10214
10215 static int
10216 insert_watchpoint (struct bp_location *bl)
10217 {
10218   struct watchpoint *w = (struct watchpoint *) bl->owner;
10219   int length = w->exact ? 1 : bl->length;
10220
10221   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10222                                    w->cond_exp.get ());
10223 }
10224
10225 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10226
10227 static int
10228 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10229 {
10230   struct watchpoint *w = (struct watchpoint *) bl->owner;
10231   int length = w->exact ? 1 : bl->length;
10232
10233   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10234                                    w->cond_exp.get ());
10235 }
10236
10237 static int
10238 breakpoint_hit_watchpoint (const struct bp_location *bl,
10239                            const address_space *aspace, CORE_ADDR bp_addr,
10240                            const struct target_waitstatus *ws)
10241 {
10242   struct breakpoint *b = bl->owner;
10243   struct watchpoint *w = (struct watchpoint *) b;
10244
10245   /* Continuable hardware watchpoints are treated as non-existent if the
10246      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10247      some data address).  Otherwise gdb won't stop on a break instruction
10248      in the code (not from a breakpoint) when a hardware watchpoint has
10249      been defined.  Also skip watchpoints which we know did not trigger
10250      (did not match the data address).  */
10251   if (is_hardware_watchpoint (b)
10252       && w->watchpoint_triggered == watch_triggered_no)
10253     return 0;
10254
10255   return 1;
10256 }
10257
10258 static void
10259 check_status_watchpoint (bpstat bs)
10260 {
10261   gdb_assert (is_watchpoint (bs->breakpoint_at));
10262
10263   bpstat_check_watchpoint (bs);
10264 }
10265
10266 /* Implement the "resources_needed" breakpoint_ops method for
10267    hardware watchpoints.  */
10268
10269 static int
10270 resources_needed_watchpoint (const struct bp_location *bl)
10271 {
10272   struct watchpoint *w = (struct watchpoint *) bl->owner;
10273   int length = w->exact? 1 : bl->length;
10274
10275   return target_region_ok_for_hw_watchpoint (bl->address, length);
10276 }
10277
10278 /* Implement the "works_in_software_mode" breakpoint_ops method for
10279    hardware watchpoints.  */
10280
10281 static int
10282 works_in_software_mode_watchpoint (const struct breakpoint *b)
10283 {
10284   /* Read and access watchpoints only work with hardware support.  */
10285   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10286 }
10287
10288 static enum print_stop_action
10289 print_it_watchpoint (bpstat bs)
10290 {
10291   struct breakpoint *b;
10292   enum print_stop_action result;
10293   struct watchpoint *w;
10294   struct ui_out *uiout = current_uiout;
10295
10296   gdb_assert (bs->bp_location_at != NULL);
10297
10298   b = bs->breakpoint_at;
10299   w = (struct watchpoint *) b;
10300
10301   annotate_watchpoint (b->number);
10302   maybe_print_thread_hit_breakpoint (uiout);
10303
10304   string_file stb;
10305
10306   gdb::optional<ui_out_emit_tuple> tuple_emitter;
10307   switch (b->type)
10308     {
10309     case bp_watchpoint:
10310     case bp_hardware_watchpoint:
10311       if (uiout->is_mi_like_p ())
10312         uiout->field_string
10313           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10314       mention (b);
10315       tuple_emitter.emplace (uiout, "value");
10316       uiout->text ("\nOld value = ");
10317       watchpoint_value_print (bs->old_val, &stb);
10318       uiout->field_stream ("old", stb);
10319       uiout->text ("\nNew value = ");
10320       watchpoint_value_print (w->val, &stb);
10321       uiout->field_stream ("new", stb);
10322       uiout->text ("\n");
10323       /* More than one watchpoint may have been triggered.  */
10324       result = PRINT_UNKNOWN;
10325       break;
10326
10327     case bp_read_watchpoint:
10328       if (uiout->is_mi_like_p ())
10329         uiout->field_string
10330           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10331       mention (b);
10332       tuple_emitter.emplace (uiout, "value");
10333       uiout->text ("\nValue = ");
10334       watchpoint_value_print (w->val, &stb);
10335       uiout->field_stream ("value", stb);
10336       uiout->text ("\n");
10337       result = PRINT_UNKNOWN;
10338       break;
10339
10340     case bp_access_watchpoint:
10341       if (bs->old_val != NULL)
10342         {
10343           if (uiout->is_mi_like_p ())
10344             uiout->field_string
10345               ("reason",
10346                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10347           mention (b);
10348           tuple_emitter.emplace (uiout, "value");
10349           uiout->text ("\nOld value = ");
10350           watchpoint_value_print (bs->old_val, &stb);
10351           uiout->field_stream ("old", stb);
10352           uiout->text ("\nNew value = ");
10353         }
10354       else
10355         {
10356           mention (b);
10357           if (uiout->is_mi_like_p ())
10358             uiout->field_string
10359               ("reason",
10360                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10361           tuple_emitter.emplace (uiout, "value");
10362           uiout->text ("\nValue = ");
10363         }
10364       watchpoint_value_print (w->val, &stb);
10365       uiout->field_stream ("new", stb);
10366       uiout->text ("\n");
10367       result = PRINT_UNKNOWN;
10368       break;
10369     default:
10370       result = PRINT_UNKNOWN;
10371     }
10372
10373   return result;
10374 }
10375
10376 /* Implement the "print_mention" breakpoint_ops method for hardware
10377    watchpoints.  */
10378
10379 static void
10380 print_mention_watchpoint (struct breakpoint *b)
10381 {
10382   struct watchpoint *w = (struct watchpoint *) b;
10383   struct ui_out *uiout = current_uiout;
10384   const char *tuple_name;
10385
10386   switch (b->type)
10387     {
10388     case bp_watchpoint:
10389       uiout->text ("Watchpoint ");
10390       tuple_name = "wpt";
10391       break;
10392     case bp_hardware_watchpoint:
10393       uiout->text ("Hardware watchpoint ");
10394       tuple_name = "wpt";
10395       break;
10396     case bp_read_watchpoint:
10397       uiout->text ("Hardware read watchpoint ");
10398       tuple_name = "hw-rwpt";
10399       break;
10400     case bp_access_watchpoint:
10401       uiout->text ("Hardware access (read/write) watchpoint ");
10402       tuple_name = "hw-awpt";
10403       break;
10404     default:
10405       internal_error (__FILE__, __LINE__,
10406                       _("Invalid hardware watchpoint type."));
10407     }
10408
10409   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10410   uiout->field_int ("number", b->number);
10411   uiout->text (": ");
10412   uiout->field_string ("exp", w->exp_string);
10413 }
10414
10415 /* Implement the "print_recreate" breakpoint_ops method for
10416    watchpoints.  */
10417
10418 static void
10419 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10420 {
10421   struct watchpoint *w = (struct watchpoint *) b;
10422
10423   switch (b->type)
10424     {
10425     case bp_watchpoint:
10426     case bp_hardware_watchpoint:
10427       fprintf_unfiltered (fp, "watch");
10428       break;
10429     case bp_read_watchpoint:
10430       fprintf_unfiltered (fp, "rwatch");
10431       break;
10432     case bp_access_watchpoint:
10433       fprintf_unfiltered (fp, "awatch");
10434       break;
10435     default:
10436       internal_error (__FILE__, __LINE__,
10437                       _("Invalid watchpoint type."));
10438     }
10439
10440   fprintf_unfiltered (fp, " %s", w->exp_string);
10441   print_recreate_thread (b, fp);
10442 }
10443
10444 /* Implement the "explains_signal" breakpoint_ops method for
10445    watchpoints.  */
10446
10447 static int
10448 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10449 {
10450   /* A software watchpoint cannot cause a signal other than
10451      GDB_SIGNAL_TRAP.  */
10452   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10453     return 0;
10454
10455   return 1;
10456 }
10457
10458 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10459
10460 static struct breakpoint_ops watchpoint_breakpoint_ops;
10461
10462 /* Implement the "insert" breakpoint_ops method for
10463    masked hardware watchpoints.  */
10464
10465 static int
10466 insert_masked_watchpoint (struct bp_location *bl)
10467 {
10468   struct watchpoint *w = (struct watchpoint *) bl->owner;
10469
10470   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10471                                         bl->watchpoint_type);
10472 }
10473
10474 /* Implement the "remove" breakpoint_ops method for
10475    masked hardware watchpoints.  */
10476
10477 static int
10478 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10479 {
10480   struct watchpoint *w = (struct watchpoint *) bl->owner;
10481
10482   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10483                                         bl->watchpoint_type);
10484 }
10485
10486 /* Implement the "resources_needed" breakpoint_ops method for
10487    masked hardware watchpoints.  */
10488
10489 static int
10490 resources_needed_masked_watchpoint (const struct bp_location *bl)
10491 {
10492   struct watchpoint *w = (struct watchpoint *) bl->owner;
10493
10494   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10495 }
10496
10497 /* Implement the "works_in_software_mode" breakpoint_ops method for
10498    masked hardware watchpoints.  */
10499
10500 static int
10501 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10502 {
10503   return 0;
10504 }
10505
10506 /* Implement the "print_it" breakpoint_ops method for
10507    masked hardware watchpoints.  */
10508
10509 static enum print_stop_action
10510 print_it_masked_watchpoint (bpstat bs)
10511 {
10512   struct breakpoint *b = bs->breakpoint_at;
10513   struct ui_out *uiout = current_uiout;
10514
10515   /* Masked watchpoints have only one location.  */
10516   gdb_assert (b->loc && b->loc->next == NULL);
10517
10518   annotate_watchpoint (b->number);
10519   maybe_print_thread_hit_breakpoint (uiout);
10520
10521   switch (b->type)
10522     {
10523     case bp_hardware_watchpoint:
10524       if (uiout->is_mi_like_p ())
10525         uiout->field_string
10526           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10527       break;
10528
10529     case bp_read_watchpoint:
10530       if (uiout->is_mi_like_p ())
10531         uiout->field_string
10532           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10533       break;
10534
10535     case bp_access_watchpoint:
10536       if (uiout->is_mi_like_p ())
10537         uiout->field_string
10538           ("reason",
10539            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10540       break;
10541     default:
10542       internal_error (__FILE__, __LINE__,
10543                       _("Invalid hardware watchpoint type."));
10544     }
10545
10546   mention (b);
10547   uiout->text (_("\n\
10548 Check the underlying instruction at PC for the memory\n\
10549 address and value which triggered this watchpoint.\n"));
10550   uiout->text ("\n");
10551
10552   /* More than one watchpoint may have been triggered.  */
10553   return PRINT_UNKNOWN;
10554 }
10555
10556 /* Implement the "print_one_detail" breakpoint_ops method for
10557    masked hardware watchpoints.  */
10558
10559 static void
10560 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10561                                     struct ui_out *uiout)
10562 {
10563   struct watchpoint *w = (struct watchpoint *) b;
10564
10565   /* Masked watchpoints have only one location.  */
10566   gdb_assert (b->loc && b->loc->next == NULL);
10567
10568   uiout->text ("\tmask ");
10569   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10570   uiout->text ("\n");
10571 }
10572
10573 /* Implement the "print_mention" breakpoint_ops method for
10574    masked hardware watchpoints.  */
10575
10576 static void
10577 print_mention_masked_watchpoint (struct breakpoint *b)
10578 {
10579   struct watchpoint *w = (struct watchpoint *) b;
10580   struct ui_out *uiout = current_uiout;
10581   const char *tuple_name;
10582
10583   switch (b->type)
10584     {
10585     case bp_hardware_watchpoint:
10586       uiout->text ("Masked hardware watchpoint ");
10587       tuple_name = "wpt";
10588       break;
10589     case bp_read_watchpoint:
10590       uiout->text ("Masked hardware read watchpoint ");
10591       tuple_name = "hw-rwpt";
10592       break;
10593     case bp_access_watchpoint:
10594       uiout->text ("Masked hardware access (read/write) watchpoint ");
10595       tuple_name = "hw-awpt";
10596       break;
10597     default:
10598       internal_error (__FILE__, __LINE__,
10599                       _("Invalid hardware watchpoint type."));
10600     }
10601
10602   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10603   uiout->field_int ("number", b->number);
10604   uiout->text (": ");
10605   uiout->field_string ("exp", w->exp_string);
10606 }
10607
10608 /* Implement the "print_recreate" breakpoint_ops method for
10609    masked hardware watchpoints.  */
10610
10611 static void
10612 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10613 {
10614   struct watchpoint *w = (struct watchpoint *) b;
10615   char tmp[40];
10616
10617   switch (b->type)
10618     {
10619     case bp_hardware_watchpoint:
10620       fprintf_unfiltered (fp, "watch");
10621       break;
10622     case bp_read_watchpoint:
10623       fprintf_unfiltered (fp, "rwatch");
10624       break;
10625     case bp_access_watchpoint:
10626       fprintf_unfiltered (fp, "awatch");
10627       break;
10628     default:
10629       internal_error (__FILE__, __LINE__,
10630                       _("Invalid hardware watchpoint type."));
10631     }
10632
10633   sprintf_vma (tmp, w->hw_wp_mask);
10634   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10635   print_recreate_thread (b, fp);
10636 }
10637
10638 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10639
10640 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10641
10642 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10643
10644 static int
10645 is_masked_watchpoint (const struct breakpoint *b)
10646 {
10647   return b->ops == &masked_watchpoint_breakpoint_ops;
10648 }
10649
10650 /* accessflag:  hw_write:  watch write, 
10651                 hw_read:   watch read, 
10652                 hw_access: watch access (read or write) */
10653 static void
10654 watch_command_1 (const char *arg, int accessflag, int from_tty,
10655                  int just_location, int internal)
10656 {
10657   struct breakpoint *scope_breakpoint = NULL;
10658   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10659   struct value *val, *mark, *result;
10660   int saved_bitpos = 0, saved_bitsize = 0;
10661   const char *exp_start = NULL;
10662   const char *exp_end = NULL;
10663   const char *tok, *end_tok;
10664   int toklen = -1;
10665   const char *cond_start = NULL;
10666   const char *cond_end = NULL;
10667   enum bptype bp_type;
10668   int thread = -1;
10669   int pc = 0;
10670   /* Flag to indicate whether we are going to use masks for
10671      the hardware watchpoint.  */
10672   int use_mask = 0;
10673   CORE_ADDR mask = 0;
10674
10675   /* Make sure that we actually have parameters to parse.  */
10676   if (arg != NULL && arg[0] != '\0')
10677     {
10678       const char *value_start;
10679
10680       exp_end = arg + strlen (arg);
10681
10682       /* Look for "parameter value" pairs at the end
10683          of the arguments string.  */
10684       for (tok = exp_end - 1; tok > arg; tok--)
10685         {
10686           /* Skip whitespace at the end of the argument list.  */
10687           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10688             tok--;
10689
10690           /* Find the beginning of the last token.
10691              This is the value of the parameter.  */
10692           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10693             tok--;
10694           value_start = tok + 1;
10695
10696           /* Skip whitespace.  */
10697           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10698             tok--;
10699
10700           end_tok = tok;
10701
10702           /* Find the beginning of the second to last token.
10703              This is the parameter itself.  */
10704           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10705             tok--;
10706           tok++;
10707           toklen = end_tok - tok + 1;
10708
10709           if (toklen == 6 && startswith (tok, "thread"))
10710             {
10711               struct thread_info *thr;
10712               /* At this point we've found a "thread" token, which means
10713                  the user is trying to set a watchpoint that triggers
10714                  only in a specific thread.  */
10715               const char *endp;
10716
10717               if (thread != -1)
10718                 error(_("You can specify only one thread."));
10719
10720               /* Extract the thread ID from the next token.  */
10721               thr = parse_thread_id (value_start, &endp);
10722
10723               /* Check if the user provided a valid thread ID.  */
10724               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10725                 invalid_thread_id_error (value_start);
10726
10727               thread = thr->global_num;
10728             }
10729           else if (toklen == 4 && startswith (tok, "mask"))
10730             {
10731               /* We've found a "mask" token, which means the user wants to
10732                  create a hardware watchpoint that is going to have the mask
10733                  facility.  */
10734               struct value *mask_value, *mark;
10735
10736               if (use_mask)
10737                 error(_("You can specify only one mask."));
10738
10739               use_mask = just_location = 1;
10740
10741               mark = value_mark ();
10742               mask_value = parse_to_comma_and_eval (&value_start);
10743               mask = value_as_address (mask_value);
10744               value_free_to_mark (mark);
10745             }
10746           else
10747             /* We didn't recognize what we found.  We should stop here.  */
10748             break;
10749
10750           /* Truncate the string and get rid of the "parameter value" pair before
10751              the arguments string is parsed by the parse_exp_1 function.  */
10752           exp_end = tok;
10753         }
10754     }
10755   else
10756     exp_end = arg;
10757
10758   /* Parse the rest of the arguments.  From here on out, everything
10759      is in terms of a newly allocated string instead of the original
10760      ARG.  */
10761   innermost_block = NULL;
10762   std::string expression (arg, exp_end - arg);
10763   exp_start = arg = expression.c_str ();
10764   expression_up exp = parse_exp_1 (&arg, 0, 0, 0);
10765   exp_end = arg;
10766   /* Remove trailing whitespace from the expression before saving it.
10767      This makes the eventual display of the expression string a bit
10768      prettier.  */
10769   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10770     --exp_end;
10771
10772   /* Checking if the expression is not constant.  */
10773   if (watchpoint_exp_is_const (exp.get ()))
10774     {
10775       int len;
10776
10777       len = exp_end - exp_start;
10778       while (len > 0 && isspace (exp_start[len - 1]))
10779         len--;
10780       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10781     }
10782
10783   exp_valid_block = innermost_block;
10784   mark = value_mark ();
10785   fetch_subexp_value (exp.get (), &pc, &val, &result, NULL, just_location);
10786
10787   if (val != NULL && just_location)
10788     {
10789       saved_bitpos = value_bitpos (val);
10790       saved_bitsize = value_bitsize (val);
10791     }
10792
10793   if (just_location)
10794     {
10795       int ret;
10796
10797       exp_valid_block = NULL;
10798       val = value_addr (result);
10799       release_value (val);
10800       value_free_to_mark (mark);
10801
10802       if (use_mask)
10803         {
10804           ret = target_masked_watch_num_registers (value_as_address (val),
10805                                                    mask);
10806           if (ret == -1)
10807             error (_("This target does not support masked watchpoints."));
10808           else if (ret == -2)
10809             error (_("Invalid mask or memory region."));
10810         }
10811     }
10812   else if (val != NULL)
10813     release_value (val);
10814
10815   tok = skip_spaces (arg);
10816   end_tok = skip_to_space (tok);
10817
10818   toklen = end_tok - tok;
10819   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10820     {
10821       innermost_block = NULL;
10822       tok = cond_start = end_tok + 1;
10823       parse_exp_1 (&tok, 0, 0, 0);
10824
10825       /* The watchpoint expression may not be local, but the condition
10826          may still be.  E.g.: `watch global if local > 0'.  */
10827       cond_exp_valid_block = innermost_block;
10828
10829       cond_end = tok;
10830     }
10831   if (*tok)
10832     error (_("Junk at end of command."));
10833
10834   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
10835
10836   /* Save this because create_internal_breakpoint below invalidates
10837      'wp_frame'.  */
10838   frame_id watchpoint_frame = get_frame_id (wp_frame);
10839
10840   /* If the expression is "local", then set up a "watchpoint scope"
10841      breakpoint at the point where we've left the scope of the watchpoint
10842      expression.  Create the scope breakpoint before the watchpoint, so
10843      that we will encounter it first in bpstat_stop_status.  */
10844   if (exp_valid_block != NULL && wp_frame != NULL)
10845     {
10846       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10847
10848       if (frame_id_p (caller_frame_id))
10849         {
10850           gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10851           CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10852
10853           scope_breakpoint
10854             = create_internal_breakpoint (caller_arch, caller_pc,
10855                                           bp_watchpoint_scope,
10856                                           &momentary_breakpoint_ops);
10857
10858           /* create_internal_breakpoint could invalidate WP_FRAME.  */
10859           wp_frame = NULL;
10860
10861           scope_breakpoint->enable_state = bp_enabled;
10862
10863           /* Automatically delete the breakpoint when it hits.  */
10864           scope_breakpoint->disposition = disp_del;
10865
10866           /* Only break in the proper frame (help with recursion).  */
10867           scope_breakpoint->frame_id = caller_frame_id;
10868
10869           /* Set the address at which we will stop.  */
10870           scope_breakpoint->loc->gdbarch = caller_arch;
10871           scope_breakpoint->loc->requested_address = caller_pc;
10872           scope_breakpoint->loc->address
10873             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10874                                          scope_breakpoint->loc->requested_address,
10875                                          scope_breakpoint->type);
10876         }
10877     }
10878
10879   /* Now set up the breakpoint.  We create all watchpoints as hardware
10880      watchpoints here even if hardware watchpoints are turned off, a call
10881      to update_watchpoint later in this function will cause the type to
10882      drop back to bp_watchpoint (software watchpoint) if required.  */
10883
10884   if (accessflag == hw_read)
10885     bp_type = bp_read_watchpoint;
10886   else if (accessflag == hw_access)
10887     bp_type = bp_access_watchpoint;
10888   else
10889     bp_type = bp_hardware_watchpoint;
10890
10891   std::unique_ptr<watchpoint> w (new watchpoint ());
10892
10893   if (use_mask)
10894     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10895                                           &masked_watchpoint_breakpoint_ops);
10896   else
10897     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10898                                           &watchpoint_breakpoint_ops);
10899   w->thread = thread;
10900   w->disposition = disp_donttouch;
10901   w->pspace = current_program_space;
10902   w->exp = std::move (exp);
10903   w->exp_valid_block = exp_valid_block;
10904   w->cond_exp_valid_block = cond_exp_valid_block;
10905   if (just_location)
10906     {
10907       struct type *t = value_type (val);
10908       CORE_ADDR addr = value_as_address (val);
10909
10910       w->exp_string_reparse
10911         = current_language->la_watch_location_expression (t, addr).release ();
10912
10913       w->exp_string = xstrprintf ("-location %.*s",
10914                                   (int) (exp_end - exp_start), exp_start);
10915     }
10916   else
10917     w->exp_string = savestring (exp_start, exp_end - exp_start);
10918
10919   if (use_mask)
10920     {
10921       w->hw_wp_mask = mask;
10922     }
10923   else
10924     {
10925       w->val = val;
10926       w->val_bitpos = saved_bitpos;
10927       w->val_bitsize = saved_bitsize;
10928       w->val_valid = 1;
10929     }
10930
10931   if (cond_start)
10932     w->cond_string = savestring (cond_start, cond_end - cond_start);
10933   else
10934     w->cond_string = 0;
10935
10936   if (frame_id_p (watchpoint_frame))
10937     {
10938       w->watchpoint_frame = watchpoint_frame;
10939       w->watchpoint_thread = inferior_ptid;
10940     }
10941   else
10942     {
10943       w->watchpoint_frame = null_frame_id;
10944       w->watchpoint_thread = null_ptid;
10945     }
10946
10947   if (scope_breakpoint != NULL)
10948     {
10949       /* The scope breakpoint is related to the watchpoint.  We will
10950          need to act on them together.  */
10951       w->related_breakpoint = scope_breakpoint;
10952       scope_breakpoint->related_breakpoint = w.get ();
10953     }
10954
10955   if (!just_location)
10956     value_free_to_mark (mark);
10957
10958   /* Finally update the new watchpoint.  This creates the locations
10959      that should be inserted.  */
10960   update_watchpoint (w.get (), 1);
10961
10962   install_breakpoint (internal, std::move (w), 1);
10963 }
10964
10965 /* Return count of debug registers needed to watch the given expression.
10966    If the watchpoint cannot be handled in hardware return zero.  */
10967
10968 static int
10969 can_use_hardware_watchpoint (struct value *v)
10970 {
10971   int found_memory_cnt = 0;
10972   struct value *head = v;
10973
10974   /* Did the user specifically forbid us to use hardware watchpoints? */
10975   if (!can_use_hw_watchpoints)
10976     return 0;
10977
10978   /* Make sure that the value of the expression depends only upon
10979      memory contents, and values computed from them within GDB.  If we
10980      find any register references or function calls, we can't use a
10981      hardware watchpoint.
10982
10983      The idea here is that evaluating an expression generates a series
10984      of values, one holding the value of every subexpression.  (The
10985      expression a*b+c has five subexpressions: a, b, a*b, c, and
10986      a*b+c.)  GDB's values hold almost enough information to establish
10987      the criteria given above --- they identify memory lvalues,
10988      register lvalues, computed values, etcetera.  So we can evaluate
10989      the expression, and then scan the chain of values that leaves
10990      behind to decide whether we can detect any possible change to the
10991      expression's final value using only hardware watchpoints.
10992
10993      However, I don't think that the values returned by inferior
10994      function calls are special in any way.  So this function may not
10995      notice that an expression involving an inferior function call
10996      can't be watched with hardware watchpoints.  FIXME.  */
10997   for (; v; v = value_next (v))
10998     {
10999       if (VALUE_LVAL (v) == lval_memory)
11000         {
11001           if (v != head && value_lazy (v))
11002             /* A lazy memory lvalue in the chain is one that GDB never
11003                needed to fetch; we either just used its address (e.g.,
11004                `a' in `a.b') or we never needed it at all (e.g., `a'
11005                in `a,b').  This doesn't apply to HEAD; if that is
11006                lazy then it was not readable, but watch it anyway.  */
11007             ;
11008           else
11009             {
11010               /* Ahh, memory we actually used!  Check if we can cover
11011                  it with hardware watchpoints.  */
11012               struct type *vtype = check_typedef (value_type (v));
11013
11014               /* We only watch structs and arrays if user asked for it
11015                  explicitly, never if they just happen to appear in a
11016                  middle of some value chain.  */
11017               if (v == head
11018                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11019                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11020                 {
11021                   CORE_ADDR vaddr = value_address (v);
11022                   int len;
11023                   int num_regs;
11024
11025                   len = (target_exact_watchpoints
11026                          && is_scalar_type_recursive (vtype))?
11027                     1 : TYPE_LENGTH (value_type (v));
11028
11029                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11030                   if (!num_regs)
11031                     return 0;
11032                   else
11033                     found_memory_cnt += num_regs;
11034                 }
11035             }
11036         }
11037       else if (VALUE_LVAL (v) != not_lval
11038                && deprecated_value_modifiable (v) == 0)
11039         return 0;       /* These are values from the history (e.g., $1).  */
11040       else if (VALUE_LVAL (v) == lval_register)
11041         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11042     }
11043
11044   /* The expression itself looks suitable for using a hardware
11045      watchpoint, but give the target machine a chance to reject it.  */
11046   return found_memory_cnt;
11047 }
11048
11049 void
11050 watch_command_wrapper (const char *arg, int from_tty, int internal)
11051 {
11052   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11053 }
11054
11055 /* A helper function that looks for the "-location" argument and then
11056    calls watch_command_1.  */
11057
11058 static void
11059 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11060 {
11061   int just_location = 0;
11062
11063   if (arg
11064       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11065           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11066     {
11067       arg = skip_spaces (arg);
11068       just_location = 1;
11069     }
11070
11071   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11072 }
11073
11074 static void
11075 watch_command (char *arg, int from_tty)
11076 {
11077   watch_maybe_just_location (arg, hw_write, from_tty);
11078 }
11079
11080 void
11081 rwatch_command_wrapper (const char *arg, int from_tty, int internal)
11082 {
11083   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11084 }
11085
11086 static void
11087 rwatch_command (char *arg, int from_tty)
11088 {
11089   watch_maybe_just_location (arg, hw_read, from_tty);
11090 }
11091
11092 void
11093 awatch_command_wrapper (const char *arg, int from_tty, int internal)
11094 {
11095   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11096 }
11097
11098 static void
11099 awatch_command (char *arg, int from_tty)
11100 {
11101   watch_maybe_just_location (arg, hw_access, from_tty);
11102 }
11103 \f
11104
11105 /* Data for the FSM that manages the until(location)/advance commands
11106    in infcmd.c.  Here because it uses the mechanisms of
11107    breakpoints.  */
11108
11109 struct until_break_fsm
11110 {
11111   /* The base class.  */
11112   struct thread_fsm thread_fsm;
11113
11114   /* The thread that as current when the command was executed.  */
11115   int thread;
11116
11117   /* The breakpoint set at the destination location.  */
11118   struct breakpoint *location_breakpoint;
11119
11120   /* Breakpoint set at the return address in the caller frame.  May be
11121      NULL.  */
11122   struct breakpoint *caller_breakpoint;
11123 };
11124
11125 static void until_break_fsm_clean_up (struct thread_fsm *self,
11126                                       struct thread_info *thread);
11127 static int until_break_fsm_should_stop (struct thread_fsm *self,
11128                                         struct thread_info *thread);
11129 static enum async_reply_reason
11130   until_break_fsm_async_reply_reason (struct thread_fsm *self);
11131
11132 /* until_break_fsm's vtable.  */
11133
11134 static struct thread_fsm_ops until_break_fsm_ops =
11135 {
11136   NULL, /* dtor */
11137   until_break_fsm_clean_up,
11138   until_break_fsm_should_stop,
11139   NULL, /* return_value */
11140   until_break_fsm_async_reply_reason,
11141 };
11142
11143 /* Allocate a new until_break_command_fsm.  */
11144
11145 static struct until_break_fsm *
11146 new_until_break_fsm (struct interp *cmd_interp, int thread,
11147                      breakpoint_up &&location_breakpoint,
11148                      breakpoint_up &&caller_breakpoint)
11149 {
11150   struct until_break_fsm *sm;
11151
11152   sm = XCNEW (struct until_break_fsm);
11153   thread_fsm_ctor (&sm->thread_fsm, &until_break_fsm_ops, cmd_interp);
11154
11155   sm->thread = thread;
11156   sm->location_breakpoint = location_breakpoint.release ();
11157   sm->caller_breakpoint = caller_breakpoint.release ();
11158
11159   return sm;
11160 }
11161
11162 /* Implementation of the 'should_stop' FSM method for the
11163    until(location)/advance commands.  */
11164
11165 static int
11166 until_break_fsm_should_stop (struct thread_fsm *self,
11167                              struct thread_info *tp)
11168 {
11169   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11170
11171   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11172                               sm->location_breakpoint) != NULL
11173       || (sm->caller_breakpoint != NULL
11174           && bpstat_find_breakpoint (tp->control.stop_bpstat,
11175                                      sm->caller_breakpoint) != NULL))
11176     thread_fsm_set_finished (self);
11177
11178   return 1;
11179 }
11180
11181 /* Implementation of the 'clean_up' FSM method for the
11182    until(location)/advance commands.  */
11183
11184 static void
11185 until_break_fsm_clean_up (struct thread_fsm *self,
11186                           struct thread_info *thread)
11187 {
11188   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11189
11190   /* Clean up our temporary breakpoints.  */
11191   if (sm->location_breakpoint != NULL)
11192     {
11193       delete_breakpoint (sm->location_breakpoint);
11194       sm->location_breakpoint = NULL;
11195     }
11196   if (sm->caller_breakpoint != NULL)
11197     {
11198       delete_breakpoint (sm->caller_breakpoint);
11199       sm->caller_breakpoint = NULL;
11200     }
11201   delete_longjmp_breakpoint (sm->thread);
11202 }
11203
11204 /* Implementation of the 'async_reply_reason' FSM method for the
11205    until(location)/advance commands.  */
11206
11207 static enum async_reply_reason
11208 until_break_fsm_async_reply_reason (struct thread_fsm *self)
11209 {
11210   return EXEC_ASYNC_LOCATION_REACHED;
11211 }
11212
11213 void
11214 until_break_command (const char *arg, int from_tty, int anywhere)
11215 {
11216   struct frame_info *frame;
11217   struct gdbarch *frame_gdbarch;
11218   struct frame_id stack_frame_id;
11219   struct frame_id caller_frame_id;
11220   struct cleanup *old_chain;
11221   int thread;
11222   struct thread_info *tp;
11223   struct until_break_fsm *sm;
11224
11225   clear_proceed_status (0);
11226
11227   /* Set a breakpoint where the user wants it and at return from
11228      this function.  */
11229
11230   event_location_up location = string_to_event_location (&arg, current_language);
11231
11232   std::vector<symtab_and_line> sals
11233     = (last_displayed_sal_is_valid ()
11234        ? decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
11235                         get_last_displayed_symtab (),
11236                         get_last_displayed_line ())
11237        : decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
11238                         NULL, (struct symtab *) NULL, 0));
11239
11240   if (sals.size () != 1)
11241     error (_("Couldn't get information on specified line."));
11242
11243   symtab_and_line &sal = sals[0];
11244
11245   if (*arg)
11246     error (_("Junk at end of arguments."));
11247
11248   resolve_sal_pc (&sal);
11249
11250   tp = inferior_thread ();
11251   thread = tp->global_num;
11252
11253   old_chain = make_cleanup (null_cleanup, NULL);
11254
11255   /* Note linespec handling above invalidates the frame chain.
11256      Installing a breakpoint also invalidates the frame chain (as it
11257      may need to switch threads), so do any frame handling before
11258      that.  */
11259
11260   frame = get_selected_frame (NULL);
11261   frame_gdbarch = get_frame_arch (frame);
11262   stack_frame_id = get_stack_frame_id (frame);
11263   caller_frame_id = frame_unwind_caller_id (frame);
11264
11265   /* Keep within the current frame, or in frames called by the current
11266      one.  */
11267
11268   breakpoint_up caller_breakpoint;
11269   if (frame_id_p (caller_frame_id))
11270     {
11271       struct symtab_and_line sal2;
11272       struct gdbarch *caller_gdbarch;
11273
11274       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11275       sal2.pc = frame_unwind_caller_pc (frame);
11276       caller_gdbarch = frame_unwind_caller_arch (frame);
11277       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11278                                                     sal2,
11279                                                     caller_frame_id,
11280                                                     bp_until);
11281
11282       set_longjmp_breakpoint (tp, caller_frame_id);
11283       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11284     }
11285
11286   /* set_momentary_breakpoint could invalidate FRAME.  */
11287   frame = NULL;
11288
11289   breakpoint_up location_breakpoint;
11290   if (anywhere)
11291     /* If the user told us to continue until a specified location,
11292        we don't specify a frame at which we need to stop.  */
11293     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11294                                                     null_frame_id, bp_until);
11295   else
11296     /* Otherwise, specify the selected frame, because we want to stop
11297        only at the very same frame.  */
11298     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11299                                                     stack_frame_id, bp_until);
11300
11301   sm = new_until_break_fsm (command_interp (), tp->global_num,
11302                             std::move (location_breakpoint),
11303                             std::move (caller_breakpoint));
11304   tp->thread_fsm = &sm->thread_fsm;
11305
11306   discard_cleanups (old_chain);
11307
11308   proceed (-1, GDB_SIGNAL_DEFAULT);
11309 }
11310
11311 /* This function attempts to parse an optional "if <cond>" clause
11312    from the arg string.  If one is not found, it returns NULL.
11313
11314    Else, it returns a pointer to the condition string.  (It does not
11315    attempt to evaluate the string against a particular block.)  And,
11316    it updates arg to point to the first character following the parsed
11317    if clause in the arg string.  */
11318
11319 const char *
11320 ep_parse_optional_if_clause (const char **arg)
11321 {
11322   const char *cond_string;
11323
11324   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11325     return NULL;
11326
11327   /* Skip the "if" keyword.  */
11328   (*arg) += 2;
11329
11330   /* Skip any extra leading whitespace, and record the start of the
11331      condition string.  */
11332   *arg = skip_spaces (*arg);
11333   cond_string = *arg;
11334
11335   /* Assume that the condition occupies the remainder of the arg
11336      string.  */
11337   (*arg) += strlen (cond_string);
11338
11339   return cond_string;
11340 }
11341
11342 /* Commands to deal with catching events, such as signals, exceptions,
11343    process start/exit, etc.  */
11344
11345 typedef enum
11346 {
11347   catch_fork_temporary, catch_vfork_temporary,
11348   catch_fork_permanent, catch_vfork_permanent
11349 }
11350 catch_fork_kind;
11351
11352 static void
11353 catch_fork_command_1 (char *arg_entry, int from_tty,
11354                       struct cmd_list_element *command)
11355 {
11356   const char *arg = arg_entry;
11357   struct gdbarch *gdbarch = get_current_arch ();
11358   const char *cond_string = NULL;
11359   catch_fork_kind fork_kind;
11360   int tempflag;
11361
11362   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11363   tempflag = (fork_kind == catch_fork_temporary
11364               || fork_kind == catch_vfork_temporary);
11365
11366   if (!arg)
11367     arg = "";
11368   arg = skip_spaces (arg);
11369
11370   /* The allowed syntax is:
11371      catch [v]fork
11372      catch [v]fork if <cond>
11373
11374      First, check if there's an if clause.  */
11375   cond_string = ep_parse_optional_if_clause (&arg);
11376
11377   if ((*arg != '\0') && !isspace (*arg))
11378     error (_("Junk at end of arguments."));
11379
11380   /* If this target supports it, create a fork or vfork catchpoint
11381      and enable reporting of such events.  */
11382   switch (fork_kind)
11383     {
11384     case catch_fork_temporary:
11385     case catch_fork_permanent:
11386       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11387                                           &catch_fork_breakpoint_ops);
11388       break;
11389     case catch_vfork_temporary:
11390     case catch_vfork_permanent:
11391       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11392                                           &catch_vfork_breakpoint_ops);
11393       break;
11394     default:
11395       error (_("unsupported or unknown fork kind; cannot catch it"));
11396       break;
11397     }
11398 }
11399
11400 static void
11401 catch_exec_command_1 (char *arg_entry, int from_tty,
11402                       struct cmd_list_element *command)
11403 {
11404   const char *arg = arg_entry;
11405   struct gdbarch *gdbarch = get_current_arch ();
11406   int tempflag;
11407   const char *cond_string = NULL;
11408
11409   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11410
11411   if (!arg)
11412     arg = "";
11413   arg = skip_spaces (arg);
11414
11415   /* The allowed syntax is:
11416      catch exec
11417      catch exec if <cond>
11418
11419      First, check if there's an if clause.  */
11420   cond_string = ep_parse_optional_if_clause (&arg);
11421
11422   if ((*arg != '\0') && !isspace (*arg))
11423     error (_("Junk at end of arguments."));
11424
11425   std::unique_ptr<exec_catchpoint> c (new exec_catchpoint ());
11426   init_catchpoint (c.get (), gdbarch, tempflag, cond_string,
11427                    &catch_exec_breakpoint_ops);
11428   c->exec_pathname = NULL;
11429
11430   install_breakpoint (0, std::move (c), 1);
11431 }
11432
11433 void
11434 init_ada_exception_breakpoint (struct breakpoint *b,
11435                                struct gdbarch *gdbarch,
11436                                struct symtab_and_line sal,
11437                                const char *addr_string,
11438                                const struct breakpoint_ops *ops,
11439                                int tempflag,
11440                                int enabled,
11441                                int from_tty)
11442 {
11443   if (from_tty)
11444     {
11445       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11446       if (!loc_gdbarch)
11447         loc_gdbarch = gdbarch;
11448
11449       describe_other_breakpoints (loc_gdbarch,
11450                                   sal.pspace, sal.pc, sal.section, -1);
11451       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11452          version for exception catchpoints, because two catchpoints
11453          used for different exception names will use the same address.
11454          In this case, a "breakpoint ... also set at..." warning is
11455          unproductive.  Besides, the warning phrasing is also a bit
11456          inappropriate, we should use the word catchpoint, and tell
11457          the user what type of catchpoint it is.  The above is good
11458          enough for now, though.  */
11459     }
11460
11461   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11462
11463   b->enable_state = enabled ? bp_enabled : bp_disabled;
11464   b->disposition = tempflag ? disp_del : disp_donttouch;
11465   b->location = string_to_event_location (&addr_string,
11466                                           language_def (language_ada));
11467   b->language = language_ada;
11468 }
11469
11470 static void
11471 catch_command (const char *arg, int from_tty)
11472 {
11473   error (_("Catch requires an event name."));
11474 }
11475 \f
11476
11477 static void
11478 tcatch_command (const char *arg, int from_tty)
11479 {
11480   error (_("Catch requires an event name."));
11481 }
11482
11483 /* Compare two breakpoints and return a strcmp-like result.  */
11484
11485 static int
11486 compare_breakpoints (const breakpoint *a, const breakpoint *b)
11487 {
11488   uintptr_t ua = (uintptr_t) a;
11489   uintptr_t ub = (uintptr_t) b;
11490
11491   if (a->number < b->number)
11492     return -1;
11493   else if (a->number > b->number)
11494     return 1;
11495
11496   /* Now sort by address, in case we see, e..g, two breakpoints with
11497      the number 0.  */
11498   if (ua < ub)
11499     return -1;
11500   return ua > ub ? 1 : 0;
11501 }
11502
11503 /* Delete breakpoints by address or line.  */
11504
11505 static void
11506 clear_command (char *arg, int from_tty)
11507 {
11508   struct breakpoint *b;
11509   int default_match;
11510   int i;
11511
11512   std::vector<symtab_and_line> decoded_sals;
11513   symtab_and_line last_sal;
11514   gdb::array_view<symtab_and_line> sals;
11515   if (arg)
11516     {
11517       decoded_sals
11518         = decode_line_with_current_source (arg,
11519                                            (DECODE_LINE_FUNFIRSTLINE
11520                                             | DECODE_LINE_LIST_MODE));
11521       default_match = 0;
11522       sals = decoded_sals;
11523     }
11524   else
11525     {
11526       /* Set sal's line, symtab, pc, and pspace to the values
11527          corresponding to the last call to print_frame_info.  If the
11528          codepoint is not valid, this will set all the fields to 0.  */
11529       last_sal = get_last_displayed_sal ();
11530       if (last_sal.symtab == 0)
11531         error (_("No source file specified."));
11532
11533       default_match = 1;
11534       sals = last_sal;
11535     }
11536
11537   /* We don't call resolve_sal_pc here.  That's not as bad as it
11538      seems, because all existing breakpoints typically have both
11539      file/line and pc set.  So, if clear is given file/line, we can
11540      match this to existing breakpoint without obtaining pc at all.
11541
11542      We only support clearing given the address explicitly 
11543      present in breakpoint table.  Say, we've set breakpoint 
11544      at file:line.  There were several PC values for that file:line,
11545      due to optimization, all in one block.
11546
11547      We've picked one PC value.  If "clear" is issued with another
11548      PC corresponding to the same file:line, the breakpoint won't
11549      be cleared.  We probably can still clear the breakpoint, but 
11550      since the other PC value is never presented to user, user
11551      can only find it by guessing, and it does not seem important
11552      to support that.  */
11553
11554   /* For each line spec given, delete bps which correspond to it.  Do
11555      it in two passes, solely to preserve the current behavior that
11556      from_tty is forced true if we delete more than one
11557      breakpoint.  */
11558
11559   std::vector<struct breakpoint *> found;
11560   for (const auto &sal : sals)
11561     {
11562       const char *sal_fullname;
11563
11564       /* If exact pc given, clear bpts at that pc.
11565          If line given (pc == 0), clear all bpts on specified line.
11566          If defaulting, clear all bpts on default line
11567          or at default pc.
11568
11569          defaulting    sal.pc != 0    tests to do
11570
11571          0              1             pc
11572          1              1             pc _and_ line
11573          0              0             line
11574          1              0             <can't happen> */
11575
11576       sal_fullname = (sal.symtab == NULL
11577                       ? NULL : symtab_to_fullname (sal.symtab));
11578
11579       /* Find all matching breakpoints and add them to 'found'.  */
11580       ALL_BREAKPOINTS (b)
11581         {
11582           int match = 0;
11583           /* Are we going to delete b?  */
11584           if (b->type != bp_none && !is_watchpoint (b))
11585             {
11586               struct bp_location *loc = b->loc;
11587               for (; loc; loc = loc->next)
11588                 {
11589                   /* If the user specified file:line, don't allow a PC
11590                      match.  This matches historical gdb behavior.  */
11591                   int pc_match = (!sal.explicit_line
11592                                   && sal.pc
11593                                   && (loc->pspace == sal.pspace)
11594                                   && (loc->address == sal.pc)
11595                                   && (!section_is_overlay (loc->section)
11596                                       || loc->section == sal.section));
11597                   int line_match = 0;
11598
11599                   if ((default_match || sal.explicit_line)
11600                       && loc->symtab != NULL
11601                       && sal_fullname != NULL
11602                       && sal.pspace == loc->pspace
11603                       && loc->line_number == sal.line
11604                       && filename_cmp (symtab_to_fullname (loc->symtab),
11605                                        sal_fullname) == 0)
11606                     line_match = 1;
11607
11608                   if (pc_match || line_match)
11609                     {
11610                       match = 1;
11611                       break;
11612                     }
11613                 }
11614             }
11615
11616           if (match)
11617             found.push_back (b);
11618         }
11619     }
11620
11621   /* Now go thru the 'found' chain and delete them.  */
11622   if (found.empty ())
11623     {
11624       if (arg)
11625         error (_("No breakpoint at %s."), arg);
11626       else
11627         error (_("No breakpoint at this line."));
11628     }
11629
11630   /* Remove duplicates from the vec.  */
11631   std::sort (found.begin (), found.end (),
11632              [] (const breakpoint *a, const breakpoint *b)
11633              {
11634                return compare_breakpoints (a, b) < 0;
11635              });
11636   found.erase (std::unique (found.begin (), found.end (),
11637                             [] (const breakpoint *a, const breakpoint *b)
11638                             {
11639                               return compare_breakpoints (a, b) == 0;
11640                             }),
11641                found.end ());
11642
11643   if (found.size () > 1)
11644     from_tty = 1;       /* Always report if deleted more than one.  */
11645   if (from_tty)
11646     {
11647       if (found.size () == 1)
11648         printf_unfiltered (_("Deleted breakpoint "));
11649       else
11650         printf_unfiltered (_("Deleted breakpoints "));
11651     }
11652
11653   for (breakpoint *iter : found)
11654     {
11655       if (from_tty)
11656         printf_unfiltered ("%d ", iter->number);
11657       delete_breakpoint (iter);
11658     }
11659   if (from_tty)
11660     putchar_unfiltered ('\n');
11661 }
11662 \f
11663 /* Delete breakpoint in BS if they are `delete' breakpoints and
11664    all breakpoints that are marked for deletion, whether hit or not.
11665    This is called after any breakpoint is hit, or after errors.  */
11666
11667 void
11668 breakpoint_auto_delete (bpstat bs)
11669 {
11670   struct breakpoint *b, *b_tmp;
11671
11672   for (; bs; bs = bs->next)
11673     if (bs->breakpoint_at
11674         && bs->breakpoint_at->disposition == disp_del
11675         && bs->stop)
11676       delete_breakpoint (bs->breakpoint_at);
11677
11678   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11679   {
11680     if (b->disposition == disp_del_at_next_stop)
11681       delete_breakpoint (b);
11682   }
11683 }
11684
11685 /* A comparison function for bp_location AP and BP being interfaced to
11686    qsort.  Sort elements primarily by their ADDRESS (no matter what
11687    does breakpoint_address_is_meaningful say for its OWNER),
11688    secondarily by ordering first permanent elements and
11689    terciarily just ensuring the array is sorted stable way despite
11690    qsort being an unstable algorithm.  */
11691
11692 static int
11693 bp_locations_compare (const void *ap, const void *bp)
11694 {
11695   const struct bp_location *a = *(const struct bp_location **) ap;
11696   const struct bp_location *b = *(const struct bp_location **) bp;
11697
11698   if (a->address != b->address)
11699     return (a->address > b->address) - (a->address < b->address);
11700
11701   /* Sort locations at the same address by their pspace number, keeping
11702      locations of the same inferior (in a multi-inferior environment)
11703      grouped.  */
11704
11705   if (a->pspace->num != b->pspace->num)
11706     return ((a->pspace->num > b->pspace->num)
11707             - (a->pspace->num < b->pspace->num));
11708
11709   /* Sort permanent breakpoints first.  */
11710   if (a->permanent != b->permanent)
11711     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
11712
11713   /* Make the internal GDB representation stable across GDB runs
11714      where A and B memory inside GDB can differ.  Breakpoint locations of
11715      the same type at the same address can be sorted in arbitrary order.  */
11716
11717   if (a->owner->number != b->owner->number)
11718     return ((a->owner->number > b->owner->number)
11719             - (a->owner->number < b->owner->number));
11720
11721   return (a > b) - (a < b);
11722 }
11723
11724 /* Set bp_locations_placed_address_before_address_max and
11725    bp_locations_shadow_len_after_address_max according to the current
11726    content of the bp_locations array.  */
11727
11728 static void
11729 bp_locations_target_extensions_update (void)
11730 {
11731   struct bp_location *bl, **blp_tmp;
11732
11733   bp_locations_placed_address_before_address_max = 0;
11734   bp_locations_shadow_len_after_address_max = 0;
11735
11736   ALL_BP_LOCATIONS (bl, blp_tmp)
11737     {
11738       CORE_ADDR start, end, addr;
11739
11740       if (!bp_location_has_shadow (bl))
11741         continue;
11742
11743       start = bl->target_info.placed_address;
11744       end = start + bl->target_info.shadow_len;
11745
11746       gdb_assert (bl->address >= start);
11747       addr = bl->address - start;
11748       if (addr > bp_locations_placed_address_before_address_max)
11749         bp_locations_placed_address_before_address_max = addr;
11750
11751       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11752
11753       gdb_assert (bl->address < end);
11754       addr = end - bl->address;
11755       if (addr > bp_locations_shadow_len_after_address_max)
11756         bp_locations_shadow_len_after_address_max = addr;
11757     }
11758 }
11759
11760 /* Download tracepoint locations if they haven't been.  */
11761
11762 static void
11763 download_tracepoint_locations (void)
11764 {
11765   struct breakpoint *b;
11766   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11767
11768   scoped_restore_current_pspace_and_thread restore_pspace_thread;
11769
11770   ALL_TRACEPOINTS (b)
11771     {
11772       struct bp_location *bl;
11773       struct tracepoint *t;
11774       int bp_location_downloaded = 0;
11775
11776       if ((b->type == bp_fast_tracepoint
11777            ? !may_insert_fast_tracepoints
11778            : !may_insert_tracepoints))
11779         continue;
11780
11781       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11782         {
11783           if (target_can_download_tracepoint ())
11784             can_download_tracepoint = TRIBOOL_TRUE;
11785           else
11786             can_download_tracepoint = TRIBOOL_FALSE;
11787         }
11788
11789       if (can_download_tracepoint == TRIBOOL_FALSE)
11790         break;
11791
11792       for (bl = b->loc; bl; bl = bl->next)
11793         {
11794           /* In tracepoint, locations are _never_ duplicated, so
11795              should_be_inserted is equivalent to
11796              unduplicated_should_be_inserted.  */
11797           if (!should_be_inserted (bl) || bl->inserted)
11798             continue;
11799
11800           switch_to_program_space_and_thread (bl->pspace);
11801
11802           target_download_tracepoint (bl);
11803
11804           bl->inserted = 1;
11805           bp_location_downloaded = 1;
11806         }
11807       t = (struct tracepoint *) b;
11808       t->number_on_target = b->number;
11809       if (bp_location_downloaded)
11810         observer_notify_breakpoint_modified (b);
11811     }
11812 }
11813
11814 /* Swap the insertion/duplication state between two locations.  */
11815
11816 static void
11817 swap_insertion (struct bp_location *left, struct bp_location *right)
11818 {
11819   const int left_inserted = left->inserted;
11820   const int left_duplicate = left->duplicate;
11821   const int left_needs_update = left->needs_update;
11822   const struct bp_target_info left_target_info = left->target_info;
11823
11824   /* Locations of tracepoints can never be duplicated.  */
11825   if (is_tracepoint (left->owner))
11826     gdb_assert (!left->duplicate);
11827   if (is_tracepoint (right->owner))
11828     gdb_assert (!right->duplicate);
11829
11830   left->inserted = right->inserted;
11831   left->duplicate = right->duplicate;
11832   left->needs_update = right->needs_update;
11833   left->target_info = right->target_info;
11834   right->inserted = left_inserted;
11835   right->duplicate = left_duplicate;
11836   right->needs_update = left_needs_update;
11837   right->target_info = left_target_info;
11838 }
11839
11840 /* Force the re-insertion of the locations at ADDRESS.  This is called
11841    once a new/deleted/modified duplicate location is found and we are evaluating
11842    conditions on the target's side.  Such conditions need to be updated on
11843    the target.  */
11844
11845 static void
11846 force_breakpoint_reinsertion (struct bp_location *bl)
11847 {
11848   struct bp_location **locp = NULL, **loc2p;
11849   struct bp_location *loc;
11850   CORE_ADDR address = 0;
11851   int pspace_num;
11852
11853   address = bl->address;
11854   pspace_num = bl->pspace->num;
11855
11856   /* This is only meaningful if the target is
11857      evaluating conditions and if the user has
11858      opted for condition evaluation on the target's
11859      side.  */
11860   if (gdb_evaluates_breakpoint_condition_p ()
11861       || !target_supports_evaluation_of_breakpoint_conditions ())
11862     return;
11863
11864   /* Flag all breakpoint locations with this address and
11865      the same program space as the location
11866      as "its condition has changed".  We need to
11867      update the conditions on the target's side.  */
11868   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11869     {
11870       loc = *loc2p;
11871
11872       if (!is_breakpoint (loc->owner)
11873           || pspace_num != loc->pspace->num)
11874         continue;
11875
11876       /* Flag the location appropriately.  We use a different state to
11877          let everyone know that we already updated the set of locations
11878          with addr bl->address and program space bl->pspace.  This is so
11879          we don't have to keep calling these functions just to mark locations
11880          that have already been marked.  */
11881       loc->condition_changed = condition_updated;
11882
11883       /* Free the agent expression bytecode as well.  We will compute
11884          it later on.  */
11885       loc->cond_bytecode.reset ();
11886     }
11887 }
11888 /* Called whether new breakpoints are created, or existing breakpoints
11889    deleted, to update the global location list and recompute which
11890    locations are duplicate of which.
11891
11892    The INSERT_MODE flag determines whether locations may not, may, or
11893    shall be inserted now.  See 'enum ugll_insert_mode' for more
11894    info.  */
11895
11896 static void
11897 update_global_location_list (enum ugll_insert_mode insert_mode)
11898 {
11899   struct breakpoint *b;
11900   struct bp_location **locp, *loc;
11901   /* Last breakpoint location address that was marked for update.  */
11902   CORE_ADDR last_addr = 0;
11903   /* Last breakpoint location program space that was marked for update.  */
11904   int last_pspace_num = -1;
11905
11906   /* Used in the duplicates detection below.  When iterating over all
11907      bp_locations, points to the first bp_location of a given address.
11908      Breakpoints and watchpoints of different types are never
11909      duplicates of each other.  Keep one pointer for each type of
11910      breakpoint/watchpoint, so we only need to loop over all locations
11911      once.  */
11912   struct bp_location *bp_loc_first;  /* breakpoint */
11913   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11914   struct bp_location *awp_loc_first; /* access watchpoint */
11915   struct bp_location *rwp_loc_first; /* read watchpoint */
11916
11917   /* Saved former bp_locations array which we compare against the newly
11918      built bp_locations from the current state of ALL_BREAKPOINTS.  */
11919   struct bp_location **old_locp;
11920   unsigned old_locations_count;
11921   gdb::unique_xmalloc_ptr<struct bp_location *> old_locations (bp_locations);
11922
11923   old_locations_count = bp_locations_count;
11924   bp_locations = NULL;
11925   bp_locations_count = 0;
11926
11927   ALL_BREAKPOINTS (b)
11928     for (loc = b->loc; loc; loc = loc->next)
11929       bp_locations_count++;
11930
11931   bp_locations = XNEWVEC (struct bp_location *, bp_locations_count);
11932   locp = bp_locations;
11933   ALL_BREAKPOINTS (b)
11934     for (loc = b->loc; loc; loc = loc->next)
11935       *locp++ = loc;
11936   qsort (bp_locations, bp_locations_count, sizeof (*bp_locations),
11937          bp_locations_compare);
11938
11939   bp_locations_target_extensions_update ();
11940
11941   /* Identify bp_location instances that are no longer present in the
11942      new list, and therefore should be freed.  Note that it's not
11943      necessary that those locations should be removed from inferior --
11944      if there's another location at the same address (previously
11945      marked as duplicate), we don't need to remove/insert the
11946      location.
11947      
11948      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11949      and former bp_location array state respectively.  */
11950
11951   locp = bp_locations;
11952   for (old_locp = old_locations.get ();
11953        old_locp < old_locations.get () + old_locations_count;
11954        old_locp++)
11955     {
11956       struct bp_location *old_loc = *old_locp;
11957       struct bp_location **loc2p;
11958
11959       /* Tells if 'old_loc' is found among the new locations.  If
11960          not, we have to free it.  */
11961       int found_object = 0;
11962       /* Tells if the location should remain inserted in the target.  */
11963       int keep_in_target = 0;
11964       int removed = 0;
11965
11966       /* Skip LOCP entries which will definitely never be needed.
11967          Stop either at or being the one matching OLD_LOC.  */
11968       while (locp < bp_locations + bp_locations_count
11969              && (*locp)->address < old_loc->address)
11970         locp++;
11971
11972       for (loc2p = locp;
11973            (loc2p < bp_locations + bp_locations_count
11974             && (*loc2p)->address == old_loc->address);
11975            loc2p++)
11976         {
11977           /* Check if this is a new/duplicated location or a duplicated
11978              location that had its condition modified.  If so, we want to send
11979              its condition to the target if evaluation of conditions is taking
11980              place there.  */
11981           if ((*loc2p)->condition_changed == condition_modified
11982               && (last_addr != old_loc->address
11983                   || last_pspace_num != old_loc->pspace->num))
11984             {
11985               force_breakpoint_reinsertion (*loc2p);
11986               last_pspace_num = old_loc->pspace->num;
11987             }
11988
11989           if (*loc2p == old_loc)
11990             found_object = 1;
11991         }
11992
11993       /* We have already handled this address, update it so that we don't
11994          have to go through updates again.  */
11995       last_addr = old_loc->address;
11996
11997       /* Target-side condition evaluation: Handle deleted locations.  */
11998       if (!found_object)
11999         force_breakpoint_reinsertion (old_loc);
12000
12001       /* If this location is no longer present, and inserted, look if
12002          there's maybe a new location at the same address.  If so,
12003          mark that one inserted, and don't remove this one.  This is
12004          needed so that we don't have a time window where a breakpoint
12005          at certain location is not inserted.  */
12006
12007       if (old_loc->inserted)
12008         {
12009           /* If the location is inserted now, we might have to remove
12010              it.  */
12011
12012           if (found_object && should_be_inserted (old_loc))
12013             {
12014               /* The location is still present in the location list,
12015                  and still should be inserted.  Don't do anything.  */
12016               keep_in_target = 1;
12017             }
12018           else
12019             {
12020               /* This location still exists, but it won't be kept in the
12021                  target since it may have been disabled.  We proceed to
12022                  remove its target-side condition.  */
12023
12024               /* The location is either no longer present, or got
12025                  disabled.  See if there's another location at the
12026                  same address, in which case we don't need to remove
12027                  this one from the target.  */
12028
12029               /* OLD_LOC comes from existing struct breakpoint.  */
12030               if (breakpoint_address_is_meaningful (old_loc->owner))
12031                 {
12032                   for (loc2p = locp;
12033                        (loc2p < bp_locations + bp_locations_count
12034                         && (*loc2p)->address == old_loc->address);
12035                        loc2p++)
12036                     {
12037                       struct bp_location *loc2 = *loc2p;
12038
12039                       if (breakpoint_locations_match (loc2, old_loc))
12040                         {
12041                           /* Read watchpoint locations are switched to
12042                              access watchpoints, if the former are not
12043                              supported, but the latter are.  */
12044                           if (is_hardware_watchpoint (old_loc->owner))
12045                             {
12046                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12047                               loc2->watchpoint_type = old_loc->watchpoint_type;
12048                             }
12049
12050                           /* loc2 is a duplicated location. We need to check
12051                              if it should be inserted in case it will be
12052                              unduplicated.  */
12053                           if (loc2 != old_loc
12054                               && unduplicated_should_be_inserted (loc2))
12055                             {
12056                               swap_insertion (old_loc, loc2);
12057                               keep_in_target = 1;
12058                               break;
12059                             }
12060                         }
12061                     }
12062                 }
12063             }
12064
12065           if (!keep_in_target)
12066             {
12067               if (remove_breakpoint (old_loc))
12068                 {
12069                   /* This is just about all we can do.  We could keep
12070                      this location on the global list, and try to
12071                      remove it next time, but there's no particular
12072                      reason why we will succeed next time.
12073                      
12074                      Note that at this point, old_loc->owner is still
12075                      valid, as delete_breakpoint frees the breakpoint
12076                      only after calling us.  */
12077                   printf_filtered (_("warning: Error removing "
12078                                      "breakpoint %d\n"), 
12079                                    old_loc->owner->number);
12080                 }
12081               removed = 1;
12082             }
12083         }
12084
12085       if (!found_object)
12086         {
12087           if (removed && target_is_non_stop_p ()
12088               && need_moribund_for_location_type (old_loc))
12089             {
12090               /* This location was removed from the target.  In
12091                  non-stop mode, a race condition is possible where
12092                  we've removed a breakpoint, but stop events for that
12093                  breakpoint are already queued and will arrive later.
12094                  We apply an heuristic to be able to distinguish such
12095                  SIGTRAPs from other random SIGTRAPs: we keep this
12096                  breakpoint location for a bit, and will retire it
12097                  after we see some number of events.  The theory here
12098                  is that reporting of events should, "on the average",
12099                  be fair, so after a while we'll see events from all
12100                  threads that have anything of interest, and no longer
12101                  need to keep this breakpoint location around.  We
12102                  don't hold locations forever so to reduce chances of
12103                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12104                  SIGTRAP.
12105
12106                  The heuristic failing can be disastrous on
12107                  decr_pc_after_break targets.
12108
12109                  On decr_pc_after_break targets, like e.g., x86-linux,
12110                  if we fail to recognize a late breakpoint SIGTRAP,
12111                  because events_till_retirement has reached 0 too
12112                  soon, we'll fail to do the PC adjustment, and report
12113                  a random SIGTRAP to the user.  When the user resumes
12114                  the inferior, it will most likely immediately crash
12115                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12116                  corrupted, because of being resumed e.g., in the
12117                  middle of a multi-byte instruction, or skipped a
12118                  one-byte instruction.  This was actually seen happen
12119                  on native x86-linux, and should be less rare on
12120                  targets that do not support new thread events, like
12121                  remote, due to the heuristic depending on
12122                  thread_count.
12123
12124                  Mistaking a random SIGTRAP for a breakpoint trap
12125                  causes similar symptoms (PC adjustment applied when
12126                  it shouldn't), but then again, playing with SIGTRAPs
12127                  behind the debugger's back is asking for trouble.
12128
12129                  Since hardware watchpoint traps are always
12130                  distinguishable from other traps, so we don't need to
12131                  apply keep hardware watchpoint moribund locations
12132                  around.  We simply always ignore hardware watchpoint
12133                  traps we can no longer explain.  */
12134
12135               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12136               old_loc->owner = NULL;
12137
12138               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12139             }
12140           else
12141             {
12142               old_loc->owner = NULL;
12143               decref_bp_location (&old_loc);
12144             }
12145         }
12146     }
12147
12148   /* Rescan breakpoints at the same address and section, marking the
12149      first one as "first" and any others as "duplicates".  This is so
12150      that the bpt instruction is only inserted once.  If we have a
12151      permanent breakpoint at the same place as BPT, make that one the
12152      official one, and the rest as duplicates.  Permanent breakpoints
12153      are sorted first for the same address.
12154
12155      Do the same for hardware watchpoints, but also considering the
12156      watchpoint's type (regular/access/read) and length.  */
12157
12158   bp_loc_first = NULL;
12159   wp_loc_first = NULL;
12160   awp_loc_first = NULL;
12161   rwp_loc_first = NULL;
12162   ALL_BP_LOCATIONS (loc, locp)
12163     {
12164       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12165          non-NULL.  */
12166       struct bp_location **loc_first_p;
12167       b = loc->owner;
12168
12169       if (!unduplicated_should_be_inserted (loc)
12170           || !breakpoint_address_is_meaningful (b)
12171           /* Don't detect duplicate for tracepoint locations because they are
12172            never duplicated.  See the comments in field `duplicate' of
12173            `struct bp_location'.  */
12174           || is_tracepoint (b))
12175         {
12176           /* Clear the condition modification flag.  */
12177           loc->condition_changed = condition_unchanged;
12178           continue;
12179         }
12180
12181       if (b->type == bp_hardware_watchpoint)
12182         loc_first_p = &wp_loc_first;
12183       else if (b->type == bp_read_watchpoint)
12184         loc_first_p = &rwp_loc_first;
12185       else if (b->type == bp_access_watchpoint)
12186         loc_first_p = &awp_loc_first;
12187       else
12188         loc_first_p = &bp_loc_first;
12189
12190       if (*loc_first_p == NULL
12191           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12192           || !breakpoint_locations_match (loc, *loc_first_p))
12193         {
12194           *loc_first_p = loc;
12195           loc->duplicate = 0;
12196
12197           if (is_breakpoint (loc->owner) && loc->condition_changed)
12198             {
12199               loc->needs_update = 1;
12200               /* Clear the condition modification flag.  */
12201               loc->condition_changed = condition_unchanged;
12202             }
12203           continue;
12204         }
12205
12206
12207       /* This and the above ensure the invariant that the first location
12208          is not duplicated, and is the inserted one.
12209          All following are marked as duplicated, and are not inserted.  */
12210       if (loc->inserted)
12211         swap_insertion (loc, *loc_first_p);
12212       loc->duplicate = 1;
12213
12214       /* Clear the condition modification flag.  */
12215       loc->condition_changed = condition_unchanged;
12216     }
12217
12218   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12219     {
12220       if (insert_mode != UGLL_DONT_INSERT)
12221         insert_breakpoint_locations ();
12222       else
12223         {
12224           /* Even though the caller told us to not insert new
12225              locations, we may still need to update conditions on the
12226              target's side of breakpoints that were already inserted
12227              if the target is evaluating breakpoint conditions.  We
12228              only update conditions for locations that are marked
12229              "needs_update".  */
12230           update_inserted_breakpoint_locations ();
12231         }
12232     }
12233
12234   if (insert_mode != UGLL_DONT_INSERT)
12235     download_tracepoint_locations ();
12236 }
12237
12238 void
12239 breakpoint_retire_moribund (void)
12240 {
12241   struct bp_location *loc;
12242   int ix;
12243
12244   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12245     if (--(loc->events_till_retirement) == 0)
12246       {
12247         decref_bp_location (&loc);
12248         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12249         --ix;
12250       }
12251 }
12252
12253 static void
12254 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12255 {
12256
12257   TRY
12258     {
12259       update_global_location_list (insert_mode);
12260     }
12261   CATCH (e, RETURN_MASK_ERROR)
12262     {
12263     }
12264   END_CATCH
12265 }
12266
12267 /* Clear BKP from a BPS.  */
12268
12269 static void
12270 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12271 {
12272   bpstat bs;
12273
12274   for (bs = bps; bs; bs = bs->next)
12275     if (bs->breakpoint_at == bpt)
12276       {
12277         bs->breakpoint_at = NULL;
12278         bs->old_val = NULL;
12279         /* bs->commands will be freed later.  */
12280       }
12281 }
12282
12283 /* Callback for iterate_over_threads.  */
12284 static int
12285 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12286 {
12287   struct breakpoint *bpt = (struct breakpoint *) data;
12288
12289   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12290   return 0;
12291 }
12292
12293 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12294    callbacks.  */
12295
12296 static void
12297 say_where (struct breakpoint *b)
12298 {
12299   struct value_print_options opts;
12300
12301   get_user_print_options (&opts);
12302
12303   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12304      single string.  */
12305   if (b->loc == NULL)
12306     {
12307       /* For pending locations, the output differs slightly based
12308          on b->extra_string.  If this is non-NULL, it contains either
12309          a condition or dprintf arguments.  */
12310       if (b->extra_string == NULL)
12311         {
12312           printf_filtered (_(" (%s) pending."),
12313                            event_location_to_string (b->location.get ()));
12314         }
12315       else if (b->type == bp_dprintf)
12316         {
12317           printf_filtered (_(" (%s,%s) pending."),
12318                            event_location_to_string (b->location.get ()),
12319                            b->extra_string);
12320         }
12321       else
12322         {
12323           printf_filtered (_(" (%s %s) pending."),
12324                            event_location_to_string (b->location.get ()),
12325                            b->extra_string);
12326         }
12327     }
12328   else
12329     {
12330       if (opts.addressprint || b->loc->symtab == NULL)
12331         {
12332           printf_filtered (" at ");
12333           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12334                           gdb_stdout);
12335         }
12336       if (b->loc->symtab != NULL)
12337         {
12338           /* If there is a single location, we can print the location
12339              more nicely.  */
12340           if (b->loc->next == NULL)
12341             printf_filtered (": file %s, line %d.",
12342                              symtab_to_filename_for_display (b->loc->symtab),
12343                              b->loc->line_number);
12344           else
12345             /* This is not ideal, but each location may have a
12346                different file name, and this at least reflects the
12347                real situation somewhat.  */
12348             printf_filtered (": %s.",
12349                              event_location_to_string (b->location.get ()));
12350         }
12351
12352       if (b->loc->next)
12353         {
12354           struct bp_location *loc = b->loc;
12355           int n = 0;
12356           for (; loc; loc = loc->next)
12357             ++n;
12358           printf_filtered (" (%d locations)", n);
12359         }
12360     }
12361 }
12362
12363 /* Default bp_location_ops methods.  */
12364
12365 static void
12366 bp_location_dtor (struct bp_location *self)
12367 {
12368   xfree (self->function_name);
12369 }
12370
12371 static const struct bp_location_ops bp_location_ops =
12372 {
12373   bp_location_dtor
12374 };
12375
12376 /* Destructor for the breakpoint base class.  */
12377
12378 breakpoint::~breakpoint ()
12379 {
12380   xfree (this->cond_string);
12381   xfree (this->extra_string);
12382   xfree (this->filter);
12383 }
12384
12385 static struct bp_location *
12386 base_breakpoint_allocate_location (struct breakpoint *self)
12387 {
12388   return new bp_location (&bp_location_ops, self);
12389 }
12390
12391 static void
12392 base_breakpoint_re_set (struct breakpoint *b)
12393 {
12394   /* Nothing to re-set. */
12395 }
12396
12397 #define internal_error_pure_virtual_called() \
12398   gdb_assert_not_reached ("pure virtual function called")
12399
12400 static int
12401 base_breakpoint_insert_location (struct bp_location *bl)
12402 {
12403   internal_error_pure_virtual_called ();
12404 }
12405
12406 static int
12407 base_breakpoint_remove_location (struct bp_location *bl,
12408                                  enum remove_bp_reason reason)
12409 {
12410   internal_error_pure_virtual_called ();
12411 }
12412
12413 static int
12414 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12415                                 const address_space *aspace,
12416                                 CORE_ADDR bp_addr,
12417                                 const struct target_waitstatus *ws)
12418 {
12419   internal_error_pure_virtual_called ();
12420 }
12421
12422 static void
12423 base_breakpoint_check_status (bpstat bs)
12424 {
12425   /* Always stop.   */
12426 }
12427
12428 /* A "works_in_software_mode" breakpoint_ops method that just internal
12429    errors.  */
12430
12431 static int
12432 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12433 {
12434   internal_error_pure_virtual_called ();
12435 }
12436
12437 /* A "resources_needed" breakpoint_ops method that just internal
12438    errors.  */
12439
12440 static int
12441 base_breakpoint_resources_needed (const struct bp_location *bl)
12442 {
12443   internal_error_pure_virtual_called ();
12444 }
12445
12446 static enum print_stop_action
12447 base_breakpoint_print_it (bpstat bs)
12448 {
12449   internal_error_pure_virtual_called ();
12450 }
12451
12452 static void
12453 base_breakpoint_print_one_detail (const struct breakpoint *self,
12454                                   struct ui_out *uiout)
12455 {
12456   /* nothing */
12457 }
12458
12459 static void
12460 base_breakpoint_print_mention (struct breakpoint *b)
12461 {
12462   internal_error_pure_virtual_called ();
12463 }
12464
12465 static void
12466 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12467 {
12468   internal_error_pure_virtual_called ();
12469 }
12470
12471 static void
12472 base_breakpoint_create_sals_from_location
12473   (const struct event_location *location,
12474    struct linespec_result *canonical,
12475    enum bptype type_wanted)
12476 {
12477   internal_error_pure_virtual_called ();
12478 }
12479
12480 static void
12481 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12482                                         struct linespec_result *c,
12483                                         gdb::unique_xmalloc_ptr<char> cond_string,
12484                                         gdb::unique_xmalloc_ptr<char> extra_string,
12485                                         enum bptype type_wanted,
12486                                         enum bpdisp disposition,
12487                                         int thread,
12488                                         int task, int ignore_count,
12489                                         const struct breakpoint_ops *o,
12490                                         int from_tty, int enabled,
12491                                         int internal, unsigned flags)
12492 {
12493   internal_error_pure_virtual_called ();
12494 }
12495
12496 static std::vector<symtab_and_line>
12497 base_breakpoint_decode_location (struct breakpoint *b,
12498                                  const struct event_location *location,
12499                                  struct program_space *search_pspace)
12500 {
12501   internal_error_pure_virtual_called ();
12502 }
12503
12504 /* The default 'explains_signal' method.  */
12505
12506 static int
12507 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12508 {
12509   return 1;
12510 }
12511
12512 /* The default "after_condition_true" method.  */
12513
12514 static void
12515 base_breakpoint_after_condition_true (struct bpstats *bs)
12516 {
12517   /* Nothing to do.   */
12518 }
12519
12520 struct breakpoint_ops base_breakpoint_ops =
12521 {
12522   base_breakpoint_allocate_location,
12523   base_breakpoint_re_set,
12524   base_breakpoint_insert_location,
12525   base_breakpoint_remove_location,
12526   base_breakpoint_breakpoint_hit,
12527   base_breakpoint_check_status,
12528   base_breakpoint_resources_needed,
12529   base_breakpoint_works_in_software_mode,
12530   base_breakpoint_print_it,
12531   NULL,
12532   base_breakpoint_print_one_detail,
12533   base_breakpoint_print_mention,
12534   base_breakpoint_print_recreate,
12535   base_breakpoint_create_sals_from_location,
12536   base_breakpoint_create_breakpoints_sal,
12537   base_breakpoint_decode_location,
12538   base_breakpoint_explains_signal,
12539   base_breakpoint_after_condition_true,
12540 };
12541
12542 /* Default breakpoint_ops methods.  */
12543
12544 static void
12545 bkpt_re_set (struct breakpoint *b)
12546 {
12547   /* FIXME: is this still reachable?  */
12548   if (breakpoint_event_location_empty_p (b))
12549     {
12550       /* Anything without a location can't be re-set.  */
12551       delete_breakpoint (b);
12552       return;
12553     }
12554
12555   breakpoint_re_set_default (b);
12556 }
12557
12558 static int
12559 bkpt_insert_location (struct bp_location *bl)
12560 {
12561   CORE_ADDR addr = bl->target_info.reqstd_address;
12562
12563   bl->target_info.kind = breakpoint_kind (bl, &addr);
12564   bl->target_info.placed_address = addr;
12565
12566   if (bl->loc_type == bp_loc_hardware_breakpoint)
12567     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12568   else
12569     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12570 }
12571
12572 static int
12573 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
12574 {
12575   if (bl->loc_type == bp_loc_hardware_breakpoint)
12576     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12577   else
12578     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12579 }
12580
12581 static int
12582 bkpt_breakpoint_hit (const struct bp_location *bl,
12583                      const address_space *aspace, CORE_ADDR bp_addr,
12584                      const struct target_waitstatus *ws)
12585 {
12586   if (ws->kind != TARGET_WAITKIND_STOPPED
12587       || ws->value.sig != GDB_SIGNAL_TRAP)
12588     return 0;
12589
12590   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12591                                  aspace, bp_addr))
12592     return 0;
12593
12594   if (overlay_debugging         /* unmapped overlay section */
12595       && section_is_overlay (bl->section)
12596       && !section_is_mapped (bl->section))
12597     return 0;
12598
12599   return 1;
12600 }
12601
12602 static int
12603 dprintf_breakpoint_hit (const struct bp_location *bl,
12604                         const address_space *aspace, CORE_ADDR bp_addr,
12605                         const struct target_waitstatus *ws)
12606 {
12607   if (dprintf_style == dprintf_style_agent
12608       && target_can_run_breakpoint_commands ())
12609     {
12610       /* An agent-style dprintf never causes a stop.  If we see a trap
12611          for this address it must be for a breakpoint that happens to
12612          be set at the same address.  */
12613       return 0;
12614     }
12615
12616   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12617 }
12618
12619 static int
12620 bkpt_resources_needed (const struct bp_location *bl)
12621 {
12622   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12623
12624   return 1;
12625 }
12626
12627 static enum print_stop_action
12628 bkpt_print_it (bpstat bs)
12629 {
12630   struct breakpoint *b;
12631   const struct bp_location *bl;
12632   int bp_temp;
12633   struct ui_out *uiout = current_uiout;
12634
12635   gdb_assert (bs->bp_location_at != NULL);
12636
12637   bl = bs->bp_location_at;
12638   b = bs->breakpoint_at;
12639
12640   bp_temp = b->disposition == disp_del;
12641   if (bl->address != bl->requested_address)
12642     breakpoint_adjustment_warning (bl->requested_address,
12643                                    bl->address,
12644                                    b->number, 1);
12645   annotate_breakpoint (b->number);
12646   maybe_print_thread_hit_breakpoint (uiout);
12647
12648   if (bp_temp)
12649     uiout->text ("Temporary breakpoint ");
12650   else
12651     uiout->text ("Breakpoint ");
12652   if (uiout->is_mi_like_p ())
12653     {
12654       uiout->field_string ("reason",
12655                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12656       uiout->field_string ("disp", bpdisp_text (b->disposition));
12657     }
12658   uiout->field_int ("bkptno", b->number);
12659   uiout->text (", ");
12660
12661   return PRINT_SRC_AND_LOC;
12662 }
12663
12664 static void
12665 bkpt_print_mention (struct breakpoint *b)
12666 {
12667   if (current_uiout->is_mi_like_p ())
12668     return;
12669
12670   switch (b->type)
12671     {
12672     case bp_breakpoint:
12673     case bp_gnu_ifunc_resolver:
12674       if (b->disposition == disp_del)
12675         printf_filtered (_("Temporary breakpoint"));
12676       else
12677         printf_filtered (_("Breakpoint"));
12678       printf_filtered (_(" %d"), b->number);
12679       if (b->type == bp_gnu_ifunc_resolver)
12680         printf_filtered (_(" at gnu-indirect-function resolver"));
12681       break;
12682     case bp_hardware_breakpoint:
12683       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12684       break;
12685     case bp_dprintf:
12686       printf_filtered (_("Dprintf %d"), b->number);
12687       break;
12688     }
12689
12690   say_where (b);
12691 }
12692
12693 static void
12694 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12695 {
12696   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12697     fprintf_unfiltered (fp, "tbreak");
12698   else if (tp->type == bp_breakpoint)
12699     fprintf_unfiltered (fp, "break");
12700   else if (tp->type == bp_hardware_breakpoint
12701            && tp->disposition == disp_del)
12702     fprintf_unfiltered (fp, "thbreak");
12703   else if (tp->type == bp_hardware_breakpoint)
12704     fprintf_unfiltered (fp, "hbreak");
12705   else
12706     internal_error (__FILE__, __LINE__,
12707                     _("unhandled breakpoint type %d"), (int) tp->type);
12708
12709   fprintf_unfiltered (fp, " %s",
12710                       event_location_to_string (tp->location.get ()));
12711
12712   /* Print out extra_string if this breakpoint is pending.  It might
12713      contain, for example, conditions that were set by the user.  */
12714   if (tp->loc == NULL && tp->extra_string != NULL)
12715     fprintf_unfiltered (fp, " %s", tp->extra_string);
12716
12717   print_recreate_thread (tp, fp);
12718 }
12719
12720 static void
12721 bkpt_create_sals_from_location (const struct event_location *location,
12722                                 struct linespec_result *canonical,
12723                                 enum bptype type_wanted)
12724 {
12725   create_sals_from_location_default (location, canonical, type_wanted);
12726 }
12727
12728 static void
12729 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12730                              struct linespec_result *canonical,
12731                              gdb::unique_xmalloc_ptr<char> cond_string,
12732                              gdb::unique_xmalloc_ptr<char> extra_string,
12733                              enum bptype type_wanted,
12734                              enum bpdisp disposition,
12735                              int thread,
12736                              int task, int ignore_count,
12737                              const struct breakpoint_ops *ops,
12738                              int from_tty, int enabled,
12739                              int internal, unsigned flags)
12740 {
12741   create_breakpoints_sal_default (gdbarch, canonical,
12742                                   std::move (cond_string),
12743                                   std::move (extra_string),
12744                                   type_wanted,
12745                                   disposition, thread, task,
12746                                   ignore_count, ops, from_tty,
12747                                   enabled, internal, flags);
12748 }
12749
12750 static std::vector<symtab_and_line>
12751 bkpt_decode_location (struct breakpoint *b,
12752                       const struct event_location *location,
12753                       struct program_space *search_pspace)
12754 {
12755   return decode_location_default (b, location, search_pspace);
12756 }
12757
12758 /* Virtual table for internal breakpoints.  */
12759
12760 static void
12761 internal_bkpt_re_set (struct breakpoint *b)
12762 {
12763   switch (b->type)
12764     {
12765       /* Delete overlay event and longjmp master breakpoints; they
12766          will be reset later by breakpoint_re_set.  */
12767     case bp_overlay_event:
12768     case bp_longjmp_master:
12769     case bp_std_terminate_master:
12770     case bp_exception_master:
12771       delete_breakpoint (b);
12772       break;
12773
12774       /* This breakpoint is special, it's set up when the inferior
12775          starts and we really don't want to touch it.  */
12776     case bp_shlib_event:
12777
12778       /* Like bp_shlib_event, this breakpoint type is special.  Once
12779          it is set up, we do not want to touch it.  */
12780     case bp_thread_event:
12781       break;
12782     }
12783 }
12784
12785 static void
12786 internal_bkpt_check_status (bpstat bs)
12787 {
12788   if (bs->breakpoint_at->type == bp_shlib_event)
12789     {
12790       /* If requested, stop when the dynamic linker notifies GDB of
12791          events.  This allows the user to get control and place
12792          breakpoints in initializer routines for dynamically loaded
12793          objects (among other things).  */
12794       bs->stop = stop_on_solib_events;
12795       bs->print = stop_on_solib_events;
12796     }
12797   else
12798     bs->stop = 0;
12799 }
12800
12801 static enum print_stop_action
12802 internal_bkpt_print_it (bpstat bs)
12803 {
12804   struct breakpoint *b;
12805
12806   b = bs->breakpoint_at;
12807
12808   switch (b->type)
12809     {
12810     case bp_shlib_event:
12811       /* Did we stop because the user set the stop_on_solib_events
12812          variable?  (If so, we report this as a generic, "Stopped due
12813          to shlib event" message.) */
12814       print_solib_event (0);
12815       break;
12816
12817     case bp_thread_event:
12818       /* Not sure how we will get here.
12819          GDB should not stop for these breakpoints.  */
12820       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12821       break;
12822
12823     case bp_overlay_event:
12824       /* By analogy with the thread event, GDB should not stop for these.  */
12825       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12826       break;
12827
12828     case bp_longjmp_master:
12829       /* These should never be enabled.  */
12830       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12831       break;
12832
12833     case bp_std_terminate_master:
12834       /* These should never be enabled.  */
12835       printf_filtered (_("std::terminate Master Breakpoint: "
12836                          "gdb should not stop!\n"));
12837       break;
12838
12839     case bp_exception_master:
12840       /* These should never be enabled.  */
12841       printf_filtered (_("Exception Master Breakpoint: "
12842                          "gdb should not stop!\n"));
12843       break;
12844     }
12845
12846   return PRINT_NOTHING;
12847 }
12848
12849 static void
12850 internal_bkpt_print_mention (struct breakpoint *b)
12851 {
12852   /* Nothing to mention.  These breakpoints are internal.  */
12853 }
12854
12855 /* Virtual table for momentary breakpoints  */
12856
12857 static void
12858 momentary_bkpt_re_set (struct breakpoint *b)
12859 {
12860   /* Keep temporary breakpoints, which can be encountered when we step
12861      over a dlopen call and solib_add is resetting the breakpoints.
12862      Otherwise these should have been blown away via the cleanup chain
12863      or by breakpoint_init_inferior when we rerun the executable.  */
12864 }
12865
12866 static void
12867 momentary_bkpt_check_status (bpstat bs)
12868 {
12869   /* Nothing.  The point of these breakpoints is causing a stop.  */
12870 }
12871
12872 static enum print_stop_action
12873 momentary_bkpt_print_it (bpstat bs)
12874 {
12875   return PRINT_UNKNOWN;
12876 }
12877
12878 static void
12879 momentary_bkpt_print_mention (struct breakpoint *b)
12880 {
12881   /* Nothing to mention.  These breakpoints are internal.  */
12882 }
12883
12884 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12885
12886    It gets cleared already on the removal of the first one of such placed
12887    breakpoints.  This is OK as they get all removed altogether.  */
12888
12889 longjmp_breakpoint::~longjmp_breakpoint ()
12890 {
12891   thread_info *tp = find_thread_global_id (this->thread);
12892
12893   if (tp != NULL)
12894     tp->initiating_frame = null_frame_id;
12895 }
12896
12897 /* Specific methods for probe breakpoints.  */
12898
12899 static int
12900 bkpt_probe_insert_location (struct bp_location *bl)
12901 {
12902   int v = bkpt_insert_location (bl);
12903
12904   if (v == 0)
12905     {
12906       /* The insertion was successful, now let's set the probe's semaphore
12907          if needed.  */
12908       if (bl->probe.probe->pops->set_semaphore != NULL)
12909         bl->probe.probe->pops->set_semaphore (bl->probe.probe,
12910                                               bl->probe.objfile,
12911                                               bl->gdbarch);
12912     }
12913
12914   return v;
12915 }
12916
12917 static int
12918 bkpt_probe_remove_location (struct bp_location *bl,
12919                             enum remove_bp_reason reason)
12920 {
12921   /* Let's clear the semaphore before removing the location.  */
12922   if (bl->probe.probe->pops->clear_semaphore != NULL)
12923     bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
12924                                             bl->probe.objfile,
12925                                             bl->gdbarch);
12926
12927   return bkpt_remove_location (bl, reason);
12928 }
12929
12930 static void
12931 bkpt_probe_create_sals_from_location (const struct event_location *location,
12932                                       struct linespec_result *canonical,
12933                                       enum bptype type_wanted)
12934 {
12935   struct linespec_sals lsal;
12936
12937   lsal.sals = parse_probes (location, NULL, canonical);
12938   lsal.canonical
12939     = xstrdup (event_location_to_string (canonical->location.get ()));
12940   canonical->lsals.push_back (std::move (lsal));
12941 }
12942
12943 static std::vector<symtab_and_line>
12944 bkpt_probe_decode_location (struct breakpoint *b,
12945                             const struct event_location *location,
12946                             struct program_space *search_pspace)
12947 {
12948   std::vector<symtab_and_line> sals = parse_probes (location, search_pspace, NULL);
12949   if (sals.empty ())
12950     error (_("probe not found"));
12951   return sals;
12952 }
12953
12954 /* The breakpoint_ops structure to be used in tracepoints.  */
12955
12956 static void
12957 tracepoint_re_set (struct breakpoint *b)
12958 {
12959   breakpoint_re_set_default (b);
12960 }
12961
12962 static int
12963 tracepoint_breakpoint_hit (const struct bp_location *bl,
12964                            const address_space *aspace, CORE_ADDR bp_addr,
12965                            const struct target_waitstatus *ws)
12966 {
12967   /* By definition, the inferior does not report stops at
12968      tracepoints.  */
12969   return 0;
12970 }
12971
12972 static void
12973 tracepoint_print_one_detail (const struct breakpoint *self,
12974                              struct ui_out *uiout)
12975 {
12976   struct tracepoint *tp = (struct tracepoint *) self;
12977   if (tp->static_trace_marker_id)
12978     {
12979       gdb_assert (self->type == bp_static_tracepoint);
12980
12981       uiout->text ("\tmarker id is ");
12982       uiout->field_string ("static-tracepoint-marker-string-id",
12983                            tp->static_trace_marker_id);
12984       uiout->text ("\n");
12985     }
12986 }
12987
12988 static void
12989 tracepoint_print_mention (struct breakpoint *b)
12990 {
12991   if (current_uiout->is_mi_like_p ())
12992     return;
12993
12994   switch (b->type)
12995     {
12996     case bp_tracepoint:
12997       printf_filtered (_("Tracepoint"));
12998       printf_filtered (_(" %d"), b->number);
12999       break;
13000     case bp_fast_tracepoint:
13001       printf_filtered (_("Fast tracepoint"));
13002       printf_filtered (_(" %d"), b->number);
13003       break;
13004     case bp_static_tracepoint:
13005       printf_filtered (_("Static tracepoint"));
13006       printf_filtered (_(" %d"), b->number);
13007       break;
13008     default:
13009       internal_error (__FILE__, __LINE__,
13010                       _("unhandled tracepoint type %d"), (int) b->type);
13011     }
13012
13013   say_where (b);
13014 }
13015
13016 static void
13017 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13018 {
13019   struct tracepoint *tp = (struct tracepoint *) self;
13020
13021   if (self->type == bp_fast_tracepoint)
13022     fprintf_unfiltered (fp, "ftrace");
13023   else if (self->type == bp_static_tracepoint)
13024     fprintf_unfiltered (fp, "strace");
13025   else if (self->type == bp_tracepoint)
13026     fprintf_unfiltered (fp, "trace");
13027   else
13028     internal_error (__FILE__, __LINE__,
13029                     _("unhandled tracepoint type %d"), (int) self->type);
13030
13031   fprintf_unfiltered (fp, " %s",
13032                       event_location_to_string (self->location.get ()));
13033   print_recreate_thread (self, fp);
13034
13035   if (tp->pass_count)
13036     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13037 }
13038
13039 static void
13040 tracepoint_create_sals_from_location (const struct event_location *location,
13041                                       struct linespec_result *canonical,
13042                                       enum bptype type_wanted)
13043 {
13044   create_sals_from_location_default (location, canonical, type_wanted);
13045 }
13046
13047 static void
13048 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13049                                    struct linespec_result *canonical,
13050                                    gdb::unique_xmalloc_ptr<char> cond_string,
13051                                    gdb::unique_xmalloc_ptr<char> extra_string,
13052                                    enum bptype type_wanted,
13053                                    enum bpdisp disposition,
13054                                    int thread,
13055                                    int task, int ignore_count,
13056                                    const struct breakpoint_ops *ops,
13057                                    int from_tty, int enabled,
13058                                    int internal, unsigned flags)
13059 {
13060   create_breakpoints_sal_default (gdbarch, canonical,
13061                                   std::move (cond_string),
13062                                   std::move (extra_string),
13063                                   type_wanted,
13064                                   disposition, thread, task,
13065                                   ignore_count, ops, from_tty,
13066                                   enabled, internal, flags);
13067 }
13068
13069 static std::vector<symtab_and_line>
13070 tracepoint_decode_location (struct breakpoint *b,
13071                             const struct event_location *location,
13072                             struct program_space *search_pspace)
13073 {
13074   return decode_location_default (b, location, search_pspace);
13075 }
13076
13077 struct breakpoint_ops tracepoint_breakpoint_ops;
13078
13079 /* The breakpoint_ops structure to be use on tracepoints placed in a
13080    static probe.  */
13081
13082 static void
13083 tracepoint_probe_create_sals_from_location
13084   (const struct event_location *location,
13085    struct linespec_result *canonical,
13086    enum bptype type_wanted)
13087 {
13088   /* We use the same method for breakpoint on probes.  */
13089   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
13090 }
13091
13092 static std::vector<symtab_and_line>
13093 tracepoint_probe_decode_location (struct breakpoint *b,
13094                                   const struct event_location *location,
13095                                   struct program_space *search_pspace)
13096 {
13097   /* We use the same method for breakpoint on probes.  */
13098   return bkpt_probe_decode_location (b, location, search_pspace);
13099 }
13100
13101 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13102
13103 /* Dprintf breakpoint_ops methods.  */
13104
13105 static void
13106 dprintf_re_set (struct breakpoint *b)
13107 {
13108   breakpoint_re_set_default (b);
13109
13110   /* extra_string should never be non-NULL for dprintf.  */
13111   gdb_assert (b->extra_string != NULL);
13112
13113   /* 1 - connect to target 1, that can run breakpoint commands.
13114      2 - create a dprintf, which resolves fine.
13115      3 - disconnect from target 1
13116      4 - connect to target 2, that can NOT run breakpoint commands.
13117
13118      After steps #3/#4, you'll want the dprintf command list to
13119      be updated, because target 1 and 2 may well return different
13120      answers for target_can_run_breakpoint_commands().
13121      Given absence of finer grained resetting, we get to do
13122      it all the time.  */
13123   if (b->extra_string != NULL)
13124     update_dprintf_command_list (b);
13125 }
13126
13127 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13128
13129 static void
13130 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13131 {
13132   fprintf_unfiltered (fp, "dprintf %s,%s",
13133                       event_location_to_string (tp->location.get ()),
13134                       tp->extra_string);
13135   print_recreate_thread (tp, fp);
13136 }
13137
13138 /* Implement the "after_condition_true" breakpoint_ops method for
13139    dprintf.
13140
13141    dprintf's are implemented with regular commands in their command
13142    list, but we run the commands here instead of before presenting the
13143    stop to the user, as dprintf's don't actually cause a stop.  This
13144    also makes it so that the commands of multiple dprintfs at the same
13145    address are all handled.  */
13146
13147 static void
13148 dprintf_after_condition_true (struct bpstats *bs)
13149 {
13150   struct bpstats tmp_bs;
13151   struct bpstats *tmp_bs_p = &tmp_bs;
13152
13153   /* dprintf's never cause a stop.  This wasn't set in the
13154      check_status hook instead because that would make the dprintf's
13155      condition not be evaluated.  */
13156   bs->stop = 0;
13157
13158   /* Run the command list here.  Take ownership of it instead of
13159      copying.  We never want these commands to run later in
13160      bpstat_do_actions, if a breakpoint that causes a stop happens to
13161      be set at same address as this dprintf, or even if running the
13162      commands here throws.  */
13163   tmp_bs.commands = bs->commands;
13164   bs->commands = NULL;
13165
13166   bpstat_do_actions_1 (&tmp_bs_p);
13167
13168   /* 'tmp_bs.commands' will usually be NULL by now, but
13169      bpstat_do_actions_1 may return early without processing the whole
13170      list.  */
13171 }
13172
13173 /* The breakpoint_ops structure to be used on static tracepoints with
13174    markers (`-m').  */
13175
13176 static void
13177 strace_marker_create_sals_from_location (const struct event_location *location,
13178                                          struct linespec_result *canonical,
13179                                          enum bptype type_wanted)
13180 {
13181   struct linespec_sals lsal;
13182   const char *arg_start, *arg;
13183
13184   arg = arg_start = get_linespec_location (location);
13185   lsal.sals = decode_static_tracepoint_spec (&arg);
13186
13187   std::string str (arg_start, arg - arg_start);
13188   const char *ptr = str.c_str ();
13189   canonical->location = new_linespec_location (&ptr);
13190
13191   lsal.canonical
13192     = xstrdup (event_location_to_string (canonical->location.get ()));
13193   canonical->lsals.push_back (std::move (lsal));
13194 }
13195
13196 static void
13197 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13198                                       struct linespec_result *canonical,
13199                                       gdb::unique_xmalloc_ptr<char> cond_string,
13200                                       gdb::unique_xmalloc_ptr<char> extra_string,
13201                                       enum bptype type_wanted,
13202                                       enum bpdisp disposition,
13203                                       int thread,
13204                                       int task, int ignore_count,
13205                                       const struct breakpoint_ops *ops,
13206                                       int from_tty, int enabled,
13207                                       int internal, unsigned flags)
13208 {
13209   const linespec_sals &lsal = canonical->lsals[0];
13210
13211   /* If the user is creating a static tracepoint by marker id
13212      (strace -m MARKER_ID), then store the sals index, so that
13213      breakpoint_re_set can try to match up which of the newly
13214      found markers corresponds to this one, and, don't try to
13215      expand multiple locations for each sal, given than SALS
13216      already should contain all sals for MARKER_ID.  */
13217
13218   for (size_t i = 0; i < lsal.sals.size (); i++)
13219     {
13220       event_location_up location
13221         = copy_event_location (canonical->location.get ());
13222
13223       std::unique_ptr<tracepoint> tp (new tracepoint ());
13224       init_breakpoint_sal (tp.get (), gdbarch, lsal.sals[i],
13225                            std::move (location), NULL,
13226                            std::move (cond_string),
13227                            std::move (extra_string),
13228                            type_wanted, disposition,
13229                            thread, task, ignore_count, ops,
13230                            from_tty, enabled, internal, flags,
13231                            canonical->special_display);
13232       /* Given that its possible to have multiple markers with
13233          the same string id, if the user is creating a static
13234          tracepoint by marker id ("strace -m MARKER_ID"), then
13235          store the sals index, so that breakpoint_re_set can
13236          try to match up which of the newly found markers
13237          corresponds to this one  */
13238       tp->static_trace_marker_id_idx = i;
13239
13240       install_breakpoint (internal, std::move (tp), 0);
13241     }
13242 }
13243
13244 static std::vector<symtab_and_line>
13245 strace_marker_decode_location (struct breakpoint *b,
13246                                const struct event_location *location,
13247                                struct program_space *search_pspace)
13248 {
13249   struct tracepoint *tp = (struct tracepoint *) b;
13250   const char *s = get_linespec_location (location);
13251
13252   std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
13253   if (sals.size () > tp->static_trace_marker_id_idx)
13254     {
13255       sals[0] = sals[tp->static_trace_marker_id_idx];
13256       sals.resize (1);
13257       return sals;
13258     }
13259   else
13260     error (_("marker %s not found"), tp->static_trace_marker_id);
13261 }
13262
13263 static struct breakpoint_ops strace_marker_breakpoint_ops;
13264
13265 static int
13266 strace_marker_p (struct breakpoint *b)
13267 {
13268   return b->ops == &strace_marker_breakpoint_ops;
13269 }
13270
13271 /* Delete a breakpoint and clean up all traces of it in the data
13272    structures.  */
13273
13274 void
13275 delete_breakpoint (struct breakpoint *bpt)
13276 {
13277   struct breakpoint *b;
13278
13279   gdb_assert (bpt != NULL);
13280
13281   /* Has this bp already been deleted?  This can happen because
13282      multiple lists can hold pointers to bp's.  bpstat lists are
13283      especial culprits.
13284
13285      One example of this happening is a watchpoint's scope bp.  When
13286      the scope bp triggers, we notice that the watchpoint is out of
13287      scope, and delete it.  We also delete its scope bp.  But the
13288      scope bp is marked "auto-deleting", and is already on a bpstat.
13289      That bpstat is then checked for auto-deleting bp's, which are
13290      deleted.
13291
13292      A real solution to this problem might involve reference counts in
13293      bp's, and/or giving them pointers back to their referencing
13294      bpstat's, and teaching delete_breakpoint to only free a bp's
13295      storage when no more references were extent.  A cheaper bandaid
13296      was chosen.  */
13297   if (bpt->type == bp_none)
13298     return;
13299
13300   /* At least avoid this stale reference until the reference counting
13301      of breakpoints gets resolved.  */
13302   if (bpt->related_breakpoint != bpt)
13303     {
13304       struct breakpoint *related;
13305       struct watchpoint *w;
13306
13307       if (bpt->type == bp_watchpoint_scope)
13308         w = (struct watchpoint *) bpt->related_breakpoint;
13309       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13310         w = (struct watchpoint *) bpt;
13311       else
13312         w = NULL;
13313       if (w != NULL)
13314         watchpoint_del_at_next_stop (w);
13315
13316       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13317       for (related = bpt; related->related_breakpoint != bpt;
13318            related = related->related_breakpoint);
13319       related->related_breakpoint = bpt->related_breakpoint;
13320       bpt->related_breakpoint = bpt;
13321     }
13322
13323   /* watch_command_1 creates a watchpoint but only sets its number if
13324      update_watchpoint succeeds in creating its bp_locations.  If there's
13325      a problem in that process, we'll be asked to delete the half-created
13326      watchpoint.  In that case, don't announce the deletion.  */
13327   if (bpt->number)
13328     observer_notify_breakpoint_deleted (bpt);
13329
13330   if (breakpoint_chain == bpt)
13331     breakpoint_chain = bpt->next;
13332
13333   ALL_BREAKPOINTS (b)
13334     if (b->next == bpt)
13335     {
13336       b->next = bpt->next;
13337       break;
13338     }
13339
13340   /* Be sure no bpstat's are pointing at the breakpoint after it's
13341      been freed.  */
13342   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13343      in all threads for now.  Note that we cannot just remove bpstats
13344      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13345      commands are associated with the bpstat; if we remove it here,
13346      then the later call to bpstat_do_actions (&stop_bpstat); in
13347      event-top.c won't do anything, and temporary breakpoints with
13348      commands won't work.  */
13349
13350   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13351
13352   /* Now that breakpoint is removed from breakpoint list, update the
13353      global location list.  This will remove locations that used to
13354      belong to this breakpoint.  Do this before freeing the breakpoint
13355      itself, since remove_breakpoint looks at location's owner.  It
13356      might be better design to have location completely
13357      self-contained, but it's not the case now.  */
13358   update_global_location_list (UGLL_DONT_INSERT);
13359
13360   /* On the chance that someone will soon try again to delete this
13361      same bp, we mark it as deleted before freeing its storage.  */
13362   bpt->type = bp_none;
13363   delete bpt;
13364 }
13365
13366 /* Iterator function to call a user-provided callback function once
13367    for each of B and its related breakpoints.  */
13368
13369 static void
13370 iterate_over_related_breakpoints (struct breakpoint *b,
13371                                   gdb::function_view<void (breakpoint *)> function)
13372 {
13373   struct breakpoint *related;
13374
13375   related = b;
13376   do
13377     {
13378       struct breakpoint *next;
13379
13380       /* FUNCTION may delete RELATED.  */
13381       next = related->related_breakpoint;
13382
13383       if (next == related)
13384         {
13385           /* RELATED is the last ring entry.  */
13386           function (related);
13387
13388           /* FUNCTION may have deleted it, so we'd never reach back to
13389              B.  There's nothing left to do anyway, so just break
13390              out.  */
13391           break;
13392         }
13393       else
13394         function (related);
13395
13396       related = next;
13397     }
13398   while (related != b);
13399 }
13400
13401 static void
13402 delete_command (const char *arg, int from_tty)
13403 {
13404   struct breakpoint *b, *b_tmp;
13405
13406   dont_repeat ();
13407
13408   if (arg == 0)
13409     {
13410       int breaks_to_delete = 0;
13411
13412       /* Delete all breakpoints if no argument.  Do not delete
13413          internal breakpoints, these have to be deleted with an
13414          explicit breakpoint number argument.  */
13415       ALL_BREAKPOINTS (b)
13416         if (user_breakpoint_p (b))
13417           {
13418             breaks_to_delete = 1;
13419             break;
13420           }
13421
13422       /* Ask user only if there are some breakpoints to delete.  */
13423       if (!from_tty
13424           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13425         {
13426           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13427             if (user_breakpoint_p (b))
13428               delete_breakpoint (b);
13429         }
13430     }
13431   else
13432     map_breakpoint_numbers
13433       (arg, [&] (breakpoint *b)
13434        {
13435          iterate_over_related_breakpoints (b, delete_breakpoint);
13436        });
13437 }
13438
13439 /* Return true if all locations of B bound to PSPACE are pending.  If
13440    PSPACE is NULL, all locations of all program spaces are
13441    considered.  */
13442
13443 static int
13444 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13445 {
13446   struct bp_location *loc;
13447
13448   for (loc = b->loc; loc != NULL; loc = loc->next)
13449     if ((pspace == NULL
13450          || loc->pspace == pspace)
13451         && !loc->shlib_disabled
13452         && !loc->pspace->executing_startup)
13453       return 0;
13454   return 1;
13455 }
13456
13457 /* Subroutine of update_breakpoint_locations to simplify it.
13458    Return non-zero if multiple fns in list LOC have the same name.
13459    Null names are ignored.  */
13460
13461 static int
13462 ambiguous_names_p (struct bp_location *loc)
13463 {
13464   struct bp_location *l;
13465   htab_t htab = htab_create_alloc (13, htab_hash_string,
13466                                    (int (*) (const void *, 
13467                                              const void *)) streq,
13468                                    NULL, xcalloc, xfree);
13469
13470   for (l = loc; l != NULL; l = l->next)
13471     {
13472       const char **slot;
13473       const char *name = l->function_name;
13474
13475       /* Allow for some names to be NULL, ignore them.  */
13476       if (name == NULL)
13477         continue;
13478
13479       slot = (const char **) htab_find_slot (htab, (const void *) name,
13480                                              INSERT);
13481       /* NOTE: We can assume slot != NULL here because xcalloc never
13482          returns NULL.  */
13483       if (*slot != NULL)
13484         {
13485           htab_delete (htab);
13486           return 1;
13487         }
13488       *slot = name;
13489     }
13490
13491   htab_delete (htab);
13492   return 0;
13493 }
13494
13495 /* When symbols change, it probably means the sources changed as well,
13496    and it might mean the static tracepoint markers are no longer at
13497    the same address or line numbers they used to be at last we
13498    checked.  Losing your static tracepoints whenever you rebuild is
13499    undesirable.  This function tries to resync/rematch gdb static
13500    tracepoints with the markers on the target, for static tracepoints
13501    that have not been set by marker id.  Static tracepoint that have
13502    been set by marker id are reset by marker id in breakpoint_re_set.
13503    The heuristic is:
13504
13505    1) For a tracepoint set at a specific address, look for a marker at
13506    the old PC.  If one is found there, assume to be the same marker.
13507    If the name / string id of the marker found is different from the
13508    previous known name, assume that means the user renamed the marker
13509    in the sources, and output a warning.
13510
13511    2) For a tracepoint set at a given line number, look for a marker
13512    at the new address of the old line number.  If one is found there,
13513    assume to be the same marker.  If the name / string id of the
13514    marker found is different from the previous known name, assume that
13515    means the user renamed the marker in the sources, and output a
13516    warning.
13517
13518    3) If a marker is no longer found at the same address or line, it
13519    may mean the marker no longer exists.  But it may also just mean
13520    the code changed a bit.  Maybe the user added a few lines of code
13521    that made the marker move up or down (in line number terms).  Ask
13522    the target for info about the marker with the string id as we knew
13523    it.  If found, update line number and address in the matching
13524    static tracepoint.  This will get confused if there's more than one
13525    marker with the same ID (possible in UST, although unadvised
13526    precisely because it confuses tools).  */
13527
13528 static struct symtab_and_line
13529 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13530 {
13531   struct tracepoint *tp = (struct tracepoint *) b;
13532   struct static_tracepoint_marker marker;
13533   CORE_ADDR pc;
13534
13535   pc = sal.pc;
13536   if (sal.line)
13537     find_line_pc (sal.symtab, sal.line, &pc);
13538
13539   if (target_static_tracepoint_marker_at (pc, &marker))
13540     {
13541       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13542         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13543                  b->number,
13544                  tp->static_trace_marker_id, marker.str_id);
13545
13546       xfree (tp->static_trace_marker_id);
13547       tp->static_trace_marker_id = xstrdup (marker.str_id);
13548       release_static_tracepoint_marker (&marker);
13549
13550       return sal;
13551     }
13552
13553   /* Old marker wasn't found on target at lineno.  Try looking it up
13554      by string ID.  */
13555   if (!sal.explicit_pc
13556       && sal.line != 0
13557       && sal.symtab != NULL
13558       && tp->static_trace_marker_id != NULL)
13559     {
13560       VEC(static_tracepoint_marker_p) *markers;
13561
13562       markers
13563         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13564
13565       if (!VEC_empty(static_tracepoint_marker_p, markers))
13566         {
13567           struct symbol *sym;
13568           struct static_tracepoint_marker *tpmarker;
13569           struct ui_out *uiout = current_uiout;
13570           struct explicit_location explicit_loc;
13571
13572           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13573
13574           xfree (tp->static_trace_marker_id);
13575           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13576
13577           warning (_("marker for static tracepoint %d (%s) not "
13578                      "found at previous line number"),
13579                    b->number, tp->static_trace_marker_id);
13580
13581           symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
13582           sym = find_pc_sect_function (tpmarker->address, NULL);
13583           uiout->text ("Now in ");
13584           if (sym)
13585             {
13586               uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
13587               uiout->text (" at ");
13588             }
13589           uiout->field_string ("file",
13590                                symtab_to_filename_for_display (sal2.symtab));
13591           uiout->text (":");
13592
13593           if (uiout->is_mi_like_p ())
13594             {
13595               const char *fullname = symtab_to_fullname (sal2.symtab);
13596
13597               uiout->field_string ("fullname", fullname);
13598             }
13599
13600           uiout->field_int ("line", sal2.line);
13601           uiout->text ("\n");
13602
13603           b->loc->line_number = sal2.line;
13604           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13605
13606           b->location.reset (NULL);
13607           initialize_explicit_location (&explicit_loc);
13608           explicit_loc.source_filename
13609             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
13610           explicit_loc.line_offset.offset = b->loc->line_number;
13611           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
13612           b->location = new_explicit_location (&explicit_loc);
13613
13614           /* Might be nice to check if function changed, and warn if
13615              so.  */
13616
13617           release_static_tracepoint_marker (tpmarker);
13618         }
13619     }
13620   return sal;
13621 }
13622
13623 /* Returns 1 iff locations A and B are sufficiently same that
13624    we don't need to report breakpoint as changed.  */
13625
13626 static int
13627 locations_are_equal (struct bp_location *a, struct bp_location *b)
13628 {
13629   while (a && b)
13630     {
13631       if (a->address != b->address)
13632         return 0;
13633
13634       if (a->shlib_disabled != b->shlib_disabled)
13635         return 0;
13636
13637       if (a->enabled != b->enabled)
13638         return 0;
13639
13640       a = a->next;
13641       b = b->next;
13642     }
13643
13644   if ((a == NULL) != (b == NULL))
13645     return 0;
13646
13647   return 1;
13648 }
13649
13650 /* Split all locations of B that are bound to PSPACE out of B's
13651    location list to a separate list and return that list's head.  If
13652    PSPACE is NULL, hoist out all locations of B.  */
13653
13654 static struct bp_location *
13655 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
13656 {
13657   struct bp_location head;
13658   struct bp_location *i = b->loc;
13659   struct bp_location **i_link = &b->loc;
13660   struct bp_location *hoisted = &head;
13661
13662   if (pspace == NULL)
13663     {
13664       i = b->loc;
13665       b->loc = NULL;
13666       return i;
13667     }
13668
13669   head.next = NULL;
13670
13671   while (i != NULL)
13672     {
13673       if (i->pspace == pspace)
13674         {
13675           *i_link = i->next;
13676           i->next = NULL;
13677           hoisted->next = i;
13678           hoisted = i;
13679         }
13680       else
13681         i_link = &i->next;
13682       i = *i_link;
13683     }
13684
13685   return head.next;
13686 }
13687
13688 /* Create new breakpoint locations for B (a hardware or software
13689    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
13690    zero, then B is a ranged breakpoint.  Only recreates locations for
13691    FILTER_PSPACE.  Locations of other program spaces are left
13692    untouched.  */
13693
13694 void
13695 update_breakpoint_locations (struct breakpoint *b,
13696                              struct program_space *filter_pspace,
13697                              gdb::array_view<const symtab_and_line> sals,
13698                              gdb::array_view<const symtab_and_line> sals_end)
13699 {
13700   int i;
13701   struct bp_location *existing_locations;
13702
13703   if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
13704     {
13705       /* Ranged breakpoints have only one start location and one end
13706          location.  */
13707       b->enable_state = bp_disabled;
13708       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13709                            "multiple locations found\n"),
13710                          b->number);
13711       return;
13712     }
13713
13714   /* If there's no new locations, and all existing locations are
13715      pending, don't do anything.  This optimizes the common case where
13716      all locations are in the same shared library, that was unloaded.
13717      We'd like to retain the location, so that when the library is
13718      loaded again, we don't loose the enabled/disabled status of the
13719      individual locations.  */
13720   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
13721     return;
13722
13723   existing_locations = hoist_existing_locations (b, filter_pspace);
13724
13725   for (const auto &sal : sals)
13726     {
13727       struct bp_location *new_loc;
13728
13729       switch_to_program_space_and_thread (sal.pspace);
13730
13731       new_loc = add_location_to_breakpoint (b, &sal);
13732
13733       /* Reparse conditions, they might contain references to the
13734          old symtab.  */
13735       if (b->cond_string != NULL)
13736         {
13737           const char *s;
13738
13739           s = b->cond_string;
13740           TRY
13741             {
13742               new_loc->cond = parse_exp_1 (&s, sal.pc,
13743                                            block_for_pc (sal.pc),
13744                                            0);
13745             }
13746           CATCH (e, RETURN_MASK_ERROR)
13747             {
13748               warning (_("failed to reevaluate condition "
13749                          "for breakpoint %d: %s"), 
13750                        b->number, e.message);
13751               new_loc->enabled = 0;
13752             }
13753           END_CATCH
13754         }
13755
13756       if (!sals_end.empty ())
13757         {
13758           CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13759
13760           new_loc->length = end - sals[0].pc + 1;
13761         }
13762     }
13763
13764   /* If possible, carry over 'disable' status from existing
13765      breakpoints.  */
13766   {
13767     struct bp_location *e = existing_locations;
13768     /* If there are multiple breakpoints with the same function name,
13769        e.g. for inline functions, comparing function names won't work.
13770        Instead compare pc addresses; this is just a heuristic as things
13771        may have moved, but in practice it gives the correct answer
13772        often enough until a better solution is found.  */
13773     int have_ambiguous_names = ambiguous_names_p (b->loc);
13774
13775     for (; e; e = e->next)
13776       {
13777         if (!e->enabled && e->function_name)
13778           {
13779             struct bp_location *l = b->loc;
13780             if (have_ambiguous_names)
13781               {
13782                 for (; l; l = l->next)
13783                   if (breakpoint_locations_match (e, l))
13784                     {
13785                       l->enabled = 0;
13786                       break;
13787                     }
13788               }
13789             else
13790               {
13791                 for (; l; l = l->next)
13792                   if (l->function_name
13793                       && strcmp (e->function_name, l->function_name) == 0)
13794                     {
13795                       l->enabled = 0;
13796                       break;
13797                     }
13798               }
13799           }
13800       }
13801   }
13802
13803   if (!locations_are_equal (existing_locations, b->loc))
13804     observer_notify_breakpoint_modified (b);
13805 }
13806
13807 /* Find the SaL locations corresponding to the given LOCATION.
13808    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13809
13810 static std::vector<symtab_and_line>
13811 location_to_sals (struct breakpoint *b, struct event_location *location,
13812                   struct program_space *search_pspace, int *found)
13813 {
13814   struct gdb_exception exception = exception_none;
13815
13816   gdb_assert (b->ops != NULL);
13817
13818   std::vector<symtab_and_line> sals;
13819
13820   TRY
13821     {
13822       sals = b->ops->decode_location (b, location, search_pspace);
13823     }
13824   CATCH (e, RETURN_MASK_ERROR)
13825     {
13826       int not_found_and_ok = 0;
13827
13828       exception = e;
13829
13830       /* For pending breakpoints, it's expected that parsing will
13831          fail until the right shared library is loaded.  User has
13832          already told to create pending breakpoints and don't need
13833          extra messages.  If breakpoint is in bp_shlib_disabled
13834          state, then user already saw the message about that
13835          breakpoint being disabled, and don't want to see more
13836          errors.  */
13837       if (e.error == NOT_FOUND_ERROR
13838           && (b->condition_not_parsed
13839               || (b->loc != NULL
13840                   && search_pspace != NULL
13841                   && b->loc->pspace != search_pspace)
13842               || (b->loc && b->loc->shlib_disabled)
13843               || (b->loc && b->loc->pspace->executing_startup)
13844               || b->enable_state == bp_disabled))
13845         not_found_and_ok = 1;
13846
13847       if (!not_found_and_ok)
13848         {
13849           /* We surely don't want to warn about the same breakpoint
13850              10 times.  One solution, implemented here, is disable
13851              the breakpoint on error.  Another solution would be to
13852              have separate 'warning emitted' flag.  Since this
13853              happens only when a binary has changed, I don't know
13854              which approach is better.  */
13855           b->enable_state = bp_disabled;
13856           throw_exception (e);
13857         }
13858     }
13859   END_CATCH
13860
13861   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13862     {
13863       for (auto &sal : sals)
13864         resolve_sal_pc (&sal);
13865       if (b->condition_not_parsed && b->extra_string != NULL)
13866         {
13867           char *cond_string, *extra_string;
13868           int thread, task;
13869
13870           find_condition_and_thread (b->extra_string, sals[0].pc,
13871                                      &cond_string, &thread, &task,
13872                                      &extra_string);
13873           gdb_assert (b->cond_string == NULL);
13874           if (cond_string)
13875             b->cond_string = cond_string;
13876           b->thread = thread;
13877           b->task = task;
13878           if (extra_string)
13879             {
13880               xfree (b->extra_string);
13881               b->extra_string = extra_string;
13882             }
13883           b->condition_not_parsed = 0;
13884         }
13885
13886       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13887         sals[0] = update_static_tracepoint (b, sals[0]);
13888
13889       *found = 1;
13890     }
13891   else
13892     *found = 0;
13893
13894   return sals;
13895 }
13896
13897 /* The default re_set method, for typical hardware or software
13898    breakpoints.  Reevaluate the breakpoint and recreate its
13899    locations.  */
13900
13901 static void
13902 breakpoint_re_set_default (struct breakpoint *b)
13903 {
13904   struct program_space *filter_pspace = current_program_space;
13905   std::vector<symtab_and_line> expanded, expanded_end;
13906
13907   int found;
13908   std::vector<symtab_and_line> sals = location_to_sals (b, b->location.get (),
13909                                                         filter_pspace, &found);
13910   if (found)
13911     expanded = std::move (sals);
13912
13913   if (b->location_range_end != NULL)
13914     {
13915       std::vector<symtab_and_line> sals_end
13916         = location_to_sals (b, b->location_range_end.get (),
13917                             filter_pspace, &found);
13918       if (found)
13919         expanded_end = std::move (sals_end);
13920     }
13921
13922   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
13923 }
13924
13925 /* Default method for creating SALs from an address string.  It basically
13926    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13927
13928 static void
13929 create_sals_from_location_default (const struct event_location *location,
13930                                    struct linespec_result *canonical,
13931                                    enum bptype type_wanted)
13932 {
13933   parse_breakpoint_sals (location, canonical);
13934 }
13935
13936 /* Call create_breakpoints_sal for the given arguments.  This is the default
13937    function for the `create_breakpoints_sal' method of
13938    breakpoint_ops.  */
13939
13940 static void
13941 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13942                                 struct linespec_result *canonical,
13943                                 gdb::unique_xmalloc_ptr<char> cond_string,
13944                                 gdb::unique_xmalloc_ptr<char> extra_string,
13945                                 enum bptype type_wanted,
13946                                 enum bpdisp disposition,
13947                                 int thread,
13948                                 int task, int ignore_count,
13949                                 const struct breakpoint_ops *ops,
13950                                 int from_tty, int enabled,
13951                                 int internal, unsigned flags)
13952 {
13953   create_breakpoints_sal (gdbarch, canonical,
13954                           std::move (cond_string),
13955                           std::move (extra_string),
13956                           type_wanted, disposition,
13957                           thread, task, ignore_count, ops, from_tty,
13958                           enabled, internal, flags);
13959 }
13960
13961 /* Decode the line represented by S by calling decode_line_full.  This is the
13962    default function for the `decode_location' method of breakpoint_ops.  */
13963
13964 static std::vector<symtab_and_line>
13965 decode_location_default (struct breakpoint *b,
13966                          const struct event_location *location,
13967                          struct program_space *search_pspace)
13968 {
13969   struct linespec_result canonical;
13970
13971   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
13972                     (struct symtab *) NULL, 0,
13973                     &canonical, multiple_symbols_all,
13974                     b->filter);
13975
13976   /* We should get 0 or 1 resulting SALs.  */
13977   gdb_assert (canonical.lsals.size () < 2);
13978
13979   if (!canonical.lsals.empty ())
13980     {
13981       const linespec_sals &lsal = canonical.lsals[0];
13982       return std::move (lsal.sals);
13983     }
13984   return {};
13985 }
13986
13987 /* Reset a breakpoint.  */
13988
13989 static void
13990 breakpoint_re_set_one (breakpoint *b)
13991 {
13992   input_radix = b->input_radix;
13993   set_language (b->language);
13994
13995   b->ops->re_set (b);
13996 }
13997
13998 /* Re-set breakpoint locations for the current program space.
13999    Locations bound to other program spaces are left untouched.  */
14000
14001 void
14002 breakpoint_re_set (void)
14003 {
14004   struct breakpoint *b, *b_tmp;
14005
14006   {
14007     scoped_restore_current_language save_language;
14008     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
14009     scoped_restore_current_pspace_and_thread restore_pspace_thread;
14010
14011     /* Note: we must not try to insert locations until after all
14012        breakpoints have been re-set.  Otherwise, e.g., when re-setting
14013        breakpoint 1, we'd insert the locations of breakpoint 2, which
14014        hadn't been re-set yet, and thus may have stale locations.  */
14015
14016     ALL_BREAKPOINTS_SAFE (b, b_tmp)
14017       {
14018         TRY
14019           {
14020             breakpoint_re_set_one (b);
14021           }
14022         CATCH (ex, RETURN_MASK_ALL)
14023           {
14024             exception_fprintf (gdb_stderr, ex,
14025                                "Error in re-setting breakpoint %d: ",
14026                                b->number);
14027           }
14028         END_CATCH
14029       }
14030
14031     jit_breakpoint_re_set ();
14032   }
14033
14034   create_overlay_event_breakpoint ();
14035   create_longjmp_master_breakpoint ();
14036   create_std_terminate_master_breakpoint ();
14037   create_exception_master_breakpoint ();
14038
14039   /* Now we can insert.  */
14040   update_global_location_list (UGLL_MAY_INSERT);
14041 }
14042 \f
14043 /* Reset the thread number of this breakpoint:
14044
14045    - If the breakpoint is for all threads, leave it as-is.
14046    - Else, reset it to the current thread for inferior_ptid.  */
14047 void
14048 breakpoint_re_set_thread (struct breakpoint *b)
14049 {
14050   if (b->thread != -1)
14051     {
14052       if (in_thread_list (inferior_ptid))
14053         b->thread = ptid_to_global_thread_id (inferior_ptid);
14054
14055       /* We're being called after following a fork.  The new fork is
14056          selected as current, and unless this was a vfork will have a
14057          different program space from the original thread.  Reset that
14058          as well.  */
14059       b->loc->pspace = current_program_space;
14060     }
14061 }
14062
14063 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14064    If from_tty is nonzero, it prints a message to that effect,
14065    which ends with a period (no newline).  */
14066
14067 void
14068 set_ignore_count (int bptnum, int count, int from_tty)
14069 {
14070   struct breakpoint *b;
14071
14072   if (count < 0)
14073     count = 0;
14074
14075   ALL_BREAKPOINTS (b)
14076     if (b->number == bptnum)
14077     {
14078       if (is_tracepoint (b))
14079         {
14080           if (from_tty && count != 0)
14081             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14082                              bptnum);
14083           return;
14084         }
14085       
14086       b->ignore_count = count;
14087       if (from_tty)
14088         {
14089           if (count == 0)
14090             printf_filtered (_("Will stop next time "
14091                                "breakpoint %d is reached."),
14092                              bptnum);
14093           else if (count == 1)
14094             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14095                              bptnum);
14096           else
14097             printf_filtered (_("Will ignore next %d "
14098                                "crossings of breakpoint %d."),
14099                              count, bptnum);
14100         }
14101       observer_notify_breakpoint_modified (b);
14102       return;
14103     }
14104
14105   error (_("No breakpoint number %d."), bptnum);
14106 }
14107
14108 /* Command to set ignore-count of breakpoint N to COUNT.  */
14109
14110 static void
14111 ignore_command (char *args, int from_tty)
14112 {
14113   char *p = args;
14114   int num;
14115
14116   if (p == 0)
14117     error_no_arg (_("a breakpoint number"));
14118
14119   num = get_number (&p);
14120   if (num == 0)
14121     error (_("bad breakpoint number: '%s'"), args);
14122   if (*p == 0)
14123     error (_("Second argument (specified ignore-count) is missing."));
14124
14125   set_ignore_count (num,
14126                     longest_to_int (value_as_long (parse_and_eval (p))),
14127                     from_tty);
14128   if (from_tty)
14129     printf_filtered ("\n");
14130 }
14131 \f
14132
14133 /* Call FUNCTION on each of the breakpoints with numbers in the range
14134    defined by BP_NUM_RANGE (an inclusive range).  */
14135
14136 static void
14137 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
14138                              gdb::function_view<void (breakpoint *)> function)
14139 {
14140   if (bp_num_range.first == 0)
14141     {
14142       warning (_("bad breakpoint number at or near '%d'"),
14143                bp_num_range.first);
14144     }
14145   else
14146     {
14147       struct breakpoint *b, *tmp;
14148
14149       for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
14150         {
14151           bool match = false;
14152
14153           ALL_BREAKPOINTS_SAFE (b, tmp)
14154             if (b->number == i)
14155               {
14156                 match = true;
14157                 function (b);
14158                 break;
14159               }
14160           if (!match)
14161             printf_unfiltered (_("No breakpoint number %d.\n"), i);
14162         }
14163     }
14164 }
14165
14166 /* Call FUNCTION on each of the breakpoints whose numbers are given in
14167    ARGS.  */
14168
14169 static void
14170 map_breakpoint_numbers (const char *args,
14171                         gdb::function_view<void (breakpoint *)> function)
14172 {
14173   if (args == NULL || *args == '\0')
14174     error_no_arg (_("one or more breakpoint numbers"));
14175
14176   number_or_range_parser parser (args);
14177
14178   while (!parser.finished ())
14179     {
14180       int num = parser.get_number ();
14181       map_breakpoint_number_range (std::make_pair (num, num), function);
14182     }
14183 }
14184
14185 /* Return the breakpoint location structure corresponding to the
14186    BP_NUM and LOC_NUM values.  */
14187
14188 static struct bp_location *
14189 find_location_by_number (int bp_num, int loc_num)
14190 {
14191   struct breakpoint *b;
14192
14193   ALL_BREAKPOINTS (b)
14194     if (b->number == bp_num)
14195       {
14196         break;
14197       }
14198
14199   if (!b || b->number != bp_num)
14200     error (_("Bad breakpoint number '%d'"), bp_num);
14201   
14202   if (loc_num == 0)
14203     error (_("Bad breakpoint location number '%d'"), loc_num);
14204
14205   int n = 0;
14206   for (bp_location *loc = b->loc; loc != NULL; loc = loc->next)
14207     if (++n == loc_num)
14208       return loc;
14209
14210   error (_("Bad breakpoint location number '%d'"), loc_num);
14211 }
14212
14213 /* Modes of operation for extract_bp_num.  */
14214 enum class extract_bp_kind
14215 {
14216   /* Extracting a breakpoint number.  */
14217   bp,
14218
14219   /* Extracting a location number.  */
14220   loc,
14221 };
14222
14223 /* Extract a breakpoint or location number (as determined by KIND)
14224    from the string starting at START.  TRAILER is a character which
14225    can be found after the number.  If you don't want a trailer, use
14226    '\0'.  If END_OUT is not NULL, it is set to point after the parsed
14227    string.  This always returns a positive integer.  */
14228
14229 static int
14230 extract_bp_num (extract_bp_kind kind, const char *start,
14231                 int trailer, const char **end_out = NULL)
14232 {
14233   const char *end = start;
14234   int num = get_number_trailer (&end, trailer);
14235   if (num < 0)
14236     error (kind == extract_bp_kind::bp
14237            ? _("Negative breakpoint number '%.*s'")
14238            : _("Negative breakpoint location number '%.*s'"),
14239            int (end - start), start);
14240   if (num == 0)
14241     error (kind == extract_bp_kind::bp
14242            ? _("Bad breakpoint number '%.*s'")
14243            : _("Bad breakpoint location number '%.*s'"),
14244            int (end - start), start);
14245
14246   if (end_out != NULL)
14247     *end_out = end;
14248   return num;
14249 }
14250
14251 /* Extract a breakpoint or location range (as determined by KIND) in
14252    the form NUM1-NUM2 stored at &ARG[arg_offset].  Returns a std::pair
14253    representing the (inclusive) range.  The returned pair's elements
14254    are always positive integers.  */
14255
14256 static std::pair<int, int>
14257 extract_bp_or_bp_range (extract_bp_kind kind,
14258                         const std::string &arg,
14259                         std::string::size_type arg_offset)
14260 {
14261   std::pair<int, int> range;
14262   const char *bp_loc = &arg[arg_offset];
14263   std::string::size_type dash = arg.find ('-', arg_offset);
14264   if (dash != std::string::npos)
14265     {
14266       /* bp_loc is a range (x-z).  */
14267       if (arg.length () == dash + 1)
14268         error (kind == extract_bp_kind::bp
14269                ? _("Bad breakpoint number at or near: '%s'")
14270                : _("Bad breakpoint location number at or near: '%s'"),
14271                bp_loc);
14272
14273       const char *end;
14274       const char *start_first = bp_loc;
14275       const char *start_second = &arg[dash + 1];
14276       range.first = extract_bp_num (kind, start_first, '-');
14277       range.second = extract_bp_num (kind, start_second, '\0', &end);
14278
14279       if (range.first > range.second)
14280         error (kind == extract_bp_kind::bp
14281                ? _("Inverted breakpoint range at '%.*s'")
14282                : _("Inverted breakpoint location range at '%.*s'"),
14283                int (end - start_first), start_first);
14284     }
14285   else
14286     {
14287       /* bp_loc is a single value.  */
14288       range.first = extract_bp_num (kind, bp_loc, '\0');
14289       range.second = range.first;
14290     }
14291   return range;
14292 }
14293
14294 /* Extract the breakpoint/location range specified by ARG.  Returns
14295    the breakpoint range in BP_NUM_RANGE, and the location range in
14296    BP_LOC_RANGE.
14297
14298    ARG may be in any of the following forms:
14299
14300    x     where 'x' is a breakpoint number.
14301    x-y   where 'x' and 'y' specify a breakpoint numbers range.
14302    x.y   where 'x' is a breakpoint number and 'y' a location number.
14303    x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
14304          location number range.
14305 */
14306
14307 static void
14308 extract_bp_number_and_location (const std::string &arg,
14309                                 std::pair<int, int> &bp_num_range,
14310                                 std::pair<int, int> &bp_loc_range)
14311 {
14312   std::string::size_type dot = arg.find ('.');
14313
14314   if (dot != std::string::npos)
14315     {
14316       /* Handle 'x.y' and 'x.y-z' cases.  */
14317
14318       if (arg.length () == dot + 1 || dot == 0)
14319         error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
14320
14321       bp_num_range.first
14322         = extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
14323       bp_num_range.second = bp_num_range.first;
14324
14325       bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
14326                                              arg, dot + 1);
14327     }
14328   else
14329     {
14330       /* Handle x and x-y cases.  */
14331
14332       bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
14333       bp_loc_range.first = 0;
14334       bp_loc_range.second = 0;
14335     }
14336 }
14337
14338 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM.  ENABLE
14339    specifies whether to enable or disable.  */
14340
14341 static void
14342 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
14343 {
14344   struct bp_location *loc = find_location_by_number (bp_num, loc_num);
14345   if (loc != NULL)
14346     {
14347       if (loc->enabled != enable)
14348         {
14349           loc->enabled = enable;
14350           mark_breakpoint_location_modified (loc);
14351         }
14352       if (target_supports_enable_disable_tracepoint ()
14353           && current_trace_status ()->running && loc->owner
14354           && is_tracepoint (loc->owner))
14355         target_disable_tracepoint (loc);
14356     }
14357   update_global_location_list (UGLL_DONT_INSERT);
14358 }
14359
14360 /* Enable or disable a range of breakpoint locations.  BP_NUM is the
14361    number of the breakpoint, and BP_LOC_RANGE specifies the
14362    (inclusive) range of location numbers of that breakpoint to
14363    enable/disable.  ENABLE specifies whether to enable or disable the
14364    location.  */
14365
14366 static void
14367 enable_disable_breakpoint_location_range (int bp_num,
14368                                           std::pair<int, int> &bp_loc_range,
14369                                           bool enable)
14370 {
14371   for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
14372     enable_disable_bp_num_loc (bp_num, i, enable);
14373 }
14374
14375 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14376    If from_tty is nonzero, it prints a message to that effect,
14377    which ends with a period (no newline).  */
14378
14379 void
14380 disable_breakpoint (struct breakpoint *bpt)
14381 {
14382   /* Never disable a watchpoint scope breakpoint; we want to
14383      hit them when we leave scope so we can delete both the
14384      watchpoint and its scope breakpoint at that time.  */
14385   if (bpt->type == bp_watchpoint_scope)
14386     return;
14387
14388   bpt->enable_state = bp_disabled;
14389
14390   /* Mark breakpoint locations modified.  */
14391   mark_breakpoint_modified (bpt);
14392
14393   if (target_supports_enable_disable_tracepoint ()
14394       && current_trace_status ()->running && is_tracepoint (bpt))
14395     {
14396       struct bp_location *location;
14397      
14398       for (location = bpt->loc; location; location = location->next)
14399         target_disable_tracepoint (location);
14400     }
14401
14402   update_global_location_list (UGLL_DONT_INSERT);
14403
14404   observer_notify_breakpoint_modified (bpt);
14405 }
14406
14407 /* Enable or disable the breakpoint(s) or breakpoint location(s)
14408    specified in ARGS.  ARGS may be in any of the formats handled by
14409    extract_bp_number_and_location.  ENABLE specifies whether to enable
14410    or disable the breakpoints/locations.  */
14411
14412 static void
14413 enable_disable_command (const char *args, int from_tty, bool enable)
14414 {
14415   if (args == 0)
14416     {
14417       struct breakpoint *bpt;
14418
14419       ALL_BREAKPOINTS (bpt)
14420         if (user_breakpoint_p (bpt))
14421           {
14422             if (enable)
14423               enable_breakpoint (bpt);
14424             else
14425               disable_breakpoint (bpt);
14426           }
14427     }
14428   else
14429     {
14430       std::string num = extract_arg (&args);
14431
14432       while (!num.empty ())
14433         {
14434           std::pair<int, int> bp_num_range, bp_loc_range;
14435
14436           extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
14437
14438           if (bp_loc_range.first == bp_loc_range.second
14439               && bp_loc_range.first == 0)
14440             {
14441               /* Handle breakpoint ids with formats 'x' or 'x-z'.  */
14442               map_breakpoint_number_range (bp_num_range,
14443                                            enable
14444                                            ? enable_breakpoint
14445                                            : disable_breakpoint);
14446             }
14447           else
14448             {
14449               /* Handle breakpoint ids with formats 'x.y' or
14450                  'x.y-z'.  */
14451               enable_disable_breakpoint_location_range
14452                 (bp_num_range.first, bp_loc_range, enable);
14453             }
14454           num = extract_arg (&args);
14455         }
14456     }
14457 }
14458
14459 /* The disable command disables the specified breakpoints/locations
14460    (or all defined breakpoints) so they're no longer effective in
14461    stopping the inferior.  ARGS may be in any of the forms defined in
14462    extract_bp_number_and_location.  */
14463
14464 static void
14465 disable_command (const char *args, int from_tty)
14466 {
14467   enable_disable_command (args, from_tty, false);
14468 }
14469
14470 static void
14471 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14472                         int count)
14473 {
14474   int target_resources_ok;
14475
14476   if (bpt->type == bp_hardware_breakpoint)
14477     {
14478       int i;
14479       i = hw_breakpoint_used_count ();
14480       target_resources_ok = 
14481         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14482                                             i + 1, 0);
14483       if (target_resources_ok == 0)
14484         error (_("No hardware breakpoint support in the target."));
14485       else if (target_resources_ok < 0)
14486         error (_("Hardware breakpoints used exceeds limit."));
14487     }
14488
14489   if (is_watchpoint (bpt))
14490     {
14491       /* Initialize it just to avoid a GCC false warning.  */
14492       enum enable_state orig_enable_state = bp_disabled;
14493
14494       TRY
14495         {
14496           struct watchpoint *w = (struct watchpoint *) bpt;
14497
14498           orig_enable_state = bpt->enable_state;
14499           bpt->enable_state = bp_enabled;
14500           update_watchpoint (w, 1 /* reparse */);
14501         }
14502       CATCH (e, RETURN_MASK_ALL)
14503         {
14504           bpt->enable_state = orig_enable_state;
14505           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14506                              bpt->number);
14507           return;
14508         }
14509       END_CATCH
14510     }
14511
14512   bpt->enable_state = bp_enabled;
14513
14514   /* Mark breakpoint locations modified.  */
14515   mark_breakpoint_modified (bpt);
14516
14517   if (target_supports_enable_disable_tracepoint ()
14518       && current_trace_status ()->running && is_tracepoint (bpt))
14519     {
14520       struct bp_location *location;
14521
14522       for (location = bpt->loc; location; location = location->next)
14523         target_enable_tracepoint (location);
14524     }
14525
14526   bpt->disposition = disposition;
14527   bpt->enable_count = count;
14528   update_global_location_list (UGLL_MAY_INSERT);
14529
14530   observer_notify_breakpoint_modified (bpt);
14531 }
14532
14533
14534 void
14535 enable_breakpoint (struct breakpoint *bpt)
14536 {
14537   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14538 }
14539
14540 /* The enable command enables the specified breakpoints/locations (or
14541    all defined breakpoints) so they once again become (or continue to
14542    be) effective in stopping the inferior.  ARGS may be in any of the
14543    forms defined in extract_bp_number_and_location.  */
14544
14545 static void
14546 enable_command (const char *args, int from_tty)
14547 {
14548   enable_disable_command (args, from_tty, true);
14549 }
14550
14551 static void
14552 enable_once_command (const char *args, int from_tty)
14553 {
14554   map_breakpoint_numbers
14555     (args, [&] (breakpoint *b)
14556      {
14557        iterate_over_related_breakpoints
14558          (b, [&] (breakpoint *bpt)
14559           {
14560             enable_breakpoint_disp (bpt, disp_disable, 1);
14561           });
14562      });
14563 }
14564
14565 static void
14566 enable_count_command (const char *args, int from_tty)
14567 {
14568   int count;
14569
14570   if (args == NULL)
14571     error_no_arg (_("hit count"));
14572
14573   count = get_number (&args);
14574
14575   map_breakpoint_numbers
14576     (args, [&] (breakpoint *b)
14577      {
14578        iterate_over_related_breakpoints
14579          (b, [&] (breakpoint *bpt)
14580           {
14581             enable_breakpoint_disp (bpt, disp_disable, count);
14582           });
14583      });
14584 }
14585
14586 static void
14587 enable_delete_command (const char *args, int from_tty)
14588 {
14589   map_breakpoint_numbers
14590     (args, [&] (breakpoint *b)
14591      {
14592        iterate_over_related_breakpoints
14593          (b, [&] (breakpoint *bpt)
14594           {
14595             enable_breakpoint_disp (bpt, disp_del, 1);
14596           });
14597      });
14598 }
14599 \f
14600 static void
14601 set_breakpoint_cmd (const char *args, int from_tty)
14602 {
14603 }
14604
14605 static void
14606 show_breakpoint_cmd (const char *args, int from_tty)
14607 {
14608 }
14609
14610 /* Invalidate last known value of any hardware watchpoint if
14611    the memory which that value represents has been written to by
14612    GDB itself.  */
14613
14614 static void
14615 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14616                                       CORE_ADDR addr, ssize_t len,
14617                                       const bfd_byte *data)
14618 {
14619   struct breakpoint *bp;
14620
14621   ALL_BREAKPOINTS (bp)
14622     if (bp->enable_state == bp_enabled
14623         && bp->type == bp_hardware_watchpoint)
14624       {
14625         struct watchpoint *wp = (struct watchpoint *) bp;
14626
14627         if (wp->val_valid && wp->val)
14628           {
14629             struct bp_location *loc;
14630
14631             for (loc = bp->loc; loc != NULL; loc = loc->next)
14632               if (loc->loc_type == bp_loc_hardware_watchpoint
14633                   && loc->address + loc->length > addr
14634                   && addr + len > loc->address)
14635                 {
14636                   value_free (wp->val);
14637                   wp->val = NULL;
14638                   wp->val_valid = 0;
14639                 }
14640           }
14641       }
14642 }
14643
14644 /* Create and insert a breakpoint for software single step.  */
14645
14646 void
14647 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14648                                const address_space *aspace,
14649                                CORE_ADDR next_pc)
14650 {
14651   struct thread_info *tp = inferior_thread ();
14652   struct symtab_and_line sal;
14653   CORE_ADDR pc = next_pc;
14654
14655   if (tp->control.single_step_breakpoints == NULL)
14656     {
14657       tp->control.single_step_breakpoints
14658         = new_single_step_breakpoint (tp->global_num, gdbarch);
14659     }
14660
14661   sal = find_pc_line (pc, 0);
14662   sal.pc = pc;
14663   sal.section = find_pc_overlay (pc);
14664   sal.explicit_pc = 1;
14665   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14666
14667   update_global_location_list (UGLL_INSERT);
14668 }
14669
14670 /* Insert single step breakpoints according to the current state.  */
14671
14672 int
14673 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14674 {
14675   struct regcache *regcache = get_current_regcache ();
14676   std::vector<CORE_ADDR> next_pcs;
14677
14678   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14679
14680   if (!next_pcs.empty ())
14681     {
14682       struct frame_info *frame = get_current_frame ();
14683       const address_space *aspace = get_frame_address_space (frame);
14684
14685       for (CORE_ADDR pc : next_pcs)
14686         insert_single_step_breakpoint (gdbarch, aspace, pc);
14687
14688       return 1;
14689     }
14690   else
14691     return 0;
14692 }
14693
14694 /* See breakpoint.h.  */
14695
14696 int
14697 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14698                                        const address_space *aspace,
14699                                        CORE_ADDR pc)
14700 {
14701   struct bp_location *loc;
14702
14703   for (loc = bp->loc; loc != NULL; loc = loc->next)
14704     if (loc->inserted
14705         && breakpoint_location_address_match (loc, aspace, pc))
14706       return 1;
14707
14708   return 0;
14709 }
14710
14711 /* Check whether a software single-step breakpoint is inserted at
14712    PC.  */
14713
14714 int
14715 single_step_breakpoint_inserted_here_p (const address_space *aspace,
14716                                         CORE_ADDR pc)
14717 {
14718   struct breakpoint *bpt;
14719
14720   ALL_BREAKPOINTS (bpt)
14721     {
14722       if (bpt->type == bp_single_step
14723           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
14724         return 1;
14725     }
14726   return 0;
14727 }
14728
14729 /* Tracepoint-specific operations.  */
14730
14731 /* Set tracepoint count to NUM.  */
14732 static void
14733 set_tracepoint_count (int num)
14734 {
14735   tracepoint_count = num;
14736   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14737 }
14738
14739 static void
14740 trace_command (char *arg_in, int from_tty)
14741 {
14742   const char *arg = arg_in;
14743   struct breakpoint_ops *ops;
14744
14745   event_location_up location = string_to_event_location (&arg,
14746                                                          current_language);
14747   if (location != NULL
14748       && event_location_type (location.get ()) == PROBE_LOCATION)
14749     ops = &tracepoint_probe_breakpoint_ops;
14750   else
14751     ops = &tracepoint_breakpoint_ops;
14752
14753   create_breakpoint (get_current_arch (),
14754                      location.get (),
14755                      NULL, 0, arg, 1 /* parse arg */,
14756                      0 /* tempflag */,
14757                      bp_tracepoint /* type_wanted */,
14758                      0 /* Ignore count */,
14759                      pending_break_support,
14760                      ops,
14761                      from_tty,
14762                      1 /* enabled */,
14763                      0 /* internal */, 0);
14764 }
14765
14766 static void
14767 ftrace_command (char *arg_in, int from_tty)
14768 {
14769   const char *arg = arg_in;
14770   event_location_up location = string_to_event_location (&arg,
14771                                                          current_language);
14772   create_breakpoint (get_current_arch (),
14773                      location.get (),
14774                      NULL, 0, arg, 1 /* parse arg */,
14775                      0 /* tempflag */,
14776                      bp_fast_tracepoint /* type_wanted */,
14777                      0 /* Ignore count */,
14778                      pending_break_support,
14779                      &tracepoint_breakpoint_ops,
14780                      from_tty,
14781                      1 /* enabled */,
14782                      0 /* internal */, 0);
14783 }
14784
14785 /* strace command implementation.  Creates a static tracepoint.  */
14786
14787 static void
14788 strace_command (char *arg_in, int from_tty)
14789 {
14790   const char *arg = arg_in;
14791   struct breakpoint_ops *ops;
14792   event_location_up location;
14793
14794   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14795      or with a normal static tracepoint.  */
14796   if (arg && startswith (arg, "-m") && isspace (arg[2]))
14797     {
14798       ops = &strace_marker_breakpoint_ops;
14799       location = new_linespec_location (&arg);
14800     }
14801   else
14802     {
14803       ops = &tracepoint_breakpoint_ops;
14804       location = string_to_event_location (&arg, current_language);
14805     }
14806
14807   create_breakpoint (get_current_arch (),
14808                      location.get (),
14809                      NULL, 0, arg, 1 /* parse arg */,
14810                      0 /* tempflag */,
14811                      bp_static_tracepoint /* type_wanted */,
14812                      0 /* Ignore count */,
14813                      pending_break_support,
14814                      ops,
14815                      from_tty,
14816                      1 /* enabled */,
14817                      0 /* internal */, 0);
14818 }
14819
14820 /* Set up a fake reader function that gets command lines from a linked
14821    list that was acquired during tracepoint uploading.  */
14822
14823 static struct uploaded_tp *this_utp;
14824 static int next_cmd;
14825
14826 static char *
14827 read_uploaded_action (void)
14828 {
14829   char *rslt;
14830
14831   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
14832
14833   next_cmd++;
14834
14835   return rslt;
14836 }
14837
14838 /* Given information about a tracepoint as recorded on a target (which
14839    can be either a live system or a trace file), attempt to create an
14840    equivalent GDB tracepoint.  This is not a reliable process, since
14841    the target does not necessarily have all the information used when
14842    the tracepoint was originally defined.  */
14843   
14844 struct tracepoint *
14845 create_tracepoint_from_upload (struct uploaded_tp *utp)
14846 {
14847   const char *addr_str;
14848   char small_buf[100];
14849   struct tracepoint *tp;
14850
14851   if (utp->at_string)
14852     addr_str = utp->at_string;
14853   else
14854     {
14855       /* In the absence of a source location, fall back to raw
14856          address.  Since there is no way to confirm that the address
14857          means the same thing as when the trace was started, warn the
14858          user.  */
14859       warning (_("Uploaded tracepoint %d has no "
14860                  "source location, using raw address"),
14861                utp->number);
14862       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14863       addr_str = small_buf;
14864     }
14865
14866   /* There's not much we can do with a sequence of bytecodes.  */
14867   if (utp->cond && !utp->cond_string)
14868     warning (_("Uploaded tracepoint %d condition "
14869                "has no source form, ignoring it"),
14870              utp->number);
14871
14872   event_location_up location = string_to_event_location (&addr_str,
14873                                                          current_language);
14874   if (!create_breakpoint (get_current_arch (),
14875                           location.get (),
14876                           utp->cond_string, -1, addr_str,
14877                           0 /* parse cond/thread */,
14878                           0 /* tempflag */,
14879                           utp->type /* type_wanted */,
14880                           0 /* Ignore count */,
14881                           pending_break_support,
14882                           &tracepoint_breakpoint_ops,
14883                           0 /* from_tty */,
14884                           utp->enabled /* enabled */,
14885                           0 /* internal */,
14886                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14887     return NULL;
14888
14889   /* Get the tracepoint we just created.  */
14890   tp = get_tracepoint (tracepoint_count);
14891   gdb_assert (tp != NULL);
14892
14893   if (utp->pass > 0)
14894     {
14895       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14896                  tp->number);
14897
14898       trace_pass_command (small_buf, 0);
14899     }
14900
14901   /* If we have uploaded versions of the original commands, set up a
14902      special-purpose "reader" function and call the usual command line
14903      reader, then pass the result to the breakpoint command-setting
14904      function.  */
14905   if (!VEC_empty (char_ptr, utp->cmd_strings))
14906     {
14907       command_line_up cmd_list;
14908
14909       this_utp = utp;
14910       next_cmd = 0;
14911
14912       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
14913
14914       breakpoint_set_commands (tp, std::move (cmd_list));
14915     }
14916   else if (!VEC_empty (char_ptr, utp->actions)
14917            || !VEC_empty (char_ptr, utp->step_actions))
14918     warning (_("Uploaded tracepoint %d actions "
14919                "have no source form, ignoring them"),
14920              utp->number);
14921
14922   /* Copy any status information that might be available.  */
14923   tp->hit_count = utp->hit_count;
14924   tp->traceframe_usage = utp->traceframe_usage;
14925
14926   return tp;
14927 }
14928   
14929 /* Print information on tracepoint number TPNUM_EXP, or all if
14930    omitted.  */
14931
14932 static void
14933 info_tracepoints_command (char *args, int from_tty)
14934 {
14935   struct ui_out *uiout = current_uiout;
14936   int num_printed;
14937
14938   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14939
14940   if (num_printed == 0)
14941     {
14942       if (args == NULL || *args == '\0')
14943         uiout->message ("No tracepoints.\n");
14944       else
14945         uiout->message ("No tracepoint matching '%s'.\n", args);
14946     }
14947
14948   default_collect_info ();
14949 }
14950
14951 /* The 'enable trace' command enables tracepoints.
14952    Not supported by all targets.  */
14953 static void
14954 enable_trace_command (char *args, int from_tty)
14955 {
14956   enable_command (args, from_tty);
14957 }
14958
14959 /* The 'disable trace' command disables tracepoints.
14960    Not supported by all targets.  */
14961 static void
14962 disable_trace_command (char *args, int from_tty)
14963 {
14964   disable_command (args, from_tty);
14965 }
14966
14967 /* Remove a tracepoint (or all if no argument).  */
14968 static void
14969 delete_trace_command (const char *arg, int from_tty)
14970 {
14971   struct breakpoint *b, *b_tmp;
14972
14973   dont_repeat ();
14974
14975   if (arg == 0)
14976     {
14977       int breaks_to_delete = 0;
14978
14979       /* Delete all breakpoints if no argument.
14980          Do not delete internal or call-dummy breakpoints, these
14981          have to be deleted with an explicit breakpoint number 
14982          argument.  */
14983       ALL_TRACEPOINTS (b)
14984         if (is_tracepoint (b) && user_breakpoint_p (b))
14985           {
14986             breaks_to_delete = 1;
14987             break;
14988           }
14989
14990       /* Ask user only if there are some breakpoints to delete.  */
14991       if (!from_tty
14992           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14993         {
14994           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14995             if (is_tracepoint (b) && user_breakpoint_p (b))
14996               delete_breakpoint (b);
14997         }
14998     }
14999   else
15000     map_breakpoint_numbers
15001       (arg, [&] (breakpoint *b)
15002        {
15003          iterate_over_related_breakpoints (b, delete_breakpoint);
15004        });
15005 }
15006
15007 /* Helper function for trace_pass_command.  */
15008
15009 static void
15010 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15011 {
15012   tp->pass_count = count;
15013   observer_notify_breakpoint_modified (tp);
15014   if (from_tty)
15015     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15016                      tp->number, count);
15017 }
15018
15019 /* Set passcount for tracepoint.
15020
15021    First command argument is passcount, second is tracepoint number.
15022    If tracepoint number omitted, apply to most recently defined.
15023    Also accepts special argument "all".  */
15024
15025 static void
15026 trace_pass_command (char *args, int from_tty)
15027 {
15028   struct tracepoint *t1;
15029   unsigned int count;
15030
15031   if (args == 0 || *args == 0)
15032     error (_("passcount command requires an "
15033              "argument (count + optional TP num)"));
15034
15035   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15036
15037   args = skip_spaces (args);
15038   if (*args && strncasecmp (args, "all", 3) == 0)
15039     {
15040       struct breakpoint *b;
15041
15042       args += 3;                        /* Skip special argument "all".  */
15043       if (*args)
15044         error (_("Junk at end of arguments."));
15045
15046       ALL_TRACEPOINTS (b)
15047       {
15048         t1 = (struct tracepoint *) b;
15049         trace_pass_set_count (t1, count, from_tty);
15050       }
15051     }
15052   else if (*args == '\0')
15053     {
15054       t1 = get_tracepoint_by_number (&args, NULL);
15055       if (t1)
15056         trace_pass_set_count (t1, count, from_tty);
15057     }
15058   else
15059     {
15060       number_or_range_parser parser (args);
15061       while (!parser.finished ())
15062         {
15063           t1 = get_tracepoint_by_number (&args, &parser);
15064           if (t1)
15065             trace_pass_set_count (t1, count, from_tty);
15066         }
15067     }
15068 }
15069
15070 struct tracepoint *
15071 get_tracepoint (int num)
15072 {
15073   struct breakpoint *t;
15074
15075   ALL_TRACEPOINTS (t)
15076     if (t->number == num)
15077       return (struct tracepoint *) t;
15078
15079   return NULL;
15080 }
15081
15082 /* Find the tracepoint with the given target-side number (which may be
15083    different from the tracepoint number after disconnecting and
15084    reconnecting).  */
15085
15086 struct tracepoint *
15087 get_tracepoint_by_number_on_target (int num)
15088 {
15089   struct breakpoint *b;
15090
15091   ALL_TRACEPOINTS (b)
15092     {
15093       struct tracepoint *t = (struct tracepoint *) b;
15094
15095       if (t->number_on_target == num)
15096         return t;
15097     }
15098
15099   return NULL;
15100 }
15101
15102 /* Utility: parse a tracepoint number and look it up in the list.
15103    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15104    If the argument is missing, the most recent tracepoint
15105    (tracepoint_count) is returned.  */
15106
15107 struct tracepoint *
15108 get_tracepoint_by_number (char **arg,
15109                           number_or_range_parser *parser)
15110 {
15111   struct breakpoint *t;
15112   int tpnum;
15113   char *instring = arg == NULL ? NULL : *arg;
15114
15115   if (parser != NULL)
15116     {
15117       gdb_assert (!parser->finished ());
15118       tpnum = parser->get_number ();
15119     }
15120   else if (arg == NULL || *arg == NULL || ! **arg)
15121     tpnum = tracepoint_count;
15122   else
15123     tpnum = get_number (arg);
15124
15125   if (tpnum <= 0)
15126     {
15127       if (instring && *instring)
15128         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15129                          instring);
15130       else
15131         printf_filtered (_("No previous tracepoint\n"));
15132       return NULL;
15133     }
15134
15135   ALL_TRACEPOINTS (t)
15136     if (t->number == tpnum)
15137     {
15138       return (struct tracepoint *) t;
15139     }
15140
15141   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15142   return NULL;
15143 }
15144
15145 void
15146 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15147 {
15148   if (b->thread != -1)
15149     fprintf_unfiltered (fp, " thread %d", b->thread);
15150
15151   if (b->task != 0)
15152     fprintf_unfiltered (fp, " task %d", b->task);
15153
15154   fprintf_unfiltered (fp, "\n");
15155 }
15156
15157 /* Save information on user settable breakpoints (watchpoints, etc) to
15158    a new script file named FILENAME.  If FILTER is non-NULL, call it
15159    on each breakpoint and only include the ones for which it returns
15160    non-zero.  */
15161
15162 static void
15163 save_breakpoints (const char *filename, int from_tty,
15164                   int (*filter) (const struct breakpoint *))
15165 {
15166   struct breakpoint *tp;
15167   int any = 0;
15168   int extra_trace_bits = 0;
15169
15170   if (filename == 0 || *filename == 0)
15171     error (_("Argument required (file name in which to save)"));
15172
15173   /* See if we have anything to save.  */
15174   ALL_BREAKPOINTS (tp)
15175   {
15176     /* Skip internal and momentary breakpoints.  */
15177     if (!user_breakpoint_p (tp))
15178       continue;
15179
15180     /* If we have a filter, only save the breakpoints it accepts.  */
15181     if (filter && !filter (tp))
15182       continue;
15183
15184     any = 1;
15185
15186     if (is_tracepoint (tp))
15187       {
15188         extra_trace_bits = 1;
15189
15190         /* We can stop searching.  */
15191         break;
15192       }
15193   }
15194
15195   if (!any)
15196     {
15197       warning (_("Nothing to save."));
15198       return;
15199     }
15200
15201   gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
15202
15203   stdio_file fp;
15204
15205   if (!fp.open (expanded_filename.get (), "w"))
15206     error (_("Unable to open file '%s' for saving (%s)"),
15207            expanded_filename.get (), safe_strerror (errno));
15208
15209   if (extra_trace_bits)
15210     save_trace_state_variables (&fp);
15211
15212   ALL_BREAKPOINTS (tp)
15213   {
15214     /* Skip internal and momentary breakpoints.  */
15215     if (!user_breakpoint_p (tp))
15216       continue;
15217
15218     /* If we have a filter, only save the breakpoints it accepts.  */
15219     if (filter && !filter (tp))
15220       continue;
15221
15222     tp->ops->print_recreate (tp, &fp);
15223
15224     /* Note, we can't rely on tp->number for anything, as we can't
15225        assume the recreated breakpoint numbers will match.  Use $bpnum
15226        instead.  */
15227
15228     if (tp->cond_string)
15229       fp.printf ("  condition $bpnum %s\n", tp->cond_string);
15230
15231     if (tp->ignore_count)
15232       fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15233
15234     if (tp->type != bp_dprintf && tp->commands)
15235       {
15236         fp.puts ("  commands\n");
15237         
15238         current_uiout->redirect (&fp);
15239         TRY
15240           {
15241             print_command_lines (current_uiout, tp->commands.get (), 2);
15242           }
15243         CATCH (ex, RETURN_MASK_ALL)
15244           {
15245           current_uiout->redirect (NULL);
15246             throw_exception (ex);
15247           }
15248         END_CATCH
15249
15250         current_uiout->redirect (NULL);
15251         fp.puts ("  end\n");
15252       }
15253
15254     if (tp->enable_state == bp_disabled)
15255       fp.puts ("disable $bpnum\n");
15256
15257     /* If this is a multi-location breakpoint, check if the locations
15258        should be individually disabled.  Watchpoint locations are
15259        special, and not user visible.  */
15260     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15261       {
15262         struct bp_location *loc;
15263         int n = 1;
15264
15265         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15266           if (!loc->enabled)
15267             fp.printf ("disable $bpnum.%d\n", n);
15268       }
15269   }
15270
15271   if (extra_trace_bits && *default_collect)
15272     fp.printf ("set default-collect %s\n", default_collect);
15273
15274   if (from_tty)
15275     printf_filtered (_("Saved to file '%s'.\n"), expanded_filename.get ());
15276 }
15277
15278 /* The `save breakpoints' command.  */
15279
15280 static void
15281 save_breakpoints_command (const char *args, int from_tty)
15282 {
15283   save_breakpoints (args, from_tty, NULL);
15284 }
15285
15286 /* The `save tracepoints' command.  */
15287
15288 static void
15289 save_tracepoints_command (const char *args, int from_tty)
15290 {
15291   save_breakpoints (args, from_tty, is_tracepoint);
15292 }
15293
15294 /* Create a vector of all tracepoints.  */
15295
15296 VEC(breakpoint_p) *
15297 all_tracepoints (void)
15298 {
15299   VEC(breakpoint_p) *tp_vec = 0;
15300   struct breakpoint *tp;
15301
15302   ALL_TRACEPOINTS (tp)
15303   {
15304     VEC_safe_push (breakpoint_p, tp_vec, tp);
15305   }
15306
15307   return tp_vec;
15308 }
15309
15310 \f
15311 /* This help string is used to consolidate all the help string for specifying
15312    locations used by several commands.  */
15313
15314 #define LOCATION_HELP_STRING \
15315 "Linespecs are colon-separated lists of location parameters, such as\n\
15316 source filename, function name, label name, and line number.\n\
15317 Example: To specify the start of a label named \"the_top\" in the\n\
15318 function \"fact\" in the file \"factorial.c\", use\n\
15319 \"factorial.c:fact:the_top\".\n\
15320 \n\
15321 Address locations begin with \"*\" and specify an exact address in the\n\
15322 program.  Example: To specify the fourth byte past the start function\n\
15323 \"main\", use \"*main + 4\".\n\
15324 \n\
15325 Explicit locations are similar to linespecs but use an option/argument\n\
15326 syntax to specify location parameters.\n\
15327 Example: To specify the start of the label named \"the_top\" in the\n\
15328 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15329 -function fact -label the_top\".\n"
15330
15331 /* This help string is used for the break, hbreak, tbreak and thbreak
15332    commands.  It is defined as a macro to prevent duplication.
15333    COMMAND should be a string constant containing the name of the
15334    command.  */
15335
15336 #define BREAK_ARGS_HELP(command) \
15337 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15338 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15339 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15340 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15341 `-probe-dtrace' (for a DTrace probe).\n\
15342 LOCATION may be a linespec, address, or explicit location as described\n\
15343 below.\n\
15344 \n\
15345 With no LOCATION, uses current execution address of the selected\n\
15346 stack frame.  This is useful for breaking on return to a stack frame.\n\
15347 \n\
15348 THREADNUM is the number from \"info threads\".\n\
15349 CONDITION is a boolean expression.\n\
15350 \n" LOCATION_HELP_STRING "\n\
15351 Multiple breakpoints at one place are permitted, and useful if their\n\
15352 conditions are different.\n\
15353 \n\
15354 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15355
15356 /* List of subcommands for "catch".  */
15357 static struct cmd_list_element *catch_cmdlist;
15358
15359 /* List of subcommands for "tcatch".  */
15360 static struct cmd_list_element *tcatch_cmdlist;
15361
15362 void
15363 add_catch_command (const char *name, const char *docstring,
15364                    cmd_sfunc_ftype *sfunc,
15365                    completer_ftype *completer,
15366                    void *user_data_catch,
15367                    void *user_data_tcatch)
15368 {
15369   struct cmd_list_element *command;
15370
15371   command = add_cmd (name, class_breakpoint, docstring,
15372                      &catch_cmdlist);
15373   set_cmd_sfunc (command, sfunc);
15374   set_cmd_context (command, user_data_catch);
15375   set_cmd_completer (command, completer);
15376
15377   command = add_cmd (name, class_breakpoint, docstring,
15378                      &tcatch_cmdlist);
15379   set_cmd_sfunc (command, sfunc);
15380   set_cmd_context (command, user_data_tcatch);
15381   set_cmd_completer (command, completer);
15382 }
15383
15384 static void
15385 save_command (const char *arg, int from_tty)
15386 {
15387   printf_unfiltered (_("\"save\" must be followed by "
15388                        "the name of a save subcommand.\n"));
15389   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15390 }
15391
15392 struct breakpoint *
15393 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15394                           void *data)
15395 {
15396   struct breakpoint *b, *b_tmp;
15397
15398   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15399     {
15400       if ((*callback) (b, data))
15401         return b;
15402     }
15403
15404   return NULL;
15405 }
15406
15407 /* Zero if any of the breakpoint's locations could be a location where
15408    functions have been inlined, nonzero otherwise.  */
15409
15410 static int
15411 is_non_inline_function (struct breakpoint *b)
15412 {
15413   /* The shared library event breakpoint is set on the address of a
15414      non-inline function.  */
15415   if (b->type == bp_shlib_event)
15416     return 1;
15417
15418   return 0;
15419 }
15420
15421 /* Nonzero if the specified PC cannot be a location where functions
15422    have been inlined.  */
15423
15424 int
15425 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
15426                            const struct target_waitstatus *ws)
15427 {
15428   struct breakpoint *b;
15429   struct bp_location *bl;
15430
15431   ALL_BREAKPOINTS (b)
15432     {
15433       if (!is_non_inline_function (b))
15434         continue;
15435
15436       for (bl = b->loc; bl != NULL; bl = bl->next)
15437         {
15438           if (!bl->shlib_disabled
15439               && bpstat_check_location (bl, aspace, pc, ws))
15440             return 1;
15441         }
15442     }
15443
15444   return 0;
15445 }
15446
15447 /* Remove any references to OBJFILE which is going to be freed.  */
15448
15449 void
15450 breakpoint_free_objfile (struct objfile *objfile)
15451 {
15452   struct bp_location **locp, *loc;
15453
15454   ALL_BP_LOCATIONS (loc, locp)
15455     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15456       loc->symtab = NULL;
15457 }
15458
15459 void
15460 initialize_breakpoint_ops (void)
15461 {
15462   static int initialized = 0;
15463
15464   struct breakpoint_ops *ops;
15465
15466   if (initialized)
15467     return;
15468   initialized = 1;
15469
15470   /* The breakpoint_ops structure to be inherit by all kinds of
15471      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15472      internal and momentary breakpoints, etc.).  */
15473   ops = &bkpt_base_breakpoint_ops;
15474   *ops = base_breakpoint_ops;
15475   ops->re_set = bkpt_re_set;
15476   ops->insert_location = bkpt_insert_location;
15477   ops->remove_location = bkpt_remove_location;
15478   ops->breakpoint_hit = bkpt_breakpoint_hit;
15479   ops->create_sals_from_location = bkpt_create_sals_from_location;
15480   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15481   ops->decode_location = bkpt_decode_location;
15482
15483   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15484   ops = &bkpt_breakpoint_ops;
15485   *ops = bkpt_base_breakpoint_ops;
15486   ops->re_set = bkpt_re_set;
15487   ops->resources_needed = bkpt_resources_needed;
15488   ops->print_it = bkpt_print_it;
15489   ops->print_mention = bkpt_print_mention;
15490   ops->print_recreate = bkpt_print_recreate;
15491
15492   /* Ranged breakpoints.  */
15493   ops = &ranged_breakpoint_ops;
15494   *ops = bkpt_breakpoint_ops;
15495   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15496   ops->resources_needed = resources_needed_ranged_breakpoint;
15497   ops->print_it = print_it_ranged_breakpoint;
15498   ops->print_one = print_one_ranged_breakpoint;
15499   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15500   ops->print_mention = print_mention_ranged_breakpoint;
15501   ops->print_recreate = print_recreate_ranged_breakpoint;
15502
15503   /* Internal breakpoints.  */
15504   ops = &internal_breakpoint_ops;
15505   *ops = bkpt_base_breakpoint_ops;
15506   ops->re_set = internal_bkpt_re_set;
15507   ops->check_status = internal_bkpt_check_status;
15508   ops->print_it = internal_bkpt_print_it;
15509   ops->print_mention = internal_bkpt_print_mention;
15510
15511   /* Momentary breakpoints.  */
15512   ops = &momentary_breakpoint_ops;
15513   *ops = bkpt_base_breakpoint_ops;
15514   ops->re_set = momentary_bkpt_re_set;
15515   ops->check_status = momentary_bkpt_check_status;
15516   ops->print_it = momentary_bkpt_print_it;
15517   ops->print_mention = momentary_bkpt_print_mention;
15518
15519   /* Probe breakpoints.  */
15520   ops = &bkpt_probe_breakpoint_ops;
15521   *ops = bkpt_breakpoint_ops;
15522   ops->insert_location = bkpt_probe_insert_location;
15523   ops->remove_location = bkpt_probe_remove_location;
15524   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15525   ops->decode_location = bkpt_probe_decode_location;
15526
15527   /* Watchpoints.  */
15528   ops = &watchpoint_breakpoint_ops;
15529   *ops = base_breakpoint_ops;
15530   ops->re_set = re_set_watchpoint;
15531   ops->insert_location = insert_watchpoint;
15532   ops->remove_location = remove_watchpoint;
15533   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15534   ops->check_status = check_status_watchpoint;
15535   ops->resources_needed = resources_needed_watchpoint;
15536   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15537   ops->print_it = print_it_watchpoint;
15538   ops->print_mention = print_mention_watchpoint;
15539   ops->print_recreate = print_recreate_watchpoint;
15540   ops->explains_signal = explains_signal_watchpoint;
15541
15542   /* Masked watchpoints.  */
15543   ops = &masked_watchpoint_breakpoint_ops;
15544   *ops = watchpoint_breakpoint_ops;
15545   ops->insert_location = insert_masked_watchpoint;
15546   ops->remove_location = remove_masked_watchpoint;
15547   ops->resources_needed = resources_needed_masked_watchpoint;
15548   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15549   ops->print_it = print_it_masked_watchpoint;
15550   ops->print_one_detail = print_one_detail_masked_watchpoint;
15551   ops->print_mention = print_mention_masked_watchpoint;
15552   ops->print_recreate = print_recreate_masked_watchpoint;
15553
15554   /* Tracepoints.  */
15555   ops = &tracepoint_breakpoint_ops;
15556   *ops = base_breakpoint_ops;
15557   ops->re_set = tracepoint_re_set;
15558   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15559   ops->print_one_detail = tracepoint_print_one_detail;
15560   ops->print_mention = tracepoint_print_mention;
15561   ops->print_recreate = tracepoint_print_recreate;
15562   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15563   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15564   ops->decode_location = tracepoint_decode_location;
15565
15566   /* Probe tracepoints.  */
15567   ops = &tracepoint_probe_breakpoint_ops;
15568   *ops = tracepoint_breakpoint_ops;
15569   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15570   ops->decode_location = tracepoint_probe_decode_location;
15571
15572   /* Static tracepoints with marker (`-m').  */
15573   ops = &strace_marker_breakpoint_ops;
15574   *ops = tracepoint_breakpoint_ops;
15575   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15576   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15577   ops->decode_location = strace_marker_decode_location;
15578
15579   /* Fork catchpoints.  */
15580   ops = &catch_fork_breakpoint_ops;
15581   *ops = base_breakpoint_ops;
15582   ops->insert_location = insert_catch_fork;
15583   ops->remove_location = remove_catch_fork;
15584   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15585   ops->print_it = print_it_catch_fork;
15586   ops->print_one = print_one_catch_fork;
15587   ops->print_mention = print_mention_catch_fork;
15588   ops->print_recreate = print_recreate_catch_fork;
15589
15590   /* Vfork catchpoints.  */
15591   ops = &catch_vfork_breakpoint_ops;
15592   *ops = base_breakpoint_ops;
15593   ops->insert_location = insert_catch_vfork;
15594   ops->remove_location = remove_catch_vfork;
15595   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15596   ops->print_it = print_it_catch_vfork;
15597   ops->print_one = print_one_catch_vfork;
15598   ops->print_mention = print_mention_catch_vfork;
15599   ops->print_recreate = print_recreate_catch_vfork;
15600
15601   /* Exec catchpoints.  */
15602   ops = &catch_exec_breakpoint_ops;
15603   *ops = base_breakpoint_ops;
15604   ops->insert_location = insert_catch_exec;
15605   ops->remove_location = remove_catch_exec;
15606   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15607   ops->print_it = print_it_catch_exec;
15608   ops->print_one = print_one_catch_exec;
15609   ops->print_mention = print_mention_catch_exec;
15610   ops->print_recreate = print_recreate_catch_exec;
15611
15612   /* Solib-related catchpoints.  */
15613   ops = &catch_solib_breakpoint_ops;
15614   *ops = base_breakpoint_ops;
15615   ops->insert_location = insert_catch_solib;
15616   ops->remove_location = remove_catch_solib;
15617   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15618   ops->check_status = check_status_catch_solib;
15619   ops->print_it = print_it_catch_solib;
15620   ops->print_one = print_one_catch_solib;
15621   ops->print_mention = print_mention_catch_solib;
15622   ops->print_recreate = print_recreate_catch_solib;
15623
15624   ops = &dprintf_breakpoint_ops;
15625   *ops = bkpt_base_breakpoint_ops;
15626   ops->re_set = dprintf_re_set;
15627   ops->resources_needed = bkpt_resources_needed;
15628   ops->print_it = bkpt_print_it;
15629   ops->print_mention = bkpt_print_mention;
15630   ops->print_recreate = dprintf_print_recreate;
15631   ops->after_condition_true = dprintf_after_condition_true;
15632   ops->breakpoint_hit = dprintf_breakpoint_hit;
15633 }
15634
15635 /* Chain containing all defined "enable breakpoint" subcommands.  */
15636
15637 static struct cmd_list_element *enablebreaklist = NULL;
15638
15639 void
15640 _initialize_breakpoint (void)
15641 {
15642   struct cmd_list_element *c;
15643
15644   initialize_breakpoint_ops ();
15645
15646   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15647   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
15648   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
15649
15650   breakpoint_objfile_key
15651     = register_objfile_data_with_cleanup (NULL, free_breakpoint_objfile_data);
15652
15653   breakpoint_chain = 0;
15654   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15655      before a breakpoint is set.  */
15656   breakpoint_count = 0;
15657
15658   tracepoint_count = 0;
15659
15660   add_com ("ignore", class_breakpoint, ignore_command, _("\
15661 Set ignore-count of breakpoint number N to COUNT.\n\
15662 Usage is `ignore N COUNT'."));
15663
15664   add_com ("commands", class_breakpoint, commands_command, _("\
15665 Set commands to be executed when the given breakpoints are hit.\n\
15666 Give a space-separated breakpoint list as argument after \"commands\".\n\
15667 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
15668 (e.g. `5-7').\n\
15669 With no argument, the targeted breakpoint is the last one set.\n\
15670 The commands themselves follow starting on the next line.\n\
15671 Type a line containing \"end\" to indicate the end of them.\n\
15672 Give \"silent\" as the first line to make the breakpoint silent;\n\
15673 then no output is printed when it is hit, except what the commands print."));
15674
15675   c = add_com ("condition", class_breakpoint, condition_command, _("\
15676 Specify breakpoint number N to break only if COND is true.\n\
15677 Usage is `condition N COND', where N is an integer and COND is an\n\
15678 expression to be evaluated whenever breakpoint N is reached."));
15679   set_cmd_completer (c, condition_completer);
15680
15681   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15682 Set a temporary breakpoint.\n\
15683 Like \"break\" except the breakpoint is only temporary,\n\
15684 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15685 by using \"enable delete\" on the breakpoint number.\n\
15686 \n"
15687 BREAK_ARGS_HELP ("tbreak")));
15688   set_cmd_completer (c, location_completer);
15689
15690   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15691 Set a hardware assisted breakpoint.\n\
15692 Like \"break\" except the breakpoint requires hardware support,\n\
15693 some target hardware may not have this support.\n\
15694 \n"
15695 BREAK_ARGS_HELP ("hbreak")));
15696   set_cmd_completer (c, location_completer);
15697
15698   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15699 Set a temporary hardware assisted breakpoint.\n\
15700 Like \"hbreak\" except the breakpoint is only temporary,\n\
15701 so it will be deleted when hit.\n\
15702 \n"
15703 BREAK_ARGS_HELP ("thbreak")));
15704   set_cmd_completer (c, location_completer);
15705
15706   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15707 Enable some breakpoints.\n\
15708 Give breakpoint numbers (separated by spaces) as arguments.\n\
15709 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15710 This is used to cancel the effect of the \"disable\" command.\n\
15711 With a subcommand you can enable temporarily."),
15712                   &enablelist, "enable ", 1, &cmdlist);
15713
15714   add_com_alias ("en", "enable", class_breakpoint, 1);
15715
15716   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15717 Enable some breakpoints.\n\
15718 Give breakpoint numbers (separated by spaces) as arguments.\n\
15719 This is used to cancel the effect of the \"disable\" command.\n\
15720 May be abbreviated to simply \"enable\".\n"),
15721                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15722
15723   add_cmd ("once", no_class, enable_once_command, _("\
15724 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15725 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15726            &enablebreaklist);
15727
15728   add_cmd ("delete", no_class, enable_delete_command, _("\
15729 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15730 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15731            &enablebreaklist);
15732
15733   add_cmd ("count", no_class, enable_count_command, _("\
15734 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15735 If a breakpoint is hit while enabled in this fashion,\n\
15736 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15737            &enablebreaklist);
15738
15739   add_cmd ("delete", no_class, enable_delete_command, _("\
15740 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15741 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15742            &enablelist);
15743
15744   add_cmd ("once", no_class, enable_once_command, _("\
15745 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15746 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15747            &enablelist);
15748
15749   add_cmd ("count", no_class, enable_count_command, _("\
15750 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15751 If a breakpoint is hit while enabled in this fashion,\n\
15752 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15753            &enablelist);
15754
15755   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15756 Disable some breakpoints.\n\
15757 Arguments are breakpoint numbers with spaces in between.\n\
15758 To disable all breakpoints, give no argument.\n\
15759 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15760                   &disablelist, "disable ", 1, &cmdlist);
15761   add_com_alias ("dis", "disable", class_breakpoint, 1);
15762   add_com_alias ("disa", "disable", class_breakpoint, 1);
15763
15764   add_cmd ("breakpoints", class_alias, disable_command, _("\
15765 Disable some breakpoints.\n\
15766 Arguments are breakpoint numbers with spaces in between.\n\
15767 To disable all breakpoints, give no argument.\n\
15768 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15769 This command may be abbreviated \"disable\"."),
15770            &disablelist);
15771
15772   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15773 Delete some breakpoints or auto-display expressions.\n\
15774 Arguments are breakpoint numbers with spaces in between.\n\
15775 To delete all breakpoints, give no argument.\n\
15776 \n\
15777 Also a prefix command for deletion of other GDB objects.\n\
15778 The \"unset\" command is also an alias for \"delete\"."),
15779                   &deletelist, "delete ", 1, &cmdlist);
15780   add_com_alias ("d", "delete", class_breakpoint, 1);
15781   add_com_alias ("del", "delete", class_breakpoint, 1);
15782
15783   add_cmd ("breakpoints", class_alias, delete_command, _("\
15784 Delete some breakpoints or auto-display expressions.\n\
15785 Arguments are breakpoint numbers with spaces in between.\n\
15786 To delete all breakpoints, give no argument.\n\
15787 This command may be abbreviated \"delete\"."),
15788            &deletelist);
15789
15790   add_com ("clear", class_breakpoint, clear_command, _("\
15791 Clear breakpoint at specified location.\n\
15792 Argument may be a linespec, explicit, or address location as described below.\n\
15793 \n\
15794 With no argument, clears all breakpoints in the line that the selected frame\n\
15795 is executing in.\n"
15796 "\n" LOCATION_HELP_STRING "\n\
15797 See also the \"delete\" command which clears breakpoints by number."));
15798   add_com_alias ("cl", "clear", class_breakpoint, 1);
15799
15800   c = add_com ("break", class_breakpoint, break_command, _("\
15801 Set breakpoint at specified location.\n"
15802 BREAK_ARGS_HELP ("break")));
15803   set_cmd_completer (c, location_completer);
15804
15805   add_com_alias ("b", "break", class_run, 1);
15806   add_com_alias ("br", "break", class_run, 1);
15807   add_com_alias ("bre", "break", class_run, 1);
15808   add_com_alias ("brea", "break", class_run, 1);
15809
15810   if (dbx_commands)
15811     {
15812       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15813 Break in function/address or break at a line in the current file."),
15814                              &stoplist, "stop ", 1, &cmdlist);
15815       add_cmd ("in", class_breakpoint, stopin_command,
15816                _("Break in function or address."), &stoplist);
15817       add_cmd ("at", class_breakpoint, stopat_command,
15818                _("Break at a line in the current file."), &stoplist);
15819       add_com ("status", class_info, info_breakpoints_command, _("\
15820 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15821 The \"Type\" column indicates one of:\n\
15822 \tbreakpoint     - normal breakpoint\n\
15823 \twatchpoint     - watchpoint\n\
15824 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15825 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15826 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15827 address and file/line number respectively.\n\
15828 \n\
15829 Convenience variable \"$_\" and default examine address for \"x\"\n\
15830 are set to the address of the last breakpoint listed unless the command\n\
15831 is prefixed with \"server \".\n\n\
15832 Convenience variable \"$bpnum\" contains the number of the last\n\
15833 breakpoint set."));
15834     }
15835
15836   add_info ("breakpoints", info_breakpoints_command, _("\
15837 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15838 The \"Type\" column indicates one of:\n\
15839 \tbreakpoint     - normal breakpoint\n\
15840 \twatchpoint     - watchpoint\n\
15841 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15842 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15843 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15844 address and file/line number respectively.\n\
15845 \n\
15846 Convenience variable \"$_\" and default examine address for \"x\"\n\
15847 are set to the address of the last breakpoint listed unless the command\n\
15848 is prefixed with \"server \".\n\n\
15849 Convenience variable \"$bpnum\" contains the number of the last\n\
15850 breakpoint set."));
15851
15852   add_info_alias ("b", "breakpoints", 1);
15853
15854   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15855 Status of all breakpoints, or breakpoint number NUMBER.\n\
15856 The \"Type\" column indicates one of:\n\
15857 \tbreakpoint     - normal breakpoint\n\
15858 \twatchpoint     - watchpoint\n\
15859 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15860 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15861 \tuntil          - internal breakpoint used by the \"until\" command\n\
15862 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15863 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15864 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15865 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15866 address and file/line number respectively.\n\
15867 \n\
15868 Convenience variable \"$_\" and default examine address for \"x\"\n\
15869 are set to the address of the last breakpoint listed unless the command\n\
15870 is prefixed with \"server \".\n\n\
15871 Convenience variable \"$bpnum\" contains the number of the last\n\
15872 breakpoint set."),
15873            &maintenanceinfolist);
15874
15875   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15876 Set catchpoints to catch events."),
15877                   &catch_cmdlist, "catch ",
15878                   0/*allow-unknown*/, &cmdlist);
15879
15880   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15881 Set temporary catchpoints to catch events."),
15882                   &tcatch_cmdlist, "tcatch ",
15883                   0/*allow-unknown*/, &cmdlist);
15884
15885   add_catch_command ("fork", _("Catch calls to fork."),
15886                      catch_fork_command_1,
15887                      NULL,
15888                      (void *) (uintptr_t) catch_fork_permanent,
15889                      (void *) (uintptr_t) catch_fork_temporary);
15890   add_catch_command ("vfork", _("Catch calls to vfork."),
15891                      catch_fork_command_1,
15892                      NULL,
15893                      (void *) (uintptr_t) catch_vfork_permanent,
15894                      (void *) (uintptr_t) catch_vfork_temporary);
15895   add_catch_command ("exec", _("Catch calls to exec."),
15896                      catch_exec_command_1,
15897                      NULL,
15898                      CATCH_PERMANENT,
15899                      CATCH_TEMPORARY);
15900   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15901 Usage: catch load [REGEX]\n\
15902 If REGEX is given, only stop for libraries matching the regular expression."),
15903                      catch_load_command_1,
15904                      NULL,
15905                      CATCH_PERMANENT,
15906                      CATCH_TEMPORARY);
15907   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15908 Usage: catch unload [REGEX]\n\
15909 If REGEX is given, only stop for libraries matching the regular expression."),
15910                      catch_unload_command_1,
15911                      NULL,
15912                      CATCH_PERMANENT,
15913                      CATCH_TEMPORARY);
15914
15915   c = add_com ("watch", class_breakpoint, watch_command, _("\
15916 Set a watchpoint for an expression.\n\
15917 Usage: watch [-l|-location] EXPRESSION\n\
15918 A watchpoint stops execution of your program whenever the value of\n\
15919 an expression changes.\n\
15920 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15921 the memory to which it refers."));
15922   set_cmd_completer (c, expression_completer);
15923
15924   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15925 Set a read watchpoint for an expression.\n\
15926 Usage: rwatch [-l|-location] EXPRESSION\n\
15927 A watchpoint stops execution of your program whenever the value of\n\
15928 an expression is read.\n\
15929 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15930 the memory to which it refers."));
15931   set_cmd_completer (c, expression_completer);
15932
15933   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15934 Set a watchpoint for an expression.\n\
15935 Usage: awatch [-l|-location] EXPRESSION\n\
15936 A watchpoint stops execution of your program whenever the value of\n\
15937 an expression is either read or written.\n\
15938 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15939 the memory to which it refers."));
15940   set_cmd_completer (c, expression_completer);
15941
15942   add_info ("watchpoints", info_watchpoints_command, _("\
15943 Status of specified watchpoints (all watchpoints if no argument)."));
15944
15945   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15946      respond to changes - contrary to the description.  */
15947   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15948                             &can_use_hw_watchpoints, _("\
15949 Set debugger's willingness to use watchpoint hardware."), _("\
15950 Show debugger's willingness to use watchpoint hardware."), _("\
15951 If zero, gdb will not use hardware for new watchpoints, even if\n\
15952 such is available.  (However, any hardware watchpoints that were\n\
15953 created before setting this to nonzero, will continue to use watchpoint\n\
15954 hardware.)"),
15955                             NULL,
15956                             show_can_use_hw_watchpoints,
15957                             &setlist, &showlist);
15958
15959   can_use_hw_watchpoints = 1;
15960
15961   /* Tracepoint manipulation commands.  */
15962
15963   c = add_com ("trace", class_breakpoint, trace_command, _("\
15964 Set a tracepoint at specified location.\n\
15965 \n"
15966 BREAK_ARGS_HELP ("trace") "\n\
15967 Do \"help tracepoints\" for info on other tracepoint commands."));
15968   set_cmd_completer (c, location_completer);
15969
15970   add_com_alias ("tp", "trace", class_alias, 0);
15971   add_com_alias ("tr", "trace", class_alias, 1);
15972   add_com_alias ("tra", "trace", class_alias, 1);
15973   add_com_alias ("trac", "trace", class_alias, 1);
15974
15975   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15976 Set a fast tracepoint at specified location.\n\
15977 \n"
15978 BREAK_ARGS_HELP ("ftrace") "\n\
15979 Do \"help tracepoints\" for info on other tracepoint commands."));
15980   set_cmd_completer (c, location_completer);
15981
15982   c = add_com ("strace", class_breakpoint, strace_command, _("\
15983 Set a static tracepoint at location or marker.\n\
15984 \n\
15985 strace [LOCATION] [if CONDITION]\n\
15986 LOCATION may be a linespec, explicit, or address location (described below) \n\
15987 or -m MARKER_ID.\n\n\
15988 If a marker id is specified, probe the marker with that name.  With\n\
15989 no LOCATION, uses current execution address of the selected stack frame.\n\
15990 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15991 This collects arbitrary user data passed in the probe point call to the\n\
15992 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15993 by printing the $_sdata variable like any other convenience variable.\n\
15994 \n\
15995 CONDITION is a boolean expression.\n\
15996 \n" LOCATION_HELP_STRING "\n\
15997 Multiple tracepoints at one place are permitted, and useful if their\n\
15998 conditions are different.\n\
15999 \n\
16000 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16001 Do \"help tracepoints\" for info on other tracepoint commands."));
16002   set_cmd_completer (c, location_completer);
16003
16004   add_info ("tracepoints", info_tracepoints_command, _("\
16005 Status of specified tracepoints (all tracepoints if no argument).\n\
16006 Convenience variable \"$tpnum\" contains the number of the\n\
16007 last tracepoint set."));
16008
16009   add_info_alias ("tp", "tracepoints", 1);
16010
16011   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16012 Delete specified tracepoints.\n\
16013 Arguments are tracepoint numbers, separated by spaces.\n\
16014 No argument means delete all tracepoints."),
16015            &deletelist);
16016   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16017
16018   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16019 Disable specified tracepoints.\n\
16020 Arguments are tracepoint numbers, separated by spaces.\n\
16021 No argument means disable all tracepoints."),
16022            &disablelist);
16023   deprecate_cmd (c, "disable");
16024
16025   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16026 Enable specified tracepoints.\n\
16027 Arguments are tracepoint numbers, separated by spaces.\n\
16028 No argument means enable all tracepoints."),
16029            &enablelist);
16030   deprecate_cmd (c, "enable");
16031
16032   add_com ("passcount", class_trace, trace_pass_command, _("\
16033 Set the passcount for a tracepoint.\n\
16034 The trace will end when the tracepoint has been passed 'count' times.\n\
16035 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16036 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16037
16038   add_prefix_cmd ("save", class_breakpoint, save_command,
16039                   _("Save breakpoint definitions as a script."),
16040                   &save_cmdlist, "save ",
16041                   0/*allow-unknown*/, &cmdlist);
16042
16043   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16044 Save current breakpoint definitions as a script.\n\
16045 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16046 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16047 session to restore them."),
16048                &save_cmdlist);
16049   set_cmd_completer (c, filename_completer);
16050
16051   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16052 Save current tracepoint definitions as a script.\n\
16053 Use the 'source' command in another debug session to restore them."),
16054                &save_cmdlist);
16055   set_cmd_completer (c, filename_completer);
16056
16057   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16058   deprecate_cmd (c, "save tracepoints");
16059
16060   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16061 Breakpoint specific settings\n\
16062 Configure various breakpoint-specific variables such as\n\
16063 pending breakpoint behavior"),
16064                   &breakpoint_set_cmdlist, "set breakpoint ",
16065                   0/*allow-unknown*/, &setlist);
16066   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16067 Breakpoint specific settings\n\
16068 Configure various breakpoint-specific variables such as\n\
16069 pending breakpoint behavior"),
16070                   &breakpoint_show_cmdlist, "show breakpoint ",
16071                   0/*allow-unknown*/, &showlist);
16072
16073   add_setshow_auto_boolean_cmd ("pending", no_class,
16074                                 &pending_break_support, _("\
16075 Set debugger's behavior regarding pending breakpoints."), _("\
16076 Show debugger's behavior regarding pending breakpoints."), _("\
16077 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16078 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16079 an error.  If auto, an unrecognized breakpoint location results in a\n\
16080 user-query to see if a pending breakpoint should be created."),
16081                                 NULL,
16082                                 show_pending_break_support,
16083                                 &breakpoint_set_cmdlist,
16084                                 &breakpoint_show_cmdlist);
16085
16086   pending_break_support = AUTO_BOOLEAN_AUTO;
16087
16088   add_setshow_boolean_cmd ("auto-hw", no_class,
16089                            &automatic_hardware_breakpoints, _("\
16090 Set automatic usage of hardware breakpoints."), _("\
16091 Show automatic usage of hardware breakpoints."), _("\
16092 If set, the debugger will automatically use hardware breakpoints for\n\
16093 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16094 a warning will be emitted for such breakpoints."),
16095                            NULL,
16096                            show_automatic_hardware_breakpoints,
16097                            &breakpoint_set_cmdlist,
16098                            &breakpoint_show_cmdlist);
16099
16100   add_setshow_boolean_cmd ("always-inserted", class_support,
16101                            &always_inserted_mode, _("\
16102 Set mode for inserting breakpoints."), _("\
16103 Show mode for inserting breakpoints."), _("\
16104 When this mode is on, breakpoints are inserted immediately as soon as\n\
16105 they're created, kept inserted even when execution stops, and removed\n\
16106 only when the user deletes them.  When this mode is off (the default),\n\
16107 breakpoints are inserted only when execution continues, and removed\n\
16108 when execution stops."),
16109                                 NULL,
16110                                 &show_always_inserted_mode,
16111                                 &breakpoint_set_cmdlist,
16112                                 &breakpoint_show_cmdlist);
16113
16114   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16115                         condition_evaluation_enums,
16116                         &condition_evaluation_mode_1, _("\
16117 Set mode of breakpoint condition evaluation."), _("\
16118 Show mode of breakpoint condition evaluation."), _("\
16119 When this is set to \"host\", breakpoint conditions will be\n\
16120 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16121 breakpoint conditions will be downloaded to the target (if the target\n\
16122 supports such feature) and conditions will be evaluated on the target's side.\n\
16123 If this is set to \"auto\" (default), this will be automatically set to\n\
16124 \"target\" if it supports condition evaluation, otherwise it will\n\
16125 be set to \"gdb\""),
16126                            &set_condition_evaluation_mode,
16127                            &show_condition_evaluation_mode,
16128                            &breakpoint_set_cmdlist,
16129                            &breakpoint_show_cmdlist);
16130
16131   add_com ("break-range", class_breakpoint, break_range_command, _("\
16132 Set a breakpoint for an address range.\n\
16133 break-range START-LOCATION, END-LOCATION\n\
16134 where START-LOCATION and END-LOCATION can be one of the following:\n\
16135   LINENUM, for that line in the current file,\n\
16136   FILE:LINENUM, for that line in that file,\n\
16137   +OFFSET, for that number of lines after the current line\n\
16138            or the start of the range\n\
16139   FUNCTION, for the first line in that function,\n\
16140   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16141   *ADDRESS, for the instruction at that address.\n\
16142 \n\
16143 The breakpoint will stop execution of the inferior whenever it executes\n\
16144 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16145 range (including START-LOCATION and END-LOCATION)."));
16146
16147   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16148 Set a dynamic printf at specified location.\n\
16149 dprintf location,format string,arg1,arg2,...\n\
16150 location may be a linespec, explicit, or address location.\n"
16151 "\n" LOCATION_HELP_STRING));
16152   set_cmd_completer (c, location_completer);
16153
16154   add_setshow_enum_cmd ("dprintf-style", class_support,
16155                         dprintf_style_enums, &dprintf_style, _("\
16156 Set the style of usage for dynamic printf."), _("\
16157 Show the style of usage for dynamic printf."), _("\
16158 This setting chooses how GDB will do a dynamic printf.\n\
16159 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16160 console, as with the \"printf\" command.\n\
16161 If the value is \"call\", the print is done by calling a function in your\n\
16162 program; by default printf(), but you can choose a different function or\n\
16163 output stream by setting dprintf-function and dprintf-channel."),
16164                         update_dprintf_commands, NULL,
16165                         &setlist, &showlist);
16166
16167   dprintf_function = xstrdup ("printf");
16168   add_setshow_string_cmd ("dprintf-function", class_support,
16169                           &dprintf_function, _("\
16170 Set the function to use for dynamic printf"), _("\
16171 Show the function to use for dynamic printf"), NULL,
16172                           update_dprintf_commands, NULL,
16173                           &setlist, &showlist);
16174
16175   dprintf_channel = xstrdup ("");
16176   add_setshow_string_cmd ("dprintf-channel", class_support,
16177                           &dprintf_channel, _("\
16178 Set the channel to use for dynamic printf"), _("\
16179 Show the channel to use for dynamic printf"), NULL,
16180                           update_dprintf_commands, NULL,
16181                           &setlist, &showlist);
16182
16183   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16184                            &disconnected_dprintf, _("\
16185 Set whether dprintf continues after GDB disconnects."), _("\
16186 Show whether dprintf continues after GDB disconnects."), _("\
16187 Use this to let dprintf commands continue to hit and produce output\n\
16188 even if GDB disconnects or detaches from the target."),
16189                            NULL,
16190                            NULL,
16191                            &setlist, &showlist);
16192
16193   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16194 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16195 (target agent only) This is useful for formatted output in user-defined commands."));
16196
16197   automatic_hardware_breakpoints = 1;
16198
16199   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16200   observer_attach_thread_exit (remove_threaded_breakpoints);
16201 }