Fix regression in "commands"
[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 breakpoint_re_set_default (struct breakpoint *);
100
101 static void
102   create_sals_from_location_default (const struct event_location *location,
103                                      struct linespec_result *canonical,
104                                      enum bptype type_wanted);
105
106 static void create_breakpoints_sal_default (struct gdbarch *,
107                                             struct linespec_result *,
108                                             gdb::unique_xmalloc_ptr<char>,
109                                             gdb::unique_xmalloc_ptr<char>,
110                                             enum bptype,
111                                             enum bpdisp, int, int,
112                                             int,
113                                             const struct breakpoint_ops *,
114                                             int, int, int, unsigned);
115
116 static std::vector<symtab_and_line> decode_location_default
117   (struct breakpoint *b, const struct event_location *location,
118    struct program_space *search_pspace);
119
120 static int can_use_hardware_watchpoint (struct value *);
121
122 static void mention (struct breakpoint *);
123
124 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
125                                                                enum bptype,
126                                                                const struct breakpoint_ops *);
127 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
128                                                        const struct symtab_and_line *);
129
130 /* This function is used in gdbtk sources and thus can not be made
131    static.  */
132 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
133                                        struct symtab_and_line,
134                                        enum bptype,
135                                        const struct breakpoint_ops *);
136
137 static struct breakpoint *
138   momentary_breakpoint_from_master (struct breakpoint *orig,
139                                     enum bptype type,
140                                     const struct breakpoint_ops *ops,
141                                     int loc_enabled);
142
143 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
144
145 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
146                                             CORE_ADDR bpaddr,
147                                             enum bptype bptype);
148
149 static void describe_other_breakpoints (struct gdbarch *,
150                                         struct program_space *, CORE_ADDR,
151                                         struct obj_section *, int);
152
153 static int watchpoint_locations_match (struct bp_location *loc1,
154                                        struct bp_location *loc2);
155
156 static int breakpoint_location_address_match (struct bp_location *bl,
157                                               const struct address_space *aspace,
158                                               CORE_ADDR addr);
159
160 static int breakpoint_location_address_range_overlap (struct bp_location *,
161                                                       const address_space *,
162                                                       CORE_ADDR, int);
163
164 static int remove_breakpoint (struct bp_location *);
165 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
166
167 static enum print_stop_action print_bp_stop_message (bpstat bs);
168
169 static int hw_breakpoint_used_count (void);
170
171 static int hw_watchpoint_use_count (struct breakpoint *);
172
173 static int hw_watchpoint_used_count_others (struct breakpoint *except,
174                                             enum bptype type,
175                                             int *other_type_used);
176
177 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
178                                     int count);
179
180 static void free_bp_location (struct bp_location *loc);
181 static void incref_bp_location (struct bp_location *loc);
182 static void decref_bp_location (struct bp_location **loc);
183
184 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
185
186 /* update_global_location_list's modes of operation wrt to whether to
187    insert locations now.  */
188 enum ugll_insert_mode
189 {
190   /* Don't insert any breakpoint locations into the inferior, only
191      remove already-inserted locations that no longer should be
192      inserted.  Functions that delete a breakpoint or breakpoints
193      should specify this mode, so that deleting a breakpoint doesn't
194      have the side effect of inserting the locations of other
195      breakpoints that are marked not-inserted, but should_be_inserted
196      returns true on them.
197
198      This behavior is useful is situations close to tear-down -- e.g.,
199      after an exec, while the target still has execution, but
200      breakpoint shadows of the previous executable image should *NOT*
201      be restored to the new image; or before detaching, where the
202      target still has execution and wants to delete breakpoints from
203      GDB's lists, and all breakpoints had already been removed from
204      the inferior.  */
205   UGLL_DONT_INSERT,
206
207   /* May insert breakpoints iff breakpoints_should_be_inserted_now
208      claims breakpoints should be inserted now.  */
209   UGLL_MAY_INSERT,
210
211   /* Insert locations now, irrespective of
212      breakpoints_should_be_inserted_now.  E.g., say all threads are
213      stopped right now, and the user did "continue".  We need to
214      insert breakpoints _before_ resuming the target, but
215      UGLL_MAY_INSERT wouldn't insert them, because
216      breakpoints_should_be_inserted_now returns false at that point,
217      as no thread is running yet.  */
218   UGLL_INSERT
219 };
220
221 static void update_global_location_list (enum ugll_insert_mode);
222
223 static void update_global_location_list_nothrow (enum ugll_insert_mode);
224
225 static int is_hardware_watchpoint (const struct breakpoint *bpt);
226
227 static void insert_breakpoint_locations (void);
228
229 static void trace_pass_command (const char *, int);
230
231 static void set_tracepoint_count (int num);
232
233 static int is_masked_watchpoint (const struct breakpoint *b);
234
235 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
236
237 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
238    otherwise.  */
239
240 static int strace_marker_p (struct breakpoint *b);
241
242 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
243    that are implemented on top of software or hardware breakpoints
244    (user breakpoints, internal and momentary breakpoints, etc.).  */
245 static struct breakpoint_ops bkpt_base_breakpoint_ops;
246
247 /* Internal breakpoints class type.  */
248 static struct breakpoint_ops internal_breakpoint_ops;
249
250 /* Momentary breakpoints class type.  */
251 static struct breakpoint_ops momentary_breakpoint_ops;
252
253 /* The breakpoint_ops structure to be used in regular user created
254    breakpoints.  */
255 struct breakpoint_ops bkpt_breakpoint_ops;
256
257 /* Breakpoints set on probes.  */
258 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
259
260 /* Dynamic printf class type.  */
261 struct breakpoint_ops dprintf_breakpoint_ops;
262
263 /* The style in which to perform a dynamic printf.  This is a user
264    option because different output options have different tradeoffs;
265    if GDB does the printing, there is better error handling if there
266    is a problem with any of the arguments, but using an inferior
267    function lets you have special-purpose printers and sending of
268    output to the same place as compiled-in print functions.  */
269
270 static const char dprintf_style_gdb[] = "gdb";
271 static const char dprintf_style_call[] = "call";
272 static const char dprintf_style_agent[] = "agent";
273 static const char *const dprintf_style_enums[] = {
274   dprintf_style_gdb,
275   dprintf_style_call,
276   dprintf_style_agent,
277   NULL
278 };
279 static const char *dprintf_style = dprintf_style_gdb;
280
281 /* The function to use for dynamic printf if the preferred style is to
282    call into the inferior.  The value is simply a string that is
283    copied into the command, so it can be anything that GDB can
284    evaluate to a callable address, not necessarily a function name.  */
285
286 static char *dprintf_function;
287
288 /* The channel to use for dynamic printf if the preferred style is to
289    call into the inferior; if a nonempty string, it will be passed to
290    the call as the first argument, with the format string as the
291    second.  As with the dprintf function, this can be anything that
292    GDB knows how to evaluate, so in addition to common choices like
293    "stderr", this could be an app-specific expression like
294    "mystreams[curlogger]".  */
295
296 static char *dprintf_channel;
297
298 /* True if dprintf commands should continue to operate even if GDB
299    has disconnected.  */
300 static int disconnected_dprintf = 1;
301
302 struct command_line *
303 breakpoint_commands (struct breakpoint *b)
304 {
305   return b->commands ? b->commands.get () : NULL;
306 }
307
308 /* Flag indicating that a command has proceeded the inferior past the
309    current breakpoint.  */
310
311 static int breakpoint_proceeded;
312
313 const char *
314 bpdisp_text (enum bpdisp disp)
315 {
316   /* NOTE: the following values are a part of MI protocol and
317      represent values of 'disp' field returned when inferior stops at
318      a breakpoint.  */
319   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
320
321   return bpdisps[(int) disp];
322 }
323
324 /* Prototypes for exported functions.  */
325 /* If FALSE, gdb will not use hardware support for watchpoints, even
326    if such is available.  */
327 static int can_use_hw_watchpoints;
328
329 static void
330 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
331                              struct cmd_list_element *c,
332                              const char *value)
333 {
334   fprintf_filtered (file,
335                     _("Debugger's willingness to use "
336                       "watchpoint hardware is %s.\n"),
337                     value);
338 }
339
340 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
341    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
342    for unrecognized breakpoint locations.
343    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
344 static enum auto_boolean pending_break_support;
345 static void
346 show_pending_break_support (struct ui_file *file, int from_tty,
347                             struct cmd_list_element *c,
348                             const char *value)
349 {
350   fprintf_filtered (file,
351                     _("Debugger's behavior regarding "
352                       "pending breakpoints is %s.\n"),
353                     value);
354 }
355
356 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
357    set with "break" but falling in read-only memory.
358    If 0, gdb will warn about such breakpoints, but won't automatically
359    use hardware breakpoints.  */
360 static int automatic_hardware_breakpoints;
361 static void
362 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
363                                      struct cmd_list_element *c,
364                                      const char *value)
365 {
366   fprintf_filtered (file,
367                     _("Automatic usage of hardware breakpoints is %s.\n"),
368                     value);
369 }
370
371 /* If on, GDB keeps breakpoints inserted even if the inferior is
372    stopped, and immediately inserts any new breakpoints as soon as
373    they're created.  If off (default), GDB keeps breakpoints off of
374    the target as long as possible.  That is, it delays inserting
375    breakpoints until the next resume, and removes them again when the
376    target fully stops.  This is a bit safer in case GDB crashes while
377    processing user input.  */
378 static int always_inserted_mode = 0;
379
380 static void
381 show_always_inserted_mode (struct ui_file *file, int from_tty,
382                      struct cmd_list_element *c, const char *value)
383 {
384   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
385                     value);
386 }
387
388 /* See breakpoint.h.  */
389
390 int
391 breakpoints_should_be_inserted_now (void)
392 {
393   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
394     {
395       /* If breakpoints are global, they should be inserted even if no
396          thread under gdb's control is running, or even if there are
397          no threads under GDB's control yet.  */
398       return 1;
399     }
400   else if (target_has_execution)
401     {
402       struct thread_info *tp;
403
404       if (always_inserted_mode)
405         {
406           /* The user wants breakpoints inserted even if all threads
407              are stopped.  */
408           return 1;
409         }
410
411       if (threads_are_executing ())
412         return 1;
413
414       /* Don't remove breakpoints yet if, even though all threads are
415          stopped, we still have events to process.  */
416       ALL_NON_EXITED_THREADS (tp)
417         if (tp->resumed
418             && tp->suspend.waitstatus_pending_p)
419           return 1;
420     }
421   return 0;
422 }
423
424 static const char condition_evaluation_both[] = "host or target";
425
426 /* Modes for breakpoint condition evaluation.  */
427 static const char condition_evaluation_auto[] = "auto";
428 static const char condition_evaluation_host[] = "host";
429 static const char condition_evaluation_target[] = "target";
430 static const char *const condition_evaluation_enums[] = {
431   condition_evaluation_auto,
432   condition_evaluation_host,
433   condition_evaluation_target,
434   NULL
435 };
436
437 /* Global that holds the current mode for breakpoint condition evaluation.  */
438 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
439
440 /* Global that we use to display information to the user (gets its value from
441    condition_evaluation_mode_1.  */
442 static const char *condition_evaluation_mode = condition_evaluation_auto;
443
444 /* Translate a condition evaluation mode MODE into either "host"
445    or "target".  This is used mostly to translate from "auto" to the
446    real setting that is being used.  It returns the translated
447    evaluation mode.  */
448
449 static const char *
450 translate_condition_evaluation_mode (const char *mode)
451 {
452   if (mode == condition_evaluation_auto)
453     {
454       if (target_supports_evaluation_of_breakpoint_conditions ())
455         return condition_evaluation_target;
456       else
457         return condition_evaluation_host;
458     }
459   else
460     return mode;
461 }
462
463 /* Discovers what condition_evaluation_auto translates to.  */
464
465 static const char *
466 breakpoint_condition_evaluation_mode (void)
467 {
468   return translate_condition_evaluation_mode (condition_evaluation_mode);
469 }
470
471 /* Return true if GDB should evaluate breakpoint conditions or false
472    otherwise.  */
473
474 static int
475 gdb_evaluates_breakpoint_condition_p (void)
476 {
477   const char *mode = breakpoint_condition_evaluation_mode ();
478
479   return (mode == condition_evaluation_host);
480 }
481
482 /* Are we executing breakpoint commands?  */
483 static int executing_breakpoint_commands;
484
485 /* Are overlay event breakpoints enabled? */
486 static int overlay_events_enabled;
487
488 /* See description in breakpoint.h. */
489 int target_exact_watchpoints = 0;
490
491 /* Walk the following statement or block through all breakpoints.
492    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
493    current breakpoint.  */
494
495 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
496
497 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
498         for (B = breakpoint_chain;      \
499              B ? (TMP=B->next, 1): 0;   \
500              B = TMP)
501
502 /* Similar iterator for the low-level breakpoints.  SAFE variant is
503    not provided so update_global_location_list must not be called
504    while executing the block of ALL_BP_LOCATIONS.  */
505
506 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
507         for (BP_TMP = bp_locations;                                     \
508              BP_TMP < bp_locations + bp_locations_count && (B = *BP_TMP);\
509              BP_TMP++)
510
511 /* Iterates through locations with address ADDRESS for the currently selected
512    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
513    to where the loop should start from.
514    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
515    appropriate location to start with.  */
516
517 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
518         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
519              BP_LOCP_TMP = BP_LOCP_START;                               \
520              BP_LOCP_START                                              \
521              && (BP_LOCP_TMP < bp_locations + bp_locations_count        \
522              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
523              BP_LOCP_TMP++)
524
525 /* Iterator for tracepoints only.  */
526
527 #define ALL_TRACEPOINTS(B)  \
528   for (B = breakpoint_chain; B; B = B->next)  \
529     if (is_tracepoint (B))
530
531 /* Chains of all breakpoints defined.  */
532
533 struct breakpoint *breakpoint_chain;
534
535 /* Array is sorted by bp_locations_compare - primarily by the ADDRESS.  */
536
537 static struct bp_location **bp_locations;
538
539 /* Number of elements of BP_LOCATIONS.  */
540
541 static unsigned bp_locations_count;
542
543 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
544    ADDRESS for the current elements of BP_LOCATIONS which get a valid
545    result from bp_location_has_shadow.  You can use it for roughly
546    limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
547    an address you need to read.  */
548
549 static CORE_ADDR bp_locations_placed_address_before_address_max;
550
551 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
552    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
553    BP_LOCATIONS which get a valid result from bp_location_has_shadow.
554    You can use it for roughly limiting the subrange of BP_LOCATIONS to
555    scan for shadow bytes for an address you need to read.  */
556
557 static CORE_ADDR bp_locations_shadow_len_after_address_max;
558
559 /* The locations that no longer correspond to any breakpoint, unlinked
560    from the bp_locations array, but for which a hit may still be
561    reported by a target.  */
562 VEC(bp_location_p) *moribund_locations = NULL;
563
564 /* Number of last breakpoint made.  */
565
566 static int breakpoint_count;
567
568 /* The value of `breakpoint_count' before the last command that
569    created breakpoints.  If the last (break-like) command created more
570    than one breakpoint, then the difference between BREAKPOINT_COUNT
571    and PREV_BREAKPOINT_COUNT is more than one.  */
572 static int prev_breakpoint_count;
573
574 /* Number of last tracepoint made.  */
575
576 static int tracepoint_count;
577
578 static struct cmd_list_element *breakpoint_set_cmdlist;
579 static struct cmd_list_element *breakpoint_show_cmdlist;
580 struct cmd_list_element *save_cmdlist;
581
582 /* See declaration at breakpoint.h.  */
583
584 struct breakpoint *
585 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
586                     void *user_data)
587 {
588   struct breakpoint *b = NULL;
589
590   ALL_BREAKPOINTS (b)
591     {
592       if (func (b, user_data) != 0)
593         break;
594     }
595
596   return b;
597 }
598
599 /* Return whether a breakpoint is an active enabled breakpoint.  */
600 static int
601 breakpoint_enabled (struct breakpoint *b)
602 {
603   return (b->enable_state == bp_enabled);
604 }
605
606 /* Set breakpoint count to NUM.  */
607
608 static void
609 set_breakpoint_count (int num)
610 {
611   prev_breakpoint_count = breakpoint_count;
612   breakpoint_count = num;
613   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
614 }
615
616 /* Used by `start_rbreak_breakpoints' below, to record the current
617    breakpoint count before "rbreak" creates any breakpoint.  */
618 static int rbreak_start_breakpoint_count;
619
620 /* Called at the start an "rbreak" command to record the first
621    breakpoint made.  */
622
623 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
624 {
625   rbreak_start_breakpoint_count = breakpoint_count;
626 }
627
628 /* Called at the end of an "rbreak" command to record the last
629    breakpoint made.  */
630
631 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
632 {
633   prev_breakpoint_count = rbreak_start_breakpoint_count;
634 }
635
636 /* Used in run_command to zero the hit count when a new run starts.  */
637
638 void
639 clear_breakpoint_hit_counts (void)
640 {
641   struct breakpoint *b;
642
643   ALL_BREAKPOINTS (b)
644     b->hit_count = 0;
645 }
646
647 \f
648 /* Return the breakpoint with the specified number, or NULL
649    if the number does not refer to an existing breakpoint.  */
650
651 struct breakpoint *
652 get_breakpoint (int num)
653 {
654   struct breakpoint *b;
655
656   ALL_BREAKPOINTS (b)
657     if (b->number == num)
658       return b;
659   
660   return NULL;
661 }
662
663 \f
664
665 /* Mark locations as "conditions have changed" in case the target supports
666    evaluating conditions on its side.  */
667
668 static void
669 mark_breakpoint_modified (struct breakpoint *b)
670 {
671   struct bp_location *loc;
672
673   /* This is only meaningful if the target is
674      evaluating conditions and if the user has
675      opted for condition evaluation on the target's
676      side.  */
677   if (gdb_evaluates_breakpoint_condition_p ()
678       || !target_supports_evaluation_of_breakpoint_conditions ())
679     return;
680
681   if (!is_breakpoint (b))
682     return;
683
684   for (loc = b->loc; loc; loc = loc->next)
685     loc->condition_changed = condition_modified;
686 }
687
688 /* Mark location as "conditions have changed" in case the target supports
689    evaluating conditions on its side.  */
690
691 static void
692 mark_breakpoint_location_modified (struct bp_location *loc)
693 {
694   /* This is only meaningful if the target is
695      evaluating conditions and if the user has
696      opted for condition evaluation on the target's
697      side.  */
698   if (gdb_evaluates_breakpoint_condition_p ()
699       || !target_supports_evaluation_of_breakpoint_conditions ())
700
701     return;
702
703   if (!is_breakpoint (loc->owner))
704     return;
705
706   loc->condition_changed = condition_modified;
707 }
708
709 /* Sets the condition-evaluation mode using the static global
710    condition_evaluation_mode.  */
711
712 static void
713 set_condition_evaluation_mode (const char *args, int from_tty,
714                                struct cmd_list_element *c)
715 {
716   const char *old_mode, *new_mode;
717
718   if ((condition_evaluation_mode_1 == condition_evaluation_target)
719       && !target_supports_evaluation_of_breakpoint_conditions ())
720     {
721       condition_evaluation_mode_1 = condition_evaluation_mode;
722       warning (_("Target does not support breakpoint condition evaluation.\n"
723                  "Using host evaluation mode instead."));
724       return;
725     }
726
727   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
728   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
729
730   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
731      settings was "auto".  */
732   condition_evaluation_mode = condition_evaluation_mode_1;
733
734   /* Only update the mode if the user picked a different one.  */
735   if (new_mode != old_mode)
736     {
737       struct bp_location *loc, **loc_tmp;
738       /* If the user switched to a different evaluation mode, we
739          need to synch the changes with the target as follows:
740
741          "host" -> "target": Send all (valid) conditions to the target.
742          "target" -> "host": Remove all the conditions from the target.
743       */
744
745       if (new_mode == condition_evaluation_target)
746         {
747           /* Mark everything modified and synch conditions with the
748              target.  */
749           ALL_BP_LOCATIONS (loc, loc_tmp)
750             mark_breakpoint_location_modified (loc);
751         }
752       else
753         {
754           /* Manually mark non-duplicate locations to synch conditions
755              with the target.  We do this to remove all the conditions the
756              target knows about.  */
757           ALL_BP_LOCATIONS (loc, loc_tmp)
758             if (is_breakpoint (loc->owner) && loc->inserted)
759               loc->needs_update = 1;
760         }
761
762       /* Do the update.  */
763       update_global_location_list (UGLL_MAY_INSERT);
764     }
765
766   return;
767 }
768
769 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
770    what "auto" is translating to.  */
771
772 static void
773 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
774                                 struct cmd_list_element *c, const char *value)
775 {
776   if (condition_evaluation_mode == condition_evaluation_auto)
777     fprintf_filtered (file,
778                       _("Breakpoint condition evaluation "
779                         "mode is %s (currently %s).\n"),
780                       value,
781                       breakpoint_condition_evaluation_mode ());
782   else
783     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
784                       value);
785 }
786
787 /* A comparison function for bp_location AP and BP that is used by
788    bsearch.  This comparison function only cares about addresses, unlike
789    the more general bp_locations_compare function.  */
790
791 static int
792 bp_locations_compare_addrs (const void *ap, const void *bp)
793 {
794   const struct bp_location *a = *(const struct bp_location **) ap;
795   const struct bp_location *b = *(const struct bp_location **) bp;
796
797   if (a->address == b->address)
798     return 0;
799   else
800     return ((a->address > b->address) - (a->address < b->address));
801 }
802
803 /* Helper function to skip all bp_locations with addresses
804    less than ADDRESS.  It returns the first bp_location that
805    is greater than or equal to ADDRESS.  If none is found, just
806    return NULL.  */
807
808 static struct bp_location **
809 get_first_locp_gte_addr (CORE_ADDR address)
810 {
811   struct bp_location dummy_loc;
812   struct bp_location *dummy_locp = &dummy_loc;
813   struct bp_location **locp_found = NULL;
814
815   /* Initialize the dummy location's address field.  */
816   dummy_loc.address = address;
817
818   /* Find a close match to the first location at ADDRESS.  */
819   locp_found = ((struct bp_location **)
820                 bsearch (&dummy_locp, bp_locations, bp_locations_count,
821                          sizeof (struct bp_location **),
822                          bp_locations_compare_addrs));
823
824   /* Nothing was found, nothing left to do.  */
825   if (locp_found == NULL)
826     return NULL;
827
828   /* We may have found a location that is at ADDRESS but is not the first in the
829      location's list.  Go backwards (if possible) and locate the first one.  */
830   while ((locp_found - 1) >= bp_locations
831          && (*(locp_found - 1))->address == address)
832     locp_found--;
833
834   return locp_found;
835 }
836
837 void
838 set_breakpoint_condition (struct breakpoint *b, const char *exp,
839                           int from_tty)
840 {
841   xfree (b->cond_string);
842   b->cond_string = NULL;
843
844   if (is_watchpoint (b))
845     {
846       struct watchpoint *w = (struct watchpoint *) b;
847
848       w->cond_exp.reset ();
849     }
850   else
851     {
852       struct bp_location *loc;
853
854       for (loc = b->loc; loc; loc = loc->next)
855         {
856           loc->cond.reset ();
857
858           /* No need to free the condition agent expression
859              bytecode (if we have one).  We will handle this
860              when we go through update_global_location_list.  */
861         }
862     }
863
864   if (*exp == 0)
865     {
866       if (from_tty)
867         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
868     }
869   else
870     {
871       const char *arg = exp;
872
873       /* I don't know if it matters whether this is the string the user
874          typed in or the decompiled expression.  */
875       b->cond_string = xstrdup (arg);
876       b->condition_not_parsed = 0;
877
878       if (is_watchpoint (b))
879         {
880           struct watchpoint *w = (struct watchpoint *) b;
881
882           innermost_block = NULL;
883           arg = exp;
884           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
885           if (*arg)
886             error (_("Junk at end of expression"));
887           w->cond_exp_valid_block = innermost_block;
888         }
889       else
890         {
891           struct bp_location *loc;
892
893           for (loc = b->loc; loc; loc = loc->next)
894             {
895               arg = exp;
896               loc->cond =
897                 parse_exp_1 (&arg, loc->address,
898                              block_for_pc (loc->address), 0);
899               if (*arg)
900                 error (_("Junk at end of expression"));
901             }
902         }
903     }
904   mark_breakpoint_modified (b);
905
906   observer_notify_breakpoint_modified (b);
907 }
908
909 /* Completion for the "condition" command.  */
910
911 static void
912 condition_completer (struct cmd_list_element *cmd,
913                      completion_tracker &tracker,
914                      const char *text, const char *word)
915 {
916   const char *space;
917
918   text = skip_spaces (text);
919   space = skip_to_space (text);
920   if (*space == '\0')
921     {
922       int len;
923       struct breakpoint *b;
924
925       if (text[0] == '$')
926         {
927           /* We don't support completion of history indices.  */
928           if (!isdigit (text[1]))
929             complete_internalvar (tracker, &text[1]);
930           return;
931         }
932
933       /* We're completing the breakpoint number.  */
934       len = strlen (text);
935
936       ALL_BREAKPOINTS (b)
937         {
938           char number[50];
939
940           xsnprintf (number, sizeof (number), "%d", b->number);
941
942           if (strncmp (number, text, len) == 0)
943             {
944               gdb::unique_xmalloc_ptr<char> copy (xstrdup (number));
945               tracker.add_completion (std::move (copy));
946             }
947         }
948
949       return;
950     }
951
952   /* We're completing the expression part.  */
953   text = skip_spaces (space);
954   expression_completer (cmd, tracker, text, word);
955 }
956
957 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
958
959 static void
960 condition_command (const char *arg, int from_tty)
961 {
962   struct breakpoint *b;
963   const char *p;
964   int bnum;
965
966   if (arg == 0)
967     error_no_arg (_("breakpoint number"));
968
969   p = arg;
970   bnum = get_number (&p);
971   if (bnum == 0)
972     error (_("Bad breakpoint argument: '%s'"), arg);
973
974   ALL_BREAKPOINTS (b)
975     if (b->number == bnum)
976       {
977         /* Check if this breakpoint has a "stop" method implemented in an
978            extension language.  This method and conditions entered into GDB
979            from the CLI are mutually exclusive.  */
980         const struct extension_language_defn *extlang
981           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
982
983         if (extlang != NULL)
984           {
985             error (_("Only one stop condition allowed.  There is currently"
986                      " a %s stop condition defined for this breakpoint."),
987                    ext_lang_capitalized_name (extlang));
988           }
989         set_breakpoint_condition (b, p, from_tty);
990
991         if (is_breakpoint (b))
992           update_global_location_list (UGLL_MAY_INSERT);
993
994         return;
995       }
996
997   error (_("No breakpoint number %d."), bnum);
998 }
999
1000 /* Check that COMMAND do not contain commands that are suitable
1001    only for tracepoints and not suitable for ordinary breakpoints.
1002    Throw if any such commands is found.  */
1003
1004 static void
1005 check_no_tracepoint_commands (struct command_line *commands)
1006 {
1007   struct command_line *c;
1008
1009   for (c = commands; c; c = c->next)
1010     {
1011       int i;
1012
1013       if (c->control_type == while_stepping_control)
1014         error (_("The 'while-stepping' command can "
1015                  "only be used for tracepoints"));
1016
1017       for (i = 0; i < c->body_count; ++i)
1018         check_no_tracepoint_commands ((c->body_list)[i]);
1019
1020       /* Not that command parsing removes leading whitespace and comment
1021          lines and also empty lines.  So, we only need to check for
1022          command directly.  */
1023       if (strstr (c->line, "collect ") == c->line)
1024         error (_("The 'collect' command can only be used for tracepoints"));
1025
1026       if (strstr (c->line, "teval ") == c->line)
1027         error (_("The 'teval' command can only be used for tracepoints"));
1028     }
1029 }
1030
1031 struct longjmp_breakpoint : public breakpoint
1032 {
1033   ~longjmp_breakpoint () override;
1034 };
1035
1036 /* Encapsulate tests for different types of tracepoints.  */
1037
1038 static bool
1039 is_tracepoint_type (bptype type)
1040 {
1041   return (type == bp_tracepoint
1042           || type == bp_fast_tracepoint
1043           || type == bp_static_tracepoint);
1044 }
1045
1046 static bool
1047 is_longjmp_type (bptype type)
1048 {
1049   return type == bp_longjmp || type == bp_exception;
1050 }
1051
1052 int
1053 is_tracepoint (const struct breakpoint *b)
1054 {
1055   return is_tracepoint_type (b->type);
1056 }
1057
1058 /* Factory function to create an appropriate instance of breakpoint given
1059    TYPE.  */
1060
1061 static std::unique_ptr<breakpoint>
1062 new_breakpoint_from_type (bptype type)
1063 {
1064   breakpoint *b;
1065
1066   if (is_tracepoint_type (type))
1067     b = new tracepoint ();
1068   else if (is_longjmp_type (type))
1069     b = new longjmp_breakpoint ();
1070   else
1071     b = new breakpoint ();
1072
1073   return std::unique_ptr<breakpoint> (b);
1074 }
1075
1076 /* A helper function that validates that COMMANDS are valid for a
1077    breakpoint.  This function will throw an exception if a problem is
1078    found.  */
1079
1080 static void
1081 validate_commands_for_breakpoint (struct breakpoint *b,
1082                                   struct command_line *commands)
1083 {
1084   if (is_tracepoint (b))
1085     {
1086       struct tracepoint *t = (struct tracepoint *) b;
1087       struct command_line *c;
1088       struct command_line *while_stepping = 0;
1089
1090       /* Reset the while-stepping step count.  The previous commands
1091          might have included a while-stepping action, while the new
1092          ones might not.  */
1093       t->step_count = 0;
1094
1095       /* We need to verify that each top-level element of commands is
1096          valid for tracepoints, that there's at most one
1097          while-stepping element, and that the while-stepping's body
1098          has valid tracing commands excluding nested while-stepping.
1099          We also need to validate the tracepoint action line in the
1100          context of the tracepoint --- validate_actionline actually
1101          has side effects, like setting the tracepoint's
1102          while-stepping STEP_COUNT, in addition to checking if the
1103          collect/teval actions parse and make sense in the
1104          tracepoint's context.  */
1105       for (c = commands; c; c = c->next)
1106         {
1107           if (c->control_type == while_stepping_control)
1108             {
1109               if (b->type == bp_fast_tracepoint)
1110                 error (_("The 'while-stepping' command "
1111                          "cannot be used for fast tracepoint"));
1112               else if (b->type == bp_static_tracepoint)
1113                 error (_("The 'while-stepping' command "
1114                          "cannot be used for static tracepoint"));
1115
1116               if (while_stepping)
1117                 error (_("The 'while-stepping' command "
1118                          "can be used only once"));
1119               else
1120                 while_stepping = c;
1121             }
1122
1123           validate_actionline (c->line, b);
1124         }
1125       if (while_stepping)
1126         {
1127           struct command_line *c2;
1128
1129           gdb_assert (while_stepping->body_count == 1);
1130           c2 = while_stepping->body_list[0];
1131           for (; c2; c2 = c2->next)
1132             {
1133               if (c2->control_type == while_stepping_control)
1134                 error (_("The 'while-stepping' command cannot be nested"));
1135             }
1136         }
1137     }
1138   else
1139     {
1140       check_no_tracepoint_commands (commands);
1141     }
1142 }
1143
1144 /* Return a vector of all the static tracepoints set at ADDR.  The
1145    caller is responsible for releasing the vector.  */
1146
1147 VEC(breakpoint_p) *
1148 static_tracepoints_here (CORE_ADDR addr)
1149 {
1150   struct breakpoint *b;
1151   VEC(breakpoint_p) *found = 0;
1152   struct bp_location *loc;
1153
1154   ALL_BREAKPOINTS (b)
1155     if (b->type == bp_static_tracepoint)
1156       {
1157         for (loc = b->loc; loc; loc = loc->next)
1158           if (loc->address == addr)
1159             VEC_safe_push(breakpoint_p, found, b);
1160       }
1161
1162   return found;
1163 }
1164
1165 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1166    validate that only allowed commands are included.  */
1167
1168 void
1169 breakpoint_set_commands (struct breakpoint *b, 
1170                          command_line_up &&commands)
1171 {
1172   validate_commands_for_breakpoint (b, commands.get ());
1173
1174   b->commands = std::move (commands);
1175   observer_notify_breakpoint_modified (b);
1176 }
1177
1178 /* Set the internal `silent' flag on the breakpoint.  Note that this
1179    is not the same as the "silent" that may appear in the breakpoint's
1180    commands.  */
1181
1182 void
1183 breakpoint_set_silent (struct breakpoint *b, int silent)
1184 {
1185   int old_silent = b->silent;
1186
1187   b->silent = silent;
1188   if (old_silent != silent)
1189     observer_notify_breakpoint_modified (b);
1190 }
1191
1192 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1193    breakpoint work for any thread.  */
1194
1195 void
1196 breakpoint_set_thread (struct breakpoint *b, int thread)
1197 {
1198   int old_thread = b->thread;
1199
1200   b->thread = thread;
1201   if (old_thread != thread)
1202     observer_notify_breakpoint_modified (b);
1203 }
1204
1205 /* Set the task for this breakpoint.  If TASK is 0, make the
1206    breakpoint work for any task.  */
1207
1208 void
1209 breakpoint_set_task (struct breakpoint *b, int task)
1210 {
1211   int old_task = b->task;
1212
1213   b->task = task;
1214   if (old_task != task)
1215     observer_notify_breakpoint_modified (b);
1216 }
1217
1218 void
1219 check_tracepoint_command (char *line, void *closure)
1220 {
1221   struct breakpoint *b = (struct breakpoint *) closure;
1222
1223   validate_actionline (line, b);
1224 }
1225
1226 static void
1227 commands_command_1 (const char *arg, int from_tty,
1228                     struct command_line *control)
1229 {
1230   counted_command_line cmd;
1231
1232   std::string new_arg;
1233
1234   if (arg == NULL || !*arg)
1235     {
1236       if (breakpoint_count - prev_breakpoint_count > 1)
1237         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1238                                  breakpoint_count);
1239       else if (breakpoint_count > 0)
1240         new_arg = string_printf ("%d", breakpoint_count);
1241       arg = new_arg.c_str ();
1242     }
1243
1244   map_breakpoint_numbers
1245     (arg, [&] (breakpoint *b)
1246      {
1247        if (cmd == NULL)
1248          {
1249            if (control != NULL)
1250              cmd = copy_command_lines (control->body_list[0]);
1251            else
1252              {
1253                std::string str
1254                  = string_printf (_("Type commands for breakpoint(s) "
1255                                     "%s, one per line."),
1256                                   arg);
1257
1258                cmd = read_command_lines (&str[0],
1259                                          from_tty, 1,
1260                                          (is_tracepoint (b)
1261                                           ? check_tracepoint_command : 0),
1262                                          b);
1263              }
1264          }
1265
1266        /* If a breakpoint was on the list more than once, we don't need to
1267           do anything.  */
1268        if (b->commands != cmd)
1269          {
1270            validate_commands_for_breakpoint (b, cmd.get ());
1271            b->commands = cmd;
1272            observer_notify_breakpoint_modified (b);
1273          }
1274      });
1275 }
1276
1277 static void
1278 commands_command (const char *arg, int from_tty)
1279 {
1280   commands_command_1 (arg, from_tty, NULL);
1281 }
1282
1283 /* Like commands_command, but instead of reading the commands from
1284    input stream, takes them from an already parsed command structure.
1285
1286    This is used by cli-script.c to DTRT with breakpoint commands
1287    that are part of if and while bodies.  */
1288 enum command_control_type
1289 commands_from_control_command (const char *arg, struct command_line *cmd)
1290 {
1291   commands_command_1 (arg, 0, cmd);
1292   return simple_control;
1293 }
1294
1295 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1296
1297 static int
1298 bp_location_has_shadow (struct bp_location *bl)
1299 {
1300   if (bl->loc_type != bp_loc_software_breakpoint)
1301     return 0;
1302   if (!bl->inserted)
1303     return 0;
1304   if (bl->target_info.shadow_len == 0)
1305     /* BL isn't valid, or doesn't shadow memory.  */
1306     return 0;
1307   return 1;
1308 }
1309
1310 /* Update BUF, which is LEN bytes read from the target address
1311    MEMADDR, by replacing a memory breakpoint with its shadowed
1312    contents.
1313
1314    If READBUF is not NULL, this buffer must not overlap with the of
1315    the breakpoint location's shadow_contents buffer.  Otherwise, a
1316    failed assertion internal error will be raised.  */
1317
1318 static void
1319 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1320                             const gdb_byte *writebuf_org,
1321                             ULONGEST memaddr, LONGEST len,
1322                             struct bp_target_info *target_info,
1323                             struct gdbarch *gdbarch)
1324 {
1325   /* Now do full processing of the found relevant range of elements.  */
1326   CORE_ADDR bp_addr = 0;
1327   int bp_size = 0;
1328   int bptoffset = 0;
1329
1330   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1331                                  current_program_space->aspace, 0))
1332     {
1333       /* The breakpoint is inserted in a different address space.  */
1334       return;
1335     }
1336
1337   /* Addresses and length of the part of the breakpoint that
1338      we need to copy.  */
1339   bp_addr = target_info->placed_address;
1340   bp_size = target_info->shadow_len;
1341
1342   if (bp_addr + bp_size <= memaddr)
1343     {
1344       /* The breakpoint is entirely before the chunk of memory we are
1345          reading.  */
1346       return;
1347     }
1348
1349   if (bp_addr >= memaddr + len)
1350     {
1351       /* The breakpoint is entirely after the chunk of memory we are
1352          reading.  */
1353       return;
1354     }
1355
1356   /* Offset within shadow_contents.  */
1357   if (bp_addr < memaddr)
1358     {
1359       /* Only copy the second part of the breakpoint.  */
1360       bp_size -= memaddr - bp_addr;
1361       bptoffset = memaddr - bp_addr;
1362       bp_addr = memaddr;
1363     }
1364
1365   if (bp_addr + bp_size > memaddr + len)
1366     {
1367       /* Only copy the first part of the breakpoint.  */
1368       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1369     }
1370
1371   if (readbuf != NULL)
1372     {
1373       /* Verify that the readbuf buffer does not overlap with the
1374          shadow_contents buffer.  */
1375       gdb_assert (target_info->shadow_contents >= readbuf + len
1376                   || readbuf >= (target_info->shadow_contents
1377                                  + target_info->shadow_len));
1378
1379       /* Update the read buffer with this inserted breakpoint's
1380          shadow.  */
1381       memcpy (readbuf + bp_addr - memaddr,
1382               target_info->shadow_contents + bptoffset, bp_size);
1383     }
1384   else
1385     {
1386       const unsigned char *bp;
1387       CORE_ADDR addr = target_info->reqstd_address;
1388       int placed_size;
1389
1390       /* Update the shadow with what we want to write to memory.  */
1391       memcpy (target_info->shadow_contents + bptoffset,
1392               writebuf_org + bp_addr - memaddr, bp_size);
1393
1394       /* Determine appropriate breakpoint contents and size for this
1395          address.  */
1396       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1397
1398       /* Update the final write buffer with this inserted
1399          breakpoint's INSN.  */
1400       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1401     }
1402 }
1403
1404 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1405    by replacing any memory breakpoints with their shadowed contents.
1406
1407    If READBUF is not NULL, this buffer must not overlap with any of
1408    the breakpoint location's shadow_contents buffers.  Otherwise,
1409    a failed assertion internal error will be raised.
1410
1411    The range of shadowed area by each bp_location is:
1412      bl->address - bp_locations_placed_address_before_address_max
1413      up to bl->address + bp_locations_shadow_len_after_address_max
1414    The range we were requested to resolve shadows for is:
1415      memaddr ... memaddr + len
1416    Thus the safe cutoff boundaries for performance optimization are
1417      memaddr + len <= (bl->address
1418                        - bp_locations_placed_address_before_address_max)
1419    and:
1420      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1421
1422 void
1423 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1424                         const gdb_byte *writebuf_org,
1425                         ULONGEST memaddr, LONGEST len)
1426 {
1427   /* Left boundary, right boundary and median element of our binary
1428      search.  */
1429   unsigned bc_l, bc_r, bc;
1430
1431   /* Find BC_L which is a leftmost element which may affect BUF
1432      content.  It is safe to report lower value but a failure to
1433      report higher one.  */
1434
1435   bc_l = 0;
1436   bc_r = bp_locations_count;
1437   while (bc_l + 1 < bc_r)
1438     {
1439       struct bp_location *bl;
1440
1441       bc = (bc_l + bc_r) / 2;
1442       bl = bp_locations[bc];
1443
1444       /* Check first BL->ADDRESS will not overflow due to the added
1445          constant.  Then advance the left boundary only if we are sure
1446          the BC element can in no way affect the BUF content (MEMADDR
1447          to MEMADDR + LEN range).
1448
1449          Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1450          offset so that we cannot miss a breakpoint with its shadow
1451          range tail still reaching MEMADDR.  */
1452
1453       if ((bl->address + bp_locations_shadow_len_after_address_max
1454            >= bl->address)
1455           && (bl->address + bp_locations_shadow_len_after_address_max
1456               <= memaddr))
1457         bc_l = bc;
1458       else
1459         bc_r = bc;
1460     }
1461
1462   /* Due to the binary search above, we need to make sure we pick the
1463      first location that's at BC_L's address.  E.g., if there are
1464      multiple locations at the same address, BC_L may end up pointing
1465      at a duplicate location, and miss the "master"/"inserted"
1466      location.  Say, given locations L1, L2 and L3 at addresses A and
1467      B:
1468
1469       L1@A, L2@A, L3@B, ...
1470
1471      BC_L could end up pointing at location L2, while the "master"
1472      location could be L1.  Since the `loc->inserted' flag is only set
1473      on "master" locations, we'd forget to restore the shadow of L1
1474      and L2.  */
1475   while (bc_l > 0
1476          && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1477     bc_l--;
1478
1479   /* Now do full processing of the found relevant range of elements.  */
1480
1481   for (bc = bc_l; bc < bp_locations_count; bc++)
1482   {
1483     struct bp_location *bl = bp_locations[bc];
1484
1485     /* bp_location array has BL->OWNER always non-NULL.  */
1486     if (bl->owner->type == bp_none)
1487       warning (_("reading through apparently deleted breakpoint #%d?"),
1488                bl->owner->number);
1489
1490     /* Performance optimization: any further element can no longer affect BUF
1491        content.  */
1492
1493     if (bl->address >= bp_locations_placed_address_before_address_max
1494         && memaddr + len <= (bl->address
1495                              - bp_locations_placed_address_before_address_max))
1496       break;
1497
1498     if (!bp_location_has_shadow (bl))
1499       continue;
1500
1501     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1502                                 memaddr, len, &bl->target_info, bl->gdbarch);
1503   }
1504 }
1505
1506 \f
1507
1508 /* Return true if BPT is either a software breakpoint or a hardware
1509    breakpoint.  */
1510
1511 int
1512 is_breakpoint (const struct breakpoint *bpt)
1513 {
1514   return (bpt->type == bp_breakpoint
1515           || bpt->type == bp_hardware_breakpoint
1516           || bpt->type == bp_dprintf);
1517 }
1518
1519 /* Return true if BPT is of any hardware watchpoint kind.  */
1520
1521 static int
1522 is_hardware_watchpoint (const struct breakpoint *bpt)
1523 {
1524   return (bpt->type == bp_hardware_watchpoint
1525           || bpt->type == bp_read_watchpoint
1526           || bpt->type == bp_access_watchpoint);
1527 }
1528
1529 /* Return true if BPT is of any watchpoint kind, hardware or
1530    software.  */
1531
1532 int
1533 is_watchpoint (const struct breakpoint *bpt)
1534 {
1535   return (is_hardware_watchpoint (bpt)
1536           || bpt->type == bp_watchpoint);
1537 }
1538
1539 /* Returns true if the current thread and its running state are safe
1540    to evaluate or update watchpoint B.  Watchpoints on local
1541    expressions need to be evaluated in the context of the thread that
1542    was current when the watchpoint was created, and, that thread needs
1543    to be stopped to be able to select the correct frame context.
1544    Watchpoints on global expressions can be evaluated on any thread,
1545    and in any state.  It is presently left to the target allowing
1546    memory accesses when threads are running.  */
1547
1548 static int
1549 watchpoint_in_thread_scope (struct watchpoint *b)
1550 {
1551   return (b->pspace == current_program_space
1552           && (ptid_equal (b->watchpoint_thread, null_ptid)
1553               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1554                   && !is_executing (inferior_ptid))));
1555 }
1556
1557 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1558    associated bp_watchpoint_scope breakpoint.  */
1559
1560 static void
1561 watchpoint_del_at_next_stop (struct watchpoint *w)
1562 {
1563   if (w->related_breakpoint != w)
1564     {
1565       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1566       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1567       w->related_breakpoint->disposition = disp_del_at_next_stop;
1568       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1569       w->related_breakpoint = w;
1570     }
1571   w->disposition = disp_del_at_next_stop;
1572 }
1573
1574 /* Extract a bitfield value from value VAL using the bit parameters contained in
1575    watchpoint W.  */
1576
1577 static struct value *
1578 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1579 {
1580   struct value *bit_val;
1581
1582   if (val == NULL)
1583     return NULL;
1584
1585   bit_val = allocate_value (value_type (val));
1586
1587   unpack_value_bitfield (bit_val,
1588                          w->val_bitpos,
1589                          w->val_bitsize,
1590                          value_contents_for_printing (val),
1591                          value_offset (val),
1592                          val);
1593
1594   return bit_val;
1595 }
1596
1597 /* Allocate a dummy location and add it to B, which must be a software
1598    watchpoint.  This is required because even if a software watchpoint
1599    is not watching any memory, bpstat_stop_status requires a location
1600    to be able to report stops.  */
1601
1602 static void
1603 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1604                                             struct program_space *pspace)
1605 {
1606   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1607
1608   b->loc = allocate_bp_location (b);
1609   b->loc->pspace = pspace;
1610   b->loc->address = -1;
1611   b->loc->length = -1;
1612 }
1613
1614 /* Returns true if B is a software watchpoint that is not watching any
1615    memory (e.g., "watch $pc").  */
1616
1617 static int
1618 is_no_memory_software_watchpoint (struct breakpoint *b)
1619 {
1620   return (b->type == bp_watchpoint
1621           && b->loc != NULL
1622           && b->loc->next == NULL
1623           && b->loc->address == -1
1624           && b->loc->length == -1);
1625 }
1626
1627 /* Assuming that B is a watchpoint:
1628    - Reparse watchpoint expression, if REPARSE is non-zero
1629    - Evaluate expression and store the result in B->val
1630    - Evaluate the condition if there is one, and store the result
1631      in b->loc->cond.
1632    - Update the list of values that must be watched in B->loc.
1633
1634    If the watchpoint disposition is disp_del_at_next_stop, then do
1635    nothing.  If this is local watchpoint that is out of scope, delete
1636    it.
1637
1638    Even with `set breakpoint always-inserted on' the watchpoints are
1639    removed + inserted on each stop here.  Normal breakpoints must
1640    never be removed because they might be missed by a running thread
1641    when debugging in non-stop mode.  On the other hand, hardware
1642    watchpoints (is_hardware_watchpoint; processed here) are specific
1643    to each LWP since they are stored in each LWP's hardware debug
1644    registers.  Therefore, such LWP must be stopped first in order to
1645    be able to modify its hardware watchpoints.
1646
1647    Hardware watchpoints must be reset exactly once after being
1648    presented to the user.  It cannot be done sooner, because it would
1649    reset the data used to present the watchpoint hit to the user.  And
1650    it must not be done later because it could display the same single
1651    watchpoint hit during multiple GDB stops.  Note that the latter is
1652    relevant only to the hardware watchpoint types bp_read_watchpoint
1653    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1654    not user-visible - its hit is suppressed if the memory content has
1655    not changed.
1656
1657    The following constraints influence the location where we can reset
1658    hardware watchpoints:
1659
1660    * target_stopped_by_watchpoint and target_stopped_data_address are
1661      called several times when GDB stops.
1662
1663    [linux] 
1664    * Multiple hardware watchpoints can be hit at the same time,
1665      causing GDB to stop.  GDB only presents one hardware watchpoint
1666      hit at a time as the reason for stopping, and all the other hits
1667      are presented later, one after the other, each time the user
1668      requests the execution to be resumed.  Execution is not resumed
1669      for the threads still having pending hit event stored in
1670      LWP_INFO->STATUS.  While the watchpoint is already removed from
1671      the inferior on the first stop the thread hit event is kept being
1672      reported from its cached value by linux_nat_stopped_data_address
1673      until the real thread resume happens after the watchpoint gets
1674      presented and thus its LWP_INFO->STATUS gets reset.
1675
1676    Therefore the hardware watchpoint hit can get safely reset on the
1677    watchpoint removal from inferior.  */
1678
1679 static void
1680 update_watchpoint (struct watchpoint *b, int reparse)
1681 {
1682   int within_current_scope;
1683   struct frame_id saved_frame_id;
1684   int frame_saved;
1685
1686   /* If this is a local watchpoint, we only want to check if the
1687      watchpoint frame is in scope if the current thread is the thread
1688      that was used to create the watchpoint.  */
1689   if (!watchpoint_in_thread_scope (b))
1690     return;
1691
1692   if (b->disposition == disp_del_at_next_stop)
1693     return;
1694  
1695   frame_saved = 0;
1696
1697   /* Determine if the watchpoint is within scope.  */
1698   if (b->exp_valid_block == NULL)
1699     within_current_scope = 1;
1700   else
1701     {
1702       struct frame_info *fi = get_current_frame ();
1703       struct gdbarch *frame_arch = get_frame_arch (fi);
1704       CORE_ADDR frame_pc = get_frame_pc (fi);
1705
1706       /* If we're at a point where the stack has been destroyed
1707          (e.g. in a function epilogue), unwinding may not work
1708          properly. Do not attempt to recreate locations at this
1709          point.  See similar comments in watchpoint_check.  */
1710       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1711         return;
1712
1713       /* Save the current frame's ID so we can restore it after
1714          evaluating the watchpoint expression on its own frame.  */
1715       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1716          took a frame parameter, so that we didn't have to change the
1717          selected frame.  */
1718       frame_saved = 1;
1719       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1720
1721       fi = frame_find_by_id (b->watchpoint_frame);
1722       within_current_scope = (fi != NULL);
1723       if (within_current_scope)
1724         select_frame (fi);
1725     }
1726
1727   /* We don't free locations.  They are stored in the bp_location array
1728      and update_global_location_list will eventually delete them and
1729      remove breakpoints if needed.  */
1730   b->loc = NULL;
1731
1732   if (within_current_scope && reparse)
1733     {
1734       const char *s;
1735
1736       b->exp.reset ();
1737       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1738       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1739       /* If the meaning of expression itself changed, the old value is
1740          no longer relevant.  We don't want to report a watchpoint hit
1741          to the user when the old value and the new value may actually
1742          be completely different objects.  */
1743       value_free (b->val);
1744       b->val = NULL;
1745       b->val_valid = 0;
1746
1747       /* Note that unlike with breakpoints, the watchpoint's condition
1748          expression is stored in the breakpoint object, not in the
1749          locations (re)created below.  */
1750       if (b->cond_string != NULL)
1751         {
1752           b->cond_exp.reset ();
1753
1754           s = b->cond_string;
1755           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1756         }
1757     }
1758
1759   /* If we failed to parse the expression, for example because
1760      it refers to a global variable in a not-yet-loaded shared library,
1761      don't try to insert watchpoint.  We don't automatically delete
1762      such watchpoint, though, since failure to parse expression
1763      is different from out-of-scope watchpoint.  */
1764   if (!target_has_execution)
1765     {
1766       /* Without execution, memory can't change.  No use to try and
1767          set watchpoint locations.  The watchpoint will be reset when
1768          the target gains execution, through breakpoint_re_set.  */
1769       if (!can_use_hw_watchpoints)
1770         {
1771           if (b->ops->works_in_software_mode (b))
1772             b->type = bp_watchpoint;
1773           else
1774             error (_("Can't set read/access watchpoint when "
1775                      "hardware watchpoints are disabled."));
1776         }
1777     }
1778   else if (within_current_scope && b->exp)
1779     {
1780       int pc = 0;
1781       struct value *val_chain, *v, *result, *next;
1782       struct program_space *frame_pspace;
1783
1784       fetch_subexp_value (b->exp.get (), &pc, &v, &result, &val_chain, 0);
1785
1786       /* Avoid setting b->val if it's already set.  The meaning of
1787          b->val is 'the last value' user saw, and we should update
1788          it only if we reported that last value to user.  As it
1789          happens, the code that reports it updates b->val directly.
1790          We don't keep track of the memory value for masked
1791          watchpoints.  */
1792       if (!b->val_valid && !is_masked_watchpoint (b))
1793         {
1794           if (b->val_bitsize != 0)
1795             {
1796               v = extract_bitfield_from_watchpoint_value (b, v);
1797               if (v != NULL)
1798                 release_value (v);
1799             }
1800           b->val = v;
1801           b->val_valid = 1;
1802         }
1803
1804       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1805
1806       /* Look at each value on the value chain.  */
1807       for (v = val_chain; v; v = value_next (v))
1808         {
1809           /* If it's a memory location, and GDB actually needed
1810              its contents to evaluate the expression, then we
1811              must watch it.  If the first value returned is
1812              still lazy, that means an error occurred reading it;
1813              watch it anyway in case it becomes readable.  */
1814           if (VALUE_LVAL (v) == lval_memory
1815               && (v == val_chain || ! value_lazy (v)))
1816             {
1817               struct type *vtype = check_typedef (value_type (v));
1818
1819               /* We only watch structs and arrays if user asked
1820                  for it explicitly, never if they just happen to
1821                  appear in the middle of some value chain.  */
1822               if (v == result
1823                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1824                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1825                 {
1826                   CORE_ADDR addr;
1827                   enum target_hw_bp_type type;
1828                   struct bp_location *loc, **tmp;
1829                   int bitpos = 0, bitsize = 0;
1830
1831                   if (value_bitsize (v) != 0)
1832                     {
1833                       /* Extract the bit parameters out from the bitfield
1834                          sub-expression.  */
1835                       bitpos = value_bitpos (v);
1836                       bitsize = value_bitsize (v);
1837                     }
1838                   else if (v == result && b->val_bitsize != 0)
1839                     {
1840                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1841                         lvalue whose bit parameters are saved in the fields
1842                         VAL_BITPOS and VAL_BITSIZE.  */
1843                       bitpos = b->val_bitpos;
1844                       bitsize = b->val_bitsize;
1845                     }
1846
1847                   addr = value_address (v);
1848                   if (bitsize != 0)
1849                     {
1850                       /* Skip the bytes that don't contain the bitfield.  */
1851                       addr += bitpos / 8;
1852                     }
1853
1854                   type = hw_write;
1855                   if (b->type == bp_read_watchpoint)
1856                     type = hw_read;
1857                   else if (b->type == bp_access_watchpoint)
1858                     type = hw_access;
1859
1860                   loc = allocate_bp_location (b);
1861                   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
1862                     ;
1863                   *tmp = loc;
1864                   loc->gdbarch = get_type_arch (value_type (v));
1865
1866                   loc->pspace = frame_pspace;
1867                   loc->address = addr;
1868
1869                   if (bitsize != 0)
1870                     {
1871                       /* Just cover the bytes that make up the bitfield.  */
1872                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
1873                     }
1874                   else
1875                     loc->length = TYPE_LENGTH (value_type (v));
1876
1877                   loc->watchpoint_type = type;
1878                 }
1879             }
1880         }
1881
1882       /* Change the type of breakpoint between hardware assisted or
1883          an ordinary watchpoint depending on the hardware support
1884          and free hardware slots.  REPARSE is set when the inferior
1885          is started.  */
1886       if (reparse)
1887         {
1888           int reg_cnt;
1889           enum bp_loc_type loc_type;
1890           struct bp_location *bl;
1891
1892           reg_cnt = can_use_hardware_watchpoint (val_chain);
1893
1894           if (reg_cnt)
1895             {
1896               int i, target_resources_ok, other_type_used;
1897               enum bptype type;
1898
1899               /* Use an exact watchpoint when there's only one memory region to be
1900                  watched, and only one debug register is needed to watch it.  */
1901               b->exact = target_exact_watchpoints && reg_cnt == 1;
1902
1903               /* We need to determine how many resources are already
1904                  used for all other hardware watchpoints plus this one
1905                  to see if we still have enough resources to also fit
1906                  this watchpoint in as well.  */
1907
1908               /* If this is a software watchpoint, we try to turn it
1909                  to a hardware one -- count resources as if B was of
1910                  hardware watchpoint type.  */
1911               type = b->type;
1912               if (type == bp_watchpoint)
1913                 type = bp_hardware_watchpoint;
1914
1915               /* This watchpoint may or may not have been placed on
1916                  the list yet at this point (it won't be in the list
1917                  if we're trying to create it for the first time,
1918                  through watch_command), so always account for it
1919                  manually.  */
1920
1921               /* Count resources used by all watchpoints except B.  */
1922               i = hw_watchpoint_used_count_others (b, type, &other_type_used);
1923
1924               /* Add in the resources needed for B.  */
1925               i += hw_watchpoint_use_count (b);
1926
1927               target_resources_ok
1928                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1929               if (target_resources_ok <= 0)
1930                 {
1931                   int sw_mode = b->ops->works_in_software_mode (b);
1932
1933                   if (target_resources_ok == 0 && !sw_mode)
1934                     error (_("Target does not support this type of "
1935                              "hardware watchpoint."));
1936                   else if (target_resources_ok < 0 && !sw_mode)
1937                     error (_("There are not enough available hardware "
1938                              "resources for this watchpoint."));
1939
1940                   /* Downgrade to software watchpoint.  */
1941                   b->type = bp_watchpoint;
1942                 }
1943               else
1944                 {
1945                   /* If this was a software watchpoint, we've just
1946                      found we have enough resources to turn it to a
1947                      hardware watchpoint.  Otherwise, this is a
1948                      nop.  */
1949                   b->type = type;
1950                 }
1951             }
1952           else if (!b->ops->works_in_software_mode (b))
1953             {
1954               if (!can_use_hw_watchpoints)
1955                 error (_("Can't set read/access watchpoint when "
1956                          "hardware watchpoints are disabled."));
1957               else
1958                 error (_("Expression cannot be implemented with "
1959                          "read/access watchpoint."));
1960             }
1961           else
1962             b->type = bp_watchpoint;
1963
1964           loc_type = (b->type == bp_watchpoint? bp_loc_other
1965                       : bp_loc_hardware_watchpoint);
1966           for (bl = b->loc; bl; bl = bl->next)
1967             bl->loc_type = loc_type;
1968         }
1969
1970       for (v = val_chain; v; v = next)
1971         {
1972           next = value_next (v);
1973           if (v != b->val)
1974             value_free (v);
1975         }
1976
1977       /* If a software watchpoint is not watching any memory, then the
1978          above left it without any location set up.  But,
1979          bpstat_stop_status requires a location to be able to report
1980          stops, so make sure there's at least a dummy one.  */
1981       if (b->type == bp_watchpoint && b->loc == NULL)
1982         software_watchpoint_add_no_memory_location (b, frame_pspace);
1983     }
1984   else if (!within_current_scope)
1985     {
1986       printf_filtered (_("\
1987 Watchpoint %d deleted because the program has left the block\n\
1988 in which its expression is valid.\n"),
1989                        b->number);
1990       watchpoint_del_at_next_stop (b);
1991     }
1992
1993   /* Restore the selected frame.  */
1994   if (frame_saved)
1995     select_frame (frame_find_by_id (saved_frame_id));
1996 }
1997
1998
1999 /* Returns 1 iff breakpoint location should be
2000    inserted in the inferior.  We don't differentiate the type of BL's owner
2001    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2002    breakpoint_ops is not defined, because in insert_bp_location,
2003    tracepoint's insert_location will not be called.  */
2004 static int
2005 should_be_inserted (struct bp_location *bl)
2006 {
2007   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2008     return 0;
2009
2010   if (bl->owner->disposition == disp_del_at_next_stop)
2011     return 0;
2012
2013   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2014     return 0;
2015
2016   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2017     return 0;
2018
2019   /* This is set for example, when we're attached to the parent of a
2020      vfork, and have detached from the child.  The child is running
2021      free, and we expect it to do an exec or exit, at which point the
2022      OS makes the parent schedulable again (and the target reports
2023      that the vfork is done).  Until the child is done with the shared
2024      memory region, do not insert breakpoints in the parent, otherwise
2025      the child could still trip on the parent's breakpoints.  Since
2026      the parent is blocked anyway, it won't miss any breakpoint.  */
2027   if (bl->pspace->breakpoints_not_allowed)
2028     return 0;
2029
2030   /* Don't insert a breakpoint if we're trying to step past its
2031      location, except if the breakpoint is a single-step breakpoint,
2032      and the breakpoint's thread is the thread which is stepping past
2033      a breakpoint.  */
2034   if ((bl->loc_type == bp_loc_software_breakpoint
2035        || bl->loc_type == bp_loc_hardware_breakpoint)
2036       && stepping_past_instruction_at (bl->pspace->aspace,
2037                                        bl->address)
2038       /* The single-step breakpoint may be inserted at the location
2039          we're trying to step if the instruction branches to itself.
2040          However, the instruction won't be executed at all and it may
2041          break the semantics of the instruction, for example, the
2042          instruction is a conditional branch or updates some flags.
2043          We can't fix it unless GDB is able to emulate the instruction
2044          or switch to displaced stepping.  */
2045       && !(bl->owner->type == bp_single_step
2046            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2047     {
2048       if (debug_infrun)
2049         {
2050           fprintf_unfiltered (gdb_stdlog,
2051                               "infrun: skipping breakpoint: "
2052                               "stepping past insn at: %s\n",
2053                               paddress (bl->gdbarch, bl->address));
2054         }
2055       return 0;
2056     }
2057
2058   /* Don't insert watchpoints if we're trying to step past the
2059      instruction that triggered one.  */
2060   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2061       && stepping_past_nonsteppable_watchpoint ())
2062     {
2063       if (debug_infrun)
2064         {
2065           fprintf_unfiltered (gdb_stdlog,
2066                               "infrun: stepping past non-steppable watchpoint. "
2067                               "skipping watchpoint at %s:%d\n",
2068                               paddress (bl->gdbarch, bl->address),
2069                               bl->length);
2070         }
2071       return 0;
2072     }
2073
2074   return 1;
2075 }
2076
2077 /* Same as should_be_inserted but does the check assuming
2078    that the location is not duplicated.  */
2079
2080 static int
2081 unduplicated_should_be_inserted (struct bp_location *bl)
2082 {
2083   int result;
2084   const int save_duplicate = bl->duplicate;
2085
2086   bl->duplicate = 0;
2087   result = should_be_inserted (bl);
2088   bl->duplicate = save_duplicate;
2089   return result;
2090 }
2091
2092 /* Parses a conditional described by an expression COND into an
2093    agent expression bytecode suitable for evaluation
2094    by the bytecode interpreter.  Return NULL if there was
2095    any error during parsing.  */
2096
2097 static agent_expr_up
2098 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2099 {
2100   if (cond == NULL)
2101     return NULL;
2102
2103   agent_expr_up aexpr;
2104
2105   /* We don't want to stop processing, so catch any errors
2106      that may show up.  */
2107   TRY
2108     {
2109       aexpr = gen_eval_for_expr (scope, cond);
2110     }
2111
2112   CATCH (ex, RETURN_MASK_ERROR)
2113     {
2114       /* If we got here, it means the condition could not be parsed to a valid
2115          bytecode expression and thus can't be evaluated on the target's side.
2116          It's no use iterating through the conditions.  */
2117     }
2118   END_CATCH
2119
2120   /* We have a valid agent expression.  */
2121   return aexpr;
2122 }
2123
2124 /* Based on location BL, create a list of breakpoint conditions to be
2125    passed on to the target.  If we have duplicated locations with different
2126    conditions, we will add such conditions to the list.  The idea is that the
2127    target will evaluate the list of conditions and will only notify GDB when
2128    one of them is true.  */
2129
2130 static void
2131 build_target_condition_list (struct bp_location *bl)
2132 {
2133   struct bp_location **locp = NULL, **loc2p;
2134   int null_condition_or_parse_error = 0;
2135   int modified = bl->needs_update;
2136   struct bp_location *loc;
2137
2138   /* Release conditions left over from a previous insert.  */
2139   bl->target_info.conditions.clear ();
2140
2141   /* This is only meaningful if the target is
2142      evaluating conditions and if the user has
2143      opted for condition evaluation on the target's
2144      side.  */
2145   if (gdb_evaluates_breakpoint_condition_p ()
2146       || !target_supports_evaluation_of_breakpoint_conditions ())
2147     return;
2148
2149   /* Do a first pass to check for locations with no assigned
2150      conditions or conditions that fail to parse to a valid agent expression
2151      bytecode.  If any of these happen, then it's no use to send conditions
2152      to the target since this location will always trigger and generate a
2153      response back to GDB.  */
2154   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2155     {
2156       loc = (*loc2p);
2157       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2158         {
2159           if (modified)
2160             {
2161               /* Re-parse the conditions since something changed.  In that
2162                  case we already freed the condition bytecodes (see
2163                  force_breakpoint_reinsertion).  We just
2164                  need to parse the condition to bytecodes again.  */
2165               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2166                                                         loc->cond.get ());
2167             }
2168
2169           /* If we have a NULL bytecode expression, it means something
2170              went wrong or we have a null condition expression.  */
2171           if (!loc->cond_bytecode)
2172             {
2173               null_condition_or_parse_error = 1;
2174               break;
2175             }
2176         }
2177     }
2178
2179   /* If any of these happened, it means we will have to evaluate the conditions
2180      for the location's address on gdb's side.  It is no use keeping bytecodes
2181      for all the other duplicate locations, thus we free all of them here.
2182
2183      This is so we have a finer control over which locations' conditions are
2184      being evaluated by GDB or the remote stub.  */
2185   if (null_condition_or_parse_error)
2186     {
2187       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2188         {
2189           loc = (*loc2p);
2190           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2191             {
2192               /* Only go as far as the first NULL bytecode is
2193                  located.  */
2194               if (!loc->cond_bytecode)
2195                 return;
2196
2197               loc->cond_bytecode.reset ();
2198             }
2199         }
2200     }
2201
2202   /* No NULL conditions or failed bytecode generation.  Build a condition list
2203      for this location's address.  */
2204   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2205     {
2206       loc = (*loc2p);
2207       if (loc->cond
2208           && is_breakpoint (loc->owner)
2209           && loc->pspace->num == bl->pspace->num
2210           && loc->owner->enable_state == bp_enabled
2211           && loc->enabled)
2212         {
2213           /* Add the condition to the vector.  This will be used later
2214              to send the conditions to the target.  */
2215           bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2216         }
2217     }
2218
2219   return;
2220 }
2221
2222 /* Parses a command described by string CMD into an agent expression
2223    bytecode suitable for evaluation by the bytecode interpreter.
2224    Return NULL if there was any error during parsing.  */
2225
2226 static agent_expr_up
2227 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2228 {
2229   struct cleanup *old_cleanups = 0;
2230   struct expression **argvec;
2231   const char *cmdrest;
2232   const char *format_start, *format_end;
2233   struct format_piece *fpieces;
2234   int nargs;
2235   struct gdbarch *gdbarch = get_current_arch ();
2236
2237   if (cmd == NULL)
2238     return NULL;
2239
2240   cmdrest = cmd;
2241
2242   if (*cmdrest == ',')
2243     ++cmdrest;
2244   cmdrest = skip_spaces (cmdrest);
2245
2246   if (*cmdrest++ != '"')
2247     error (_("No format string following the location"));
2248
2249   format_start = cmdrest;
2250
2251   fpieces = parse_format_string (&cmdrest);
2252
2253   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2254
2255   format_end = cmdrest;
2256
2257   if (*cmdrest++ != '"')
2258     error (_("Bad format string, non-terminated '\"'."));
2259   
2260   cmdrest = skip_spaces (cmdrest);
2261
2262   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2263     error (_("Invalid argument syntax"));
2264
2265   if (*cmdrest == ',')
2266     cmdrest++;
2267   cmdrest = skip_spaces (cmdrest);
2268
2269   /* For each argument, make an expression.  */
2270
2271   argvec = (struct expression **) alloca (strlen (cmd)
2272                                          * sizeof (struct expression *));
2273
2274   nargs = 0;
2275   while (*cmdrest != '\0')
2276     {
2277       const char *cmd1;
2278
2279       cmd1 = cmdrest;
2280       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2281       argvec[nargs++] = expr.release ();
2282       cmdrest = cmd1;
2283       if (*cmdrest == ',')
2284         ++cmdrest;
2285     }
2286
2287   agent_expr_up aexpr;
2288
2289   /* We don't want to stop processing, so catch any errors
2290      that may show up.  */
2291   TRY
2292     {
2293       aexpr = gen_printf (scope, gdbarch, 0, 0,
2294                           format_start, format_end - format_start,
2295                           fpieces, nargs, argvec);
2296     }
2297   CATCH (ex, RETURN_MASK_ERROR)
2298     {
2299       /* If we got here, it means the command could not be parsed to a valid
2300          bytecode expression and thus can't be evaluated on the target's side.
2301          It's no use iterating through the other commands.  */
2302     }
2303   END_CATCH
2304
2305   do_cleanups (old_cleanups);
2306
2307   /* We have a valid agent expression, return it.  */
2308   return aexpr;
2309 }
2310
2311 /* Based on location BL, create a list of breakpoint commands to be
2312    passed on to the target.  If we have duplicated locations with
2313    different commands, we will add any such to the list.  */
2314
2315 static void
2316 build_target_command_list (struct bp_location *bl)
2317 {
2318   struct bp_location **locp = NULL, **loc2p;
2319   int null_command_or_parse_error = 0;
2320   int modified = bl->needs_update;
2321   struct bp_location *loc;
2322
2323   /* Clear commands left over from a previous insert.  */
2324   bl->target_info.tcommands.clear ();
2325
2326   if (!target_can_run_breakpoint_commands ())
2327     return;
2328
2329   /* For now, limit to agent-style dprintf breakpoints.  */
2330   if (dprintf_style != dprintf_style_agent)
2331     return;
2332
2333   /* For now, if we have any duplicate location that isn't a dprintf,
2334      don't install the target-side commands, as that would make the
2335      breakpoint not be reported to the core, and we'd lose
2336      control.  */
2337   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2338     {
2339       loc = (*loc2p);
2340       if (is_breakpoint (loc->owner)
2341           && loc->pspace->num == bl->pspace->num
2342           && loc->owner->type != bp_dprintf)
2343         return;
2344     }
2345
2346   /* Do a first pass to check for locations with no assigned
2347      conditions or conditions that fail to parse to a valid agent expression
2348      bytecode.  If any of these happen, then it's no use to send conditions
2349      to the target since this location will always trigger and generate a
2350      response back to GDB.  */
2351   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2352     {
2353       loc = (*loc2p);
2354       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2355         {
2356           if (modified)
2357             {
2358               /* Re-parse the commands since something changed.  In that
2359                  case we already freed the command bytecodes (see
2360                  force_breakpoint_reinsertion).  We just
2361                  need to parse the command to bytecodes again.  */
2362               loc->cmd_bytecode
2363                 = parse_cmd_to_aexpr (bl->address,
2364                                       loc->owner->extra_string);
2365             }
2366
2367           /* If we have a NULL bytecode expression, it means something
2368              went wrong or we have a null command expression.  */
2369           if (!loc->cmd_bytecode)
2370             {
2371               null_command_or_parse_error = 1;
2372               break;
2373             }
2374         }
2375     }
2376
2377   /* If anything failed, then we're not doing target-side commands,
2378      and so clean up.  */
2379   if (null_command_or_parse_error)
2380     {
2381       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2382         {
2383           loc = (*loc2p);
2384           if (is_breakpoint (loc->owner)
2385               && loc->pspace->num == bl->pspace->num)
2386             {
2387               /* Only go as far as the first NULL bytecode is
2388                  located.  */
2389               if (loc->cmd_bytecode == NULL)
2390                 return;
2391
2392               loc->cmd_bytecode.reset ();
2393             }
2394         }
2395     }
2396
2397   /* No NULL commands or failed bytecode generation.  Build a command list
2398      for this location's address.  */
2399   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2400     {
2401       loc = (*loc2p);
2402       if (loc->owner->extra_string
2403           && is_breakpoint (loc->owner)
2404           && loc->pspace->num == bl->pspace->num
2405           && loc->owner->enable_state == bp_enabled
2406           && loc->enabled)
2407         {
2408           /* Add the command to the vector.  This will be used later
2409              to send the commands to the target.  */
2410           bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2411         }
2412     }
2413
2414   bl->target_info.persist = 0;
2415   /* Maybe flag this location as persistent.  */
2416   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2417     bl->target_info.persist = 1;
2418 }
2419
2420 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2421    of breakpoint according to ADDR except single-step breakpoint.
2422    Get the kind of single-step breakpoint according to the current
2423    registers state.  */
2424
2425 static int
2426 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2427 {
2428   if (bl->owner->type == bp_single_step)
2429     {
2430       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2431       struct regcache *regcache;
2432
2433       regcache = get_thread_regcache (thr->ptid);
2434
2435       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2436                                                          regcache, addr);
2437     }
2438   else
2439     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2440 }
2441
2442 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2443    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2444    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2445    Returns 0 for success, 1 if the bp_location type is not supported or
2446    -1 for failure.
2447
2448    NOTE drow/2003-09-09: This routine could be broken down to an
2449    object-style method for each breakpoint or catchpoint type.  */
2450 static int
2451 insert_bp_location (struct bp_location *bl,
2452                     struct ui_file *tmp_error_stream,
2453                     int *disabled_breaks,
2454                     int *hw_breakpoint_error,
2455                     int *hw_bp_error_explained_already)
2456 {
2457   gdb_exception bp_excpt = exception_none;
2458
2459   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2460     return 0;
2461
2462   /* Note we don't initialize bl->target_info, as that wipes out
2463      the breakpoint location's shadow_contents if the breakpoint
2464      is still inserted at that location.  This in turn breaks
2465      target_read_memory which depends on these buffers when
2466      a memory read is requested at the breakpoint location:
2467      Once the target_info has been wiped, we fail to see that
2468      we have a breakpoint inserted at that address and thus
2469      read the breakpoint instead of returning the data saved in
2470      the breakpoint location's shadow contents.  */
2471   bl->target_info.reqstd_address = bl->address;
2472   bl->target_info.placed_address_space = bl->pspace->aspace;
2473   bl->target_info.length = bl->length;
2474
2475   /* When working with target-side conditions, we must pass all the conditions
2476      for the same breakpoint address down to the target since GDB will not
2477      insert those locations.  With a list of breakpoint conditions, the target
2478      can decide when to stop and notify GDB.  */
2479
2480   if (is_breakpoint (bl->owner))
2481     {
2482       build_target_condition_list (bl);
2483       build_target_command_list (bl);
2484       /* Reset the modification marker.  */
2485       bl->needs_update = 0;
2486     }
2487
2488   if (bl->loc_type == bp_loc_software_breakpoint
2489       || bl->loc_type == bp_loc_hardware_breakpoint)
2490     {
2491       if (bl->owner->type != bp_hardware_breakpoint)
2492         {
2493           /* If the explicitly specified breakpoint type
2494              is not hardware breakpoint, check the memory map to see
2495              if the breakpoint address is in read only memory or not.
2496
2497              Two important cases are:
2498              - location type is not hardware breakpoint, memory
2499              is readonly.  We change the type of the location to
2500              hardware breakpoint.
2501              - location type is hardware breakpoint, memory is
2502              read-write.  This means we've previously made the
2503              location hardware one, but then the memory map changed,
2504              so we undo.
2505              
2506              When breakpoints are removed, remove_breakpoints will use
2507              location types we've just set here, the only possible
2508              problem is that memory map has changed during running
2509              program, but it's not going to work anyway with current
2510              gdb.  */
2511           struct mem_region *mr 
2512             = lookup_mem_region (bl->target_info.reqstd_address);
2513           
2514           if (mr)
2515             {
2516               if (automatic_hardware_breakpoints)
2517                 {
2518                   enum bp_loc_type new_type;
2519                   
2520                   if (mr->attrib.mode != MEM_RW)
2521                     new_type = bp_loc_hardware_breakpoint;
2522                   else 
2523                     new_type = bp_loc_software_breakpoint;
2524                   
2525                   if (new_type != bl->loc_type)
2526                     {
2527                       static int said = 0;
2528
2529                       bl->loc_type = new_type;
2530                       if (!said)
2531                         {
2532                           fprintf_filtered (gdb_stdout,
2533                                             _("Note: automatically using "
2534                                               "hardware breakpoints for "
2535                                               "read-only addresses.\n"));
2536                           said = 1;
2537                         }
2538                     }
2539                 }
2540               else if (bl->loc_type == bp_loc_software_breakpoint
2541                        && mr->attrib.mode != MEM_RW)
2542                 {
2543                   fprintf_unfiltered (tmp_error_stream,
2544                                       _("Cannot insert breakpoint %d.\n"
2545                                         "Cannot set software breakpoint "
2546                                         "at read-only address %s\n"),
2547                                       bl->owner->number,
2548                                       paddress (bl->gdbarch, bl->address));
2549                   return 1;
2550                 }
2551             }
2552         }
2553         
2554       /* First check to see if we have to handle an overlay.  */
2555       if (overlay_debugging == ovly_off
2556           || bl->section == NULL
2557           || !(section_is_overlay (bl->section)))
2558         {
2559           /* No overlay handling: just set the breakpoint.  */
2560           TRY
2561             {
2562               int val;
2563
2564               val = bl->owner->ops->insert_location (bl);
2565               if (val)
2566                 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2567             }
2568           CATCH (e, RETURN_MASK_ALL)
2569             {
2570               bp_excpt = e;
2571             }
2572           END_CATCH
2573         }
2574       else
2575         {
2576           /* This breakpoint is in an overlay section.
2577              Shall we set a breakpoint at the LMA?  */
2578           if (!overlay_events_enabled)
2579             {
2580               /* Yes -- overlay event support is not active, 
2581                  so we must try to set a breakpoint at the LMA.
2582                  This will not work for a hardware breakpoint.  */
2583               if (bl->loc_type == bp_loc_hardware_breakpoint)
2584                 warning (_("hardware breakpoint %d not supported in overlay!"),
2585                          bl->owner->number);
2586               else
2587                 {
2588                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2589                                                              bl->section);
2590                   /* Set a software (trap) breakpoint at the LMA.  */
2591                   bl->overlay_target_info = bl->target_info;
2592                   bl->overlay_target_info.reqstd_address = addr;
2593
2594                   /* No overlay handling: just set the breakpoint.  */
2595                   TRY
2596                     {
2597                       int val;
2598
2599                       bl->overlay_target_info.kind
2600                         = breakpoint_kind (bl, &addr);
2601                       bl->overlay_target_info.placed_address = addr;
2602                       val = target_insert_breakpoint (bl->gdbarch,
2603                                                       &bl->overlay_target_info);
2604                       if (val)
2605                         bp_excpt
2606                           = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2607                     }
2608                   CATCH (e, RETURN_MASK_ALL)
2609                     {
2610                       bp_excpt = e;
2611                     }
2612                   END_CATCH
2613
2614                   if (bp_excpt.reason != 0)
2615                     fprintf_unfiltered (tmp_error_stream,
2616                                         "Overlay breakpoint %d "
2617                                         "failed: in ROM?\n",
2618                                         bl->owner->number);
2619                 }
2620             }
2621           /* Shall we set a breakpoint at the VMA? */
2622           if (section_is_mapped (bl->section))
2623             {
2624               /* Yes.  This overlay section is mapped into memory.  */
2625               TRY
2626                 {
2627                   int val;
2628
2629                   val = bl->owner->ops->insert_location (bl);
2630                   if (val)
2631                     bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2632                 }
2633               CATCH (e, RETURN_MASK_ALL)
2634                 {
2635                   bp_excpt = e;
2636                 }
2637               END_CATCH
2638             }
2639           else
2640             {
2641               /* No.  This breakpoint will not be inserted.  
2642                  No error, but do not mark the bp as 'inserted'.  */
2643               return 0;
2644             }
2645         }
2646
2647       if (bp_excpt.reason != 0)
2648         {
2649           /* Can't set the breakpoint.  */
2650
2651           /* In some cases, we might not be able to insert a
2652              breakpoint in a shared library that has already been
2653              removed, but we have not yet processed the shlib unload
2654              event.  Unfortunately, some targets that implement
2655              breakpoint insertion themselves can't tell why the
2656              breakpoint insertion failed (e.g., the remote target
2657              doesn't define error codes), so we must treat generic
2658              errors as memory errors.  */
2659           if (bp_excpt.reason == RETURN_ERROR
2660               && (bp_excpt.error == GENERIC_ERROR
2661                   || bp_excpt.error == MEMORY_ERROR)
2662               && bl->loc_type == bp_loc_software_breakpoint
2663               && (solib_name_from_address (bl->pspace, bl->address)
2664                   || shared_objfile_contains_address_p (bl->pspace,
2665                                                         bl->address)))
2666             {
2667               /* See also: disable_breakpoints_in_shlibs.  */
2668               bl->shlib_disabled = 1;
2669               observer_notify_breakpoint_modified (bl->owner);
2670               if (!*disabled_breaks)
2671                 {
2672                   fprintf_unfiltered (tmp_error_stream, 
2673                                       "Cannot insert breakpoint %d.\n", 
2674                                       bl->owner->number);
2675                   fprintf_unfiltered (tmp_error_stream, 
2676                                       "Temporarily disabling shared "
2677                                       "library breakpoints:\n");
2678                 }
2679               *disabled_breaks = 1;
2680               fprintf_unfiltered (tmp_error_stream,
2681                                   "breakpoint #%d\n", bl->owner->number);
2682               return 0;
2683             }
2684           else
2685             {
2686               if (bl->loc_type == bp_loc_hardware_breakpoint)
2687                 {
2688                   *hw_breakpoint_error = 1;
2689                   *hw_bp_error_explained_already = bp_excpt.message != NULL;
2690                   fprintf_unfiltered (tmp_error_stream,
2691                                       "Cannot insert hardware breakpoint %d%s",
2692                                       bl->owner->number,
2693                                       bp_excpt.message ? ":" : ".\n");
2694                   if (bp_excpt.message != NULL)
2695                     fprintf_unfiltered (tmp_error_stream, "%s.\n",
2696                                         bp_excpt.message);
2697                 }
2698               else
2699                 {
2700                   if (bp_excpt.message == NULL)
2701                     {
2702                       std::string message
2703                         = memory_error_message (TARGET_XFER_E_IO,
2704                                                 bl->gdbarch, bl->address);
2705
2706                       fprintf_unfiltered (tmp_error_stream,
2707                                           "Cannot insert breakpoint %d.\n"
2708                                           "%s\n",
2709                                           bl->owner->number, message.c_str ());
2710                     }
2711                   else
2712                     {
2713                       fprintf_unfiltered (tmp_error_stream,
2714                                           "Cannot insert breakpoint %d: %s\n",
2715                                           bl->owner->number,
2716                                           bp_excpt.message);
2717                     }
2718                 }
2719               return 1;
2720
2721             }
2722         }
2723       else
2724         bl->inserted = 1;
2725
2726       return 0;
2727     }
2728
2729   else if (bl->loc_type == bp_loc_hardware_watchpoint
2730            /* NOTE drow/2003-09-08: This state only exists for removing
2731               watchpoints.  It's not clear that it's necessary...  */
2732            && bl->owner->disposition != disp_del_at_next_stop)
2733     {
2734       int val;
2735
2736       gdb_assert (bl->owner->ops != NULL
2737                   && bl->owner->ops->insert_location != NULL);
2738
2739       val = bl->owner->ops->insert_location (bl);
2740
2741       /* If trying to set a read-watchpoint, and it turns out it's not
2742          supported, try emulating one with an access watchpoint.  */
2743       if (val == 1 && bl->watchpoint_type == hw_read)
2744         {
2745           struct bp_location *loc, **loc_temp;
2746
2747           /* But don't try to insert it, if there's already another
2748              hw_access location that would be considered a duplicate
2749              of this one.  */
2750           ALL_BP_LOCATIONS (loc, loc_temp)
2751             if (loc != bl
2752                 && loc->watchpoint_type == hw_access
2753                 && watchpoint_locations_match (bl, loc))
2754               {
2755                 bl->duplicate = 1;
2756                 bl->inserted = 1;
2757                 bl->target_info = loc->target_info;
2758                 bl->watchpoint_type = hw_access;
2759                 val = 0;
2760                 break;
2761               }
2762
2763           if (val == 1)
2764             {
2765               bl->watchpoint_type = hw_access;
2766               val = bl->owner->ops->insert_location (bl);
2767
2768               if (val)
2769                 /* Back to the original value.  */
2770                 bl->watchpoint_type = hw_read;
2771             }
2772         }
2773
2774       bl->inserted = (val == 0);
2775     }
2776
2777   else if (bl->owner->type == bp_catchpoint)
2778     {
2779       int val;
2780
2781       gdb_assert (bl->owner->ops != NULL
2782                   && bl->owner->ops->insert_location != NULL);
2783
2784       val = bl->owner->ops->insert_location (bl);
2785       if (val)
2786         {
2787           bl->owner->enable_state = bp_disabled;
2788
2789           if (val == 1)
2790             warning (_("\
2791 Error inserting catchpoint %d: Your system does not support this type\n\
2792 of catchpoint."), bl->owner->number);
2793           else
2794             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2795         }
2796
2797       bl->inserted = (val == 0);
2798
2799       /* We've already printed an error message if there was a problem
2800          inserting this catchpoint, and we've disabled the catchpoint,
2801          so just return success.  */
2802       return 0;
2803     }
2804
2805   return 0;
2806 }
2807
2808 /* This function is called when program space PSPACE is about to be
2809    deleted.  It takes care of updating breakpoints to not reference
2810    PSPACE anymore.  */
2811
2812 void
2813 breakpoint_program_space_exit (struct program_space *pspace)
2814 {
2815   struct breakpoint *b, *b_temp;
2816   struct bp_location *loc, **loc_temp;
2817
2818   /* Remove any breakpoint that was set through this program space.  */
2819   ALL_BREAKPOINTS_SAFE (b, b_temp)
2820     {
2821       if (b->pspace == pspace)
2822         delete_breakpoint (b);
2823     }
2824
2825   /* Breakpoints set through other program spaces could have locations
2826      bound to PSPACE as well.  Remove those.  */
2827   ALL_BP_LOCATIONS (loc, loc_temp)
2828     {
2829       struct bp_location *tmp;
2830
2831       if (loc->pspace == pspace)
2832         {
2833           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2834           if (loc->owner->loc == loc)
2835             loc->owner->loc = loc->next;
2836           else
2837             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2838               if (tmp->next == loc)
2839                 {
2840                   tmp->next = loc->next;
2841                   break;
2842                 }
2843         }
2844     }
2845
2846   /* Now update the global location list to permanently delete the
2847      removed locations above.  */
2848   update_global_location_list (UGLL_DONT_INSERT);
2849 }
2850
2851 /* Make sure all breakpoints are inserted in inferior.
2852    Throws exception on any error.
2853    A breakpoint that is already inserted won't be inserted
2854    again, so calling this function twice is safe.  */
2855 void
2856 insert_breakpoints (void)
2857 {
2858   struct breakpoint *bpt;
2859
2860   ALL_BREAKPOINTS (bpt)
2861     if (is_hardware_watchpoint (bpt))
2862       {
2863         struct watchpoint *w = (struct watchpoint *) bpt;
2864
2865         update_watchpoint (w, 0 /* don't reparse.  */);
2866       }
2867
2868   /* Updating watchpoints creates new locations, so update the global
2869      location list.  Explicitly tell ugll to insert locations and
2870      ignore breakpoints_always_inserted_mode.  */
2871   update_global_location_list (UGLL_INSERT);
2872 }
2873
2874 /* Invoke CALLBACK for each of bp_location.  */
2875
2876 void
2877 iterate_over_bp_locations (walk_bp_location_callback callback)
2878 {
2879   struct bp_location *loc, **loc_tmp;
2880
2881   ALL_BP_LOCATIONS (loc, loc_tmp)
2882     {
2883       callback (loc, NULL);
2884     }
2885 }
2886
2887 /* This is used when we need to synch breakpoint conditions between GDB and the
2888    target.  It is the case with deleting and disabling of breakpoints when using
2889    always-inserted mode.  */
2890
2891 static void
2892 update_inserted_breakpoint_locations (void)
2893 {
2894   struct bp_location *bl, **blp_tmp;
2895   int error_flag = 0;
2896   int val = 0;
2897   int disabled_breaks = 0;
2898   int hw_breakpoint_error = 0;
2899   int hw_bp_details_reported = 0;
2900
2901   string_file tmp_error_stream;
2902
2903   /* Explicitly mark the warning -- this will only be printed if
2904      there was an error.  */
2905   tmp_error_stream.puts ("Warning:\n");
2906
2907   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2908
2909   ALL_BP_LOCATIONS (bl, blp_tmp)
2910     {
2911       /* We only want to update software breakpoints and hardware
2912          breakpoints.  */
2913       if (!is_breakpoint (bl->owner))
2914         continue;
2915
2916       /* We only want to update locations that are already inserted
2917          and need updating.  This is to avoid unwanted insertion during
2918          deletion of breakpoints.  */
2919       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2920         continue;
2921
2922       switch_to_program_space_and_thread (bl->pspace);
2923
2924       /* For targets that support global breakpoints, there's no need
2925          to select an inferior to insert breakpoint to.  In fact, even
2926          if we aren't attached to any process yet, we should still
2927          insert breakpoints.  */
2928       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2929           && ptid_equal (inferior_ptid, null_ptid))
2930         continue;
2931
2932       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2933                                     &hw_breakpoint_error, &hw_bp_details_reported);
2934       if (val)
2935         error_flag = val;
2936     }
2937
2938   if (error_flag)
2939     {
2940       target_terminal::ours_for_output ();
2941       error_stream (tmp_error_stream);
2942     }
2943 }
2944
2945 /* Used when starting or continuing the program.  */
2946
2947 static void
2948 insert_breakpoint_locations (void)
2949 {
2950   struct breakpoint *bpt;
2951   struct bp_location *bl, **blp_tmp;
2952   int error_flag = 0;
2953   int val = 0;
2954   int disabled_breaks = 0;
2955   int hw_breakpoint_error = 0;
2956   int hw_bp_error_explained_already = 0;
2957
2958   string_file tmp_error_stream;
2959
2960   /* Explicitly mark the warning -- this will only be printed if
2961      there was an error.  */
2962   tmp_error_stream.puts ("Warning:\n");
2963
2964   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2965
2966   ALL_BP_LOCATIONS (bl, blp_tmp)
2967     {
2968       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2969         continue;
2970
2971       /* There is no point inserting thread-specific breakpoints if
2972          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2973          has BL->OWNER always non-NULL.  */
2974       if (bl->owner->thread != -1
2975           && !valid_global_thread_id (bl->owner->thread))
2976         continue;
2977
2978       switch_to_program_space_and_thread (bl->pspace);
2979
2980       /* For targets that support global breakpoints, there's no need
2981          to select an inferior to insert breakpoint to.  In fact, even
2982          if we aren't attached to any process yet, we should still
2983          insert breakpoints.  */
2984       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2985           && ptid_equal (inferior_ptid, null_ptid))
2986         continue;
2987
2988       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2989                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
2990       if (val)
2991         error_flag = val;
2992     }
2993
2994   /* If we failed to insert all locations of a watchpoint, remove
2995      them, as half-inserted watchpoint is of limited use.  */
2996   ALL_BREAKPOINTS (bpt)  
2997     {
2998       int some_failed = 0;
2999       struct bp_location *loc;
3000
3001       if (!is_hardware_watchpoint (bpt))
3002         continue;
3003
3004       if (!breakpoint_enabled (bpt))
3005         continue;
3006
3007       if (bpt->disposition == disp_del_at_next_stop)
3008         continue;
3009       
3010       for (loc = bpt->loc; loc; loc = loc->next)
3011         if (!loc->inserted && should_be_inserted (loc))
3012           {
3013             some_failed = 1;
3014             break;
3015           }
3016       if (some_failed)
3017         {
3018           for (loc = bpt->loc; loc; loc = loc->next)
3019             if (loc->inserted)
3020               remove_breakpoint (loc);
3021
3022           hw_breakpoint_error = 1;
3023           tmp_error_stream.printf ("Could not insert "
3024                                    "hardware watchpoint %d.\n",
3025                                    bpt->number);
3026           error_flag = -1;
3027         }
3028     }
3029
3030   if (error_flag)
3031     {
3032       /* If a hardware breakpoint or watchpoint was inserted, add a
3033          message about possibly exhausted resources.  */
3034       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3035         {
3036           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3037 You may have requested too many hardware breakpoints/watchpoints.\n");
3038         }
3039       target_terminal::ours_for_output ();
3040       error_stream (tmp_error_stream);
3041     }
3042 }
3043
3044 /* Used when the program stops.
3045    Returns zero if successful, or non-zero if there was a problem
3046    removing a breakpoint location.  */
3047
3048 int
3049 remove_breakpoints (void)
3050 {
3051   struct bp_location *bl, **blp_tmp;
3052   int val = 0;
3053
3054   ALL_BP_LOCATIONS (bl, blp_tmp)
3055   {
3056     if (bl->inserted && !is_tracepoint (bl->owner))
3057       val |= remove_breakpoint (bl);
3058   }
3059   return val;
3060 }
3061
3062 /* When a thread exits, remove breakpoints that are related to
3063    that thread.  */
3064
3065 static void
3066 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3067 {
3068   struct breakpoint *b, *b_tmp;
3069
3070   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3071     {
3072       if (b->thread == tp->global_num && user_breakpoint_p (b))
3073         {
3074           b->disposition = disp_del_at_next_stop;
3075
3076           printf_filtered (_("\
3077 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3078                            b->number, print_thread_id (tp));
3079
3080           /* Hide it from the user.  */
3081           b->number = 0;
3082        }
3083     }
3084 }
3085
3086 /* Remove breakpoints of process PID.  */
3087
3088 int
3089 remove_breakpoints_pid (int pid)
3090 {
3091   struct bp_location *bl, **blp_tmp;
3092   int val;
3093   struct inferior *inf = find_inferior_pid (pid);
3094
3095   ALL_BP_LOCATIONS (bl, blp_tmp)
3096   {
3097     if (bl->pspace != inf->pspace)
3098       continue;
3099
3100     if (bl->inserted && !bl->target_info.persist)
3101       {
3102         val = remove_breakpoint (bl);
3103         if (val != 0)
3104           return val;
3105       }
3106   }
3107   return 0;
3108 }
3109
3110 static int internal_breakpoint_number = -1;
3111
3112 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3113    If INTERNAL is non-zero, the breakpoint number will be populated
3114    from internal_breakpoint_number and that variable decremented.
3115    Otherwise the breakpoint number will be populated from
3116    breakpoint_count and that value incremented.  Internal breakpoints
3117    do not set the internal var bpnum.  */
3118 static void
3119 set_breakpoint_number (int internal, struct breakpoint *b)
3120 {
3121   if (internal)
3122     b->number = internal_breakpoint_number--;
3123   else
3124     {
3125       set_breakpoint_count (breakpoint_count + 1);
3126       b->number = breakpoint_count;
3127     }
3128 }
3129
3130 static struct breakpoint *
3131 create_internal_breakpoint (struct gdbarch *gdbarch,
3132                             CORE_ADDR address, enum bptype type,
3133                             const struct breakpoint_ops *ops)
3134 {
3135   symtab_and_line sal;
3136   sal.pc = address;
3137   sal.section = find_pc_overlay (sal.pc);
3138   sal.pspace = current_program_space;
3139
3140   breakpoint *b = set_raw_breakpoint (gdbarch, sal, type, ops);
3141   b->number = internal_breakpoint_number--;
3142   b->disposition = disp_donttouch;
3143
3144   return b;
3145 }
3146
3147 static const char *const longjmp_names[] =
3148   {
3149     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3150   };
3151 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3152
3153 /* Per-objfile data private to breakpoint.c.  */
3154 struct breakpoint_objfile_data
3155 {
3156   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3157   struct bound_minimal_symbol overlay_msym {};
3158
3159   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3160   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES] {};
3161
3162   /* True if we have looked for longjmp probes.  */
3163   int longjmp_searched = 0;
3164
3165   /* SystemTap probe points for longjmp (if any).  These are non-owning
3166      references.  */
3167   std::vector<probe *> longjmp_probes;
3168
3169   /* Minimal symbol for "std::terminate()" (if any).  */
3170   struct bound_minimal_symbol terminate_msym {};
3171
3172   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3173   struct bound_minimal_symbol exception_msym {};
3174
3175   /* True if we have looked for exception probes.  */
3176   int exception_searched = 0;
3177
3178   /* SystemTap probe points for unwinding (if any).  These are non-owning
3179      references.  */
3180   std::vector<probe *> exception_probes;
3181 };
3182
3183 static const struct objfile_data *breakpoint_objfile_key;
3184
3185 /* Minimal symbol not found sentinel.  */
3186 static struct minimal_symbol msym_not_found;
3187
3188 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3189
3190 static int
3191 msym_not_found_p (const struct minimal_symbol *msym)
3192 {
3193   return msym == &msym_not_found;
3194 }
3195
3196 /* Return per-objfile data needed by breakpoint.c.
3197    Allocate the data if necessary.  */
3198
3199 static struct breakpoint_objfile_data *
3200 get_breakpoint_objfile_data (struct objfile *objfile)
3201 {
3202   struct breakpoint_objfile_data *bp_objfile_data;
3203
3204   bp_objfile_data = ((struct breakpoint_objfile_data *)
3205                      objfile_data (objfile, breakpoint_objfile_key));
3206   if (bp_objfile_data == NULL)
3207     {
3208       bp_objfile_data = new breakpoint_objfile_data ();
3209       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3210     }
3211   return bp_objfile_data;
3212 }
3213
3214 static void
3215 free_breakpoint_objfile_data (struct objfile *obj, void *data)
3216 {
3217   struct breakpoint_objfile_data *bp_objfile_data
3218     = (struct breakpoint_objfile_data *) data;
3219
3220   delete bp_objfile_data;
3221 }
3222
3223 static void
3224 create_overlay_event_breakpoint (void)
3225 {
3226   struct objfile *objfile;
3227   const char *const func_name = "_ovly_debug_event";
3228
3229   ALL_OBJFILES (objfile)
3230     {
3231       struct breakpoint *b;
3232       struct breakpoint_objfile_data *bp_objfile_data;
3233       CORE_ADDR addr;
3234       struct explicit_location explicit_loc;
3235
3236       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3237
3238       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3239         continue;
3240
3241       if (bp_objfile_data->overlay_msym.minsym == NULL)
3242         {
3243           struct bound_minimal_symbol m;
3244
3245           m = lookup_minimal_symbol_text (func_name, objfile);
3246           if (m.minsym == NULL)
3247             {
3248               /* Avoid future lookups in this objfile.  */
3249               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3250               continue;
3251             }
3252           bp_objfile_data->overlay_msym = m;
3253         }
3254
3255       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3256       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3257                                       bp_overlay_event,
3258                                       &internal_breakpoint_ops);
3259       initialize_explicit_location (&explicit_loc);
3260       explicit_loc.function_name = ASTRDUP (func_name);
3261       b->location = new_explicit_location (&explicit_loc);
3262
3263       if (overlay_debugging == ovly_auto)
3264         {
3265           b->enable_state = bp_enabled;
3266           overlay_events_enabled = 1;
3267         }
3268       else
3269        {
3270          b->enable_state = bp_disabled;
3271          overlay_events_enabled = 0;
3272        }
3273     }
3274 }
3275
3276 static void
3277 create_longjmp_master_breakpoint (void)
3278 {
3279   struct program_space *pspace;
3280
3281   scoped_restore_current_program_space restore_pspace;
3282
3283   ALL_PSPACES (pspace)
3284   {
3285     struct objfile *objfile;
3286
3287     set_current_program_space (pspace);
3288
3289     ALL_OBJFILES (objfile)
3290     {
3291       int i;
3292       struct gdbarch *gdbarch;
3293       struct breakpoint_objfile_data *bp_objfile_data;
3294
3295       gdbarch = get_objfile_arch (objfile);
3296
3297       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3298
3299       if (!bp_objfile_data->longjmp_searched)
3300         {
3301           std::vector<probe *> ret
3302             = find_probes_in_objfile (objfile, "libc", "longjmp");
3303
3304           if (!ret.empty ())
3305             {
3306               /* We are only interested in checking one element.  */
3307               probe *p = ret[0];
3308
3309               if (!p->can_evaluate_arguments ())
3310                 {
3311                   /* We cannot use the probe interface here, because it does
3312                      not know how to evaluate arguments.  */
3313                   ret.clear ();
3314                 }
3315             }
3316           bp_objfile_data->longjmp_probes = ret;
3317           bp_objfile_data->longjmp_searched = 1;
3318         }
3319
3320       if (!bp_objfile_data->longjmp_probes.empty ())
3321         {
3322           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3323
3324           for (probe *p : bp_objfile_data->longjmp_probes)
3325             {
3326               struct breakpoint *b;
3327
3328               b = create_internal_breakpoint (gdbarch,
3329                                               p->get_relocated_address (objfile),
3330                                               bp_longjmp_master,
3331                                               &internal_breakpoint_ops);
3332               b->location = new_probe_location ("-probe-stap libc:longjmp");
3333               b->enable_state = bp_disabled;
3334             }
3335
3336           continue;
3337         }
3338
3339       if (!gdbarch_get_longjmp_target_p (gdbarch))
3340         continue;
3341
3342       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3343         {
3344           struct breakpoint *b;
3345           const char *func_name;
3346           CORE_ADDR addr;
3347           struct explicit_location explicit_loc;
3348
3349           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3350             continue;
3351
3352           func_name = longjmp_names[i];
3353           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3354             {
3355               struct bound_minimal_symbol m;
3356
3357               m = lookup_minimal_symbol_text (func_name, objfile);
3358               if (m.minsym == NULL)
3359                 {
3360                   /* Prevent future lookups in this objfile.  */
3361                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3362                   continue;
3363                 }
3364               bp_objfile_data->longjmp_msym[i] = m;
3365             }
3366
3367           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3368           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3369                                           &internal_breakpoint_ops);
3370           initialize_explicit_location (&explicit_loc);
3371           explicit_loc.function_name = ASTRDUP (func_name);
3372           b->location = new_explicit_location (&explicit_loc);
3373           b->enable_state = bp_disabled;
3374         }
3375     }
3376   }
3377 }
3378
3379 /* Create a master std::terminate breakpoint.  */
3380 static void
3381 create_std_terminate_master_breakpoint (void)
3382 {
3383   struct program_space *pspace;
3384   const char *const func_name = "std::terminate()";
3385
3386   scoped_restore_current_program_space restore_pspace;
3387
3388   ALL_PSPACES (pspace)
3389   {
3390     struct objfile *objfile;
3391     CORE_ADDR addr;
3392
3393     set_current_program_space (pspace);
3394
3395     ALL_OBJFILES (objfile)
3396     {
3397       struct breakpoint *b;
3398       struct breakpoint_objfile_data *bp_objfile_data;
3399       struct explicit_location explicit_loc;
3400
3401       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3402
3403       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3404         continue;
3405
3406       if (bp_objfile_data->terminate_msym.minsym == NULL)
3407         {
3408           struct bound_minimal_symbol m;
3409
3410           m = lookup_minimal_symbol (func_name, NULL, objfile);
3411           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3412                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3413             {
3414               /* Prevent future lookups in this objfile.  */
3415               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3416               continue;
3417             }
3418           bp_objfile_data->terminate_msym = m;
3419         }
3420
3421       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3422       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3423                                       bp_std_terminate_master,
3424                                       &internal_breakpoint_ops);
3425       initialize_explicit_location (&explicit_loc);
3426       explicit_loc.function_name = ASTRDUP (func_name);
3427       b->location = new_explicit_location (&explicit_loc);
3428       b->enable_state = bp_disabled;
3429     }
3430   }
3431 }
3432
3433 /* Install a master breakpoint on the unwinder's debug hook.  */
3434
3435 static void
3436 create_exception_master_breakpoint (void)
3437 {
3438   struct objfile *objfile;
3439   const char *const func_name = "_Unwind_DebugHook";
3440
3441   ALL_OBJFILES (objfile)
3442     {
3443       struct breakpoint *b;
3444       struct gdbarch *gdbarch;
3445       struct breakpoint_objfile_data *bp_objfile_data;
3446       CORE_ADDR addr;
3447       struct explicit_location explicit_loc;
3448
3449       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3450
3451       /* We prefer the SystemTap probe point if it exists.  */
3452       if (!bp_objfile_data->exception_searched)
3453         {
3454           std::vector<probe *> ret
3455             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3456
3457           if (!ret.empty ())
3458             {
3459               /* We are only interested in checking one element.  */
3460               probe *p = ret[0];
3461
3462               if (!p->can_evaluate_arguments ())
3463                 {
3464                   /* We cannot use the probe interface here, because it does
3465                      not know how to evaluate arguments.  */
3466                   ret.clear ();
3467                 }
3468             }
3469           bp_objfile_data->exception_probes = ret;
3470           bp_objfile_data->exception_searched = 1;
3471         }
3472
3473       if (!bp_objfile_data->exception_probes.empty ())
3474         {
3475           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3476
3477           for (probe *p : bp_objfile_data->exception_probes)
3478             {
3479               struct breakpoint *b;
3480
3481               b = create_internal_breakpoint (gdbarch,
3482                                               p->get_relocated_address (objfile),
3483                                               bp_exception_master,
3484                                               &internal_breakpoint_ops);
3485               b->location = new_probe_location ("-probe-stap libgcc:unwind");
3486               b->enable_state = bp_disabled;
3487             }
3488
3489           continue;
3490         }
3491
3492       /* Otherwise, try the hook function.  */
3493
3494       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3495         continue;
3496
3497       gdbarch = get_objfile_arch (objfile);
3498
3499       if (bp_objfile_data->exception_msym.minsym == NULL)
3500         {
3501           struct bound_minimal_symbol debug_hook;
3502
3503           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3504           if (debug_hook.minsym == NULL)
3505             {
3506               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3507               continue;
3508             }
3509
3510           bp_objfile_data->exception_msym = debug_hook;
3511         }
3512
3513       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3514       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3515                                                  &current_target);
3516       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3517                                       &internal_breakpoint_ops);
3518       initialize_explicit_location (&explicit_loc);
3519       explicit_loc.function_name = ASTRDUP (func_name);
3520       b->location = new_explicit_location (&explicit_loc);
3521       b->enable_state = bp_disabled;
3522     }
3523 }
3524
3525 /* Does B have a location spec?  */
3526
3527 static int
3528 breakpoint_event_location_empty_p (const struct breakpoint *b)
3529 {
3530   return b->location != NULL && event_location_empty_p (b->location.get ());
3531 }
3532
3533 void
3534 update_breakpoints_after_exec (void)
3535 {
3536   struct breakpoint *b, *b_tmp;
3537   struct bp_location *bploc, **bplocp_tmp;
3538
3539   /* We're about to delete breakpoints from GDB's lists.  If the
3540      INSERTED flag is true, GDB will try to lift the breakpoints by
3541      writing the breakpoints' "shadow contents" back into memory.  The
3542      "shadow contents" are NOT valid after an exec, so GDB should not
3543      do that.  Instead, the target is responsible from marking
3544      breakpoints out as soon as it detects an exec.  We don't do that
3545      here instead, because there may be other attempts to delete
3546      breakpoints after detecting an exec and before reaching here.  */
3547   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3548     if (bploc->pspace == current_program_space)
3549       gdb_assert (!bploc->inserted);
3550
3551   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3552   {
3553     if (b->pspace != current_program_space)
3554       continue;
3555
3556     /* Solib breakpoints must be explicitly reset after an exec().  */
3557     if (b->type == bp_shlib_event)
3558       {
3559         delete_breakpoint (b);
3560         continue;
3561       }
3562
3563     /* JIT breakpoints must be explicitly reset after an exec().  */
3564     if (b->type == bp_jit_event)
3565       {
3566         delete_breakpoint (b);
3567         continue;
3568       }
3569
3570     /* Thread event breakpoints must be set anew after an exec(),
3571        as must overlay event and longjmp master breakpoints.  */
3572     if (b->type == bp_thread_event || b->type == bp_overlay_event
3573         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3574         || b->type == bp_exception_master)
3575       {
3576         delete_breakpoint (b);
3577         continue;
3578       }
3579
3580     /* Step-resume breakpoints are meaningless after an exec().  */
3581     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3582       {
3583         delete_breakpoint (b);
3584         continue;
3585       }
3586
3587     /* Just like single-step breakpoints.  */
3588     if (b->type == bp_single_step)
3589       {
3590         delete_breakpoint (b);
3591         continue;
3592       }
3593
3594     /* Longjmp and longjmp-resume breakpoints are also meaningless
3595        after an exec.  */
3596     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3597         || b->type == bp_longjmp_call_dummy
3598         || b->type == bp_exception || b->type == bp_exception_resume)
3599       {
3600         delete_breakpoint (b);
3601         continue;
3602       }
3603
3604     if (b->type == bp_catchpoint)
3605       {
3606         /* For now, none of the bp_catchpoint breakpoints need to
3607            do anything at this point.  In the future, if some of
3608            the catchpoints need to something, we will need to add
3609            a new method, and call this method from here.  */
3610         continue;
3611       }
3612
3613     /* bp_finish is a special case.  The only way we ought to be able
3614        to see one of these when an exec() has happened, is if the user
3615        caught a vfork, and then said "finish".  Ordinarily a finish just
3616        carries them to the call-site of the current callee, by setting
3617        a temporary bp there and resuming.  But in this case, the finish
3618        will carry them entirely through the vfork & exec.
3619
3620        We don't want to allow a bp_finish to remain inserted now.  But
3621        we can't safely delete it, 'cause finish_command has a handle to
3622        the bp on a bpstat, and will later want to delete it.  There's a
3623        chance (and I've seen it happen) that if we delete the bp_finish
3624        here, that its storage will get reused by the time finish_command
3625        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3626        We really must allow finish_command to delete a bp_finish.
3627
3628        In the absence of a general solution for the "how do we know
3629        it's safe to delete something others may have handles to?"
3630        problem, what we'll do here is just uninsert the bp_finish, and
3631        let finish_command delete it.
3632
3633        (We know the bp_finish is "doomed" in the sense that it's
3634        momentary, and will be deleted as soon as finish_command sees
3635        the inferior stopped.  So it doesn't matter that the bp's
3636        address is probably bogus in the new a.out, unlike e.g., the
3637        solib breakpoints.)  */
3638
3639     if (b->type == bp_finish)
3640       {
3641         continue;
3642       }
3643
3644     /* Without a symbolic address, we have little hope of the
3645        pre-exec() address meaning the same thing in the post-exec()
3646        a.out.  */
3647     if (breakpoint_event_location_empty_p (b))
3648       {
3649         delete_breakpoint (b);
3650         continue;
3651       }
3652   }
3653 }
3654
3655 int
3656 detach_breakpoints (ptid_t ptid)
3657 {
3658   struct bp_location *bl, **blp_tmp;
3659   int val = 0;
3660   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3661   struct inferior *inf = current_inferior ();
3662
3663   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3664     error (_("Cannot detach breakpoints of inferior_ptid"));
3665
3666   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3667   inferior_ptid = ptid;
3668   ALL_BP_LOCATIONS (bl, blp_tmp)
3669   {
3670     if (bl->pspace != inf->pspace)
3671       continue;
3672
3673     /* This function must physically remove breakpoints locations
3674        from the specified ptid, without modifying the breakpoint
3675        package's state.  Locations of type bp_loc_other are only
3676        maintained at GDB side.  So, there is no need to remove
3677        these bp_loc_other locations.  Moreover, removing these
3678        would modify the breakpoint package's state.  */
3679     if (bl->loc_type == bp_loc_other)
3680       continue;
3681
3682     if (bl->inserted)
3683       val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3684   }
3685
3686   return val;
3687 }
3688
3689 /* Remove the breakpoint location BL from the current address space.
3690    Note that this is used to detach breakpoints from a child fork.
3691    When we get here, the child isn't in the inferior list, and neither
3692    do we have objects to represent its address space --- we should
3693    *not* look at bl->pspace->aspace here.  */
3694
3695 static int
3696 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3697 {
3698   int val;
3699
3700   /* BL is never in moribund_locations by our callers.  */
3701   gdb_assert (bl->owner != NULL);
3702
3703   /* The type of none suggests that owner is actually deleted.
3704      This should not ever happen.  */
3705   gdb_assert (bl->owner->type != bp_none);
3706
3707   if (bl->loc_type == bp_loc_software_breakpoint
3708       || bl->loc_type == bp_loc_hardware_breakpoint)
3709     {
3710       /* "Normal" instruction breakpoint: either the standard
3711          trap-instruction bp (bp_breakpoint), or a
3712          bp_hardware_breakpoint.  */
3713
3714       /* First check to see if we have to handle an overlay.  */
3715       if (overlay_debugging == ovly_off
3716           || bl->section == NULL
3717           || !(section_is_overlay (bl->section)))
3718         {
3719           /* No overlay handling: just remove the breakpoint.  */
3720
3721           /* If we're trying to uninsert a memory breakpoint that we
3722              know is set in a dynamic object that is marked
3723              shlib_disabled, then either the dynamic object was
3724              removed with "remove-symbol-file" or with
3725              "nosharedlibrary".  In the former case, we don't know
3726              whether another dynamic object might have loaded over the
3727              breakpoint's address -- the user might well let us know
3728              about it next with add-symbol-file (the whole point of
3729              add-symbol-file is letting the user manually maintain a
3730              list of dynamically loaded objects).  If we have the
3731              breakpoint's shadow memory, that is, this is a software
3732              breakpoint managed by GDB, check whether the breakpoint
3733              is still inserted in memory, to avoid overwriting wrong
3734              code with stale saved shadow contents.  Note that HW
3735              breakpoints don't have shadow memory, as they're
3736              implemented using a mechanism that is not dependent on
3737              being able to modify the target's memory, and as such
3738              they should always be removed.  */
3739           if (bl->shlib_disabled
3740               && bl->target_info.shadow_len != 0
3741               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3742             val = 0;
3743           else
3744             val = bl->owner->ops->remove_location (bl, reason);
3745         }
3746       else
3747         {
3748           /* This breakpoint is in an overlay section.
3749              Did we set a breakpoint at the LMA?  */
3750           if (!overlay_events_enabled)
3751               {
3752                 /* Yes -- overlay event support is not active, so we
3753                    should have set a breakpoint at the LMA.  Remove it.  
3754                 */
3755                 /* Ignore any failures: if the LMA is in ROM, we will
3756                    have already warned when we failed to insert it.  */
3757                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3758                   target_remove_hw_breakpoint (bl->gdbarch,
3759                                                &bl->overlay_target_info);
3760                 else
3761                   target_remove_breakpoint (bl->gdbarch,
3762                                             &bl->overlay_target_info,
3763                                             reason);
3764               }
3765           /* Did we set a breakpoint at the VMA? 
3766              If so, we will have marked the breakpoint 'inserted'.  */
3767           if (bl->inserted)
3768             {
3769               /* Yes -- remove it.  Previously we did not bother to
3770                  remove the breakpoint if the section had been
3771                  unmapped, but let's not rely on that being safe.  We
3772                  don't know what the overlay manager might do.  */
3773
3774               /* However, we should remove *software* breakpoints only
3775                  if the section is still mapped, or else we overwrite
3776                  wrong code with the saved shadow contents.  */
3777               if (bl->loc_type == bp_loc_hardware_breakpoint
3778                   || section_is_mapped (bl->section))
3779                 val = bl->owner->ops->remove_location (bl, reason);
3780               else
3781                 val = 0;
3782             }
3783           else
3784             {
3785               /* No -- not inserted, so no need to remove.  No error.  */
3786               val = 0;
3787             }
3788         }
3789
3790       /* In some cases, we might not be able to remove a breakpoint in
3791          a shared library that has already been removed, but we have
3792          not yet processed the shlib unload event.  Similarly for an
3793          unloaded add-symbol-file object - the user might not yet have
3794          had the chance to remove-symbol-file it.  shlib_disabled will
3795          be set if the library/object has already been removed, but
3796          the breakpoint hasn't been uninserted yet, e.g., after
3797          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3798          always-inserted mode.  */
3799       if (val
3800           && (bl->loc_type == bp_loc_software_breakpoint
3801               && (bl->shlib_disabled
3802                   || solib_name_from_address (bl->pspace, bl->address)
3803                   || shared_objfile_contains_address_p (bl->pspace,
3804                                                         bl->address))))
3805         val = 0;
3806
3807       if (val)
3808         return val;
3809       bl->inserted = (reason == DETACH_BREAKPOINT);
3810     }
3811   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3812     {
3813       gdb_assert (bl->owner->ops != NULL
3814                   && bl->owner->ops->remove_location != NULL);
3815
3816       bl->inserted = (reason == DETACH_BREAKPOINT);
3817       bl->owner->ops->remove_location (bl, reason);
3818
3819       /* Failure to remove any of the hardware watchpoints comes here.  */
3820       if (reason == REMOVE_BREAKPOINT && bl->inserted)
3821         warning (_("Could not remove hardware watchpoint %d."),
3822                  bl->owner->number);
3823     }
3824   else if (bl->owner->type == bp_catchpoint
3825            && breakpoint_enabled (bl->owner)
3826            && !bl->duplicate)
3827     {
3828       gdb_assert (bl->owner->ops != NULL
3829                   && bl->owner->ops->remove_location != NULL);
3830
3831       val = bl->owner->ops->remove_location (bl, reason);
3832       if (val)
3833         return val;
3834
3835       bl->inserted = (reason == DETACH_BREAKPOINT);
3836     }
3837
3838   return 0;
3839 }
3840
3841 static int
3842 remove_breakpoint (struct bp_location *bl)
3843 {
3844   /* BL is never in moribund_locations by our callers.  */
3845   gdb_assert (bl->owner != NULL);
3846
3847   /* The type of none suggests that owner is actually deleted.
3848      This should not ever happen.  */
3849   gdb_assert (bl->owner->type != bp_none);
3850
3851   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3852
3853   switch_to_program_space_and_thread (bl->pspace);
3854
3855   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
3856 }
3857
3858 /* Clear the "inserted" flag in all breakpoints.  */
3859
3860 void
3861 mark_breakpoints_out (void)
3862 {
3863   struct bp_location *bl, **blp_tmp;
3864
3865   ALL_BP_LOCATIONS (bl, blp_tmp)
3866     if (bl->pspace == current_program_space)
3867       bl->inserted = 0;
3868 }
3869
3870 /* Clear the "inserted" flag in all breakpoints and delete any
3871    breakpoints which should go away between runs of the program.
3872
3873    Plus other such housekeeping that has to be done for breakpoints
3874    between runs.
3875
3876    Note: this function gets called at the end of a run (by
3877    generic_mourn_inferior) and when a run begins (by
3878    init_wait_for_inferior).  */
3879
3880
3881
3882 void
3883 breakpoint_init_inferior (enum inf_context context)
3884 {
3885   struct breakpoint *b, *b_tmp;
3886   struct bp_location *bl;
3887   int ix;
3888   struct program_space *pspace = current_program_space;
3889
3890   /* If breakpoint locations are shared across processes, then there's
3891      nothing to do.  */
3892   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3893     return;
3894
3895   mark_breakpoints_out ();
3896
3897   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3898   {
3899     if (b->loc && b->loc->pspace != pspace)
3900       continue;
3901
3902     switch (b->type)
3903       {
3904       case bp_call_dummy:
3905       case bp_longjmp_call_dummy:
3906
3907         /* If the call dummy breakpoint is at the entry point it will
3908            cause problems when the inferior is rerun, so we better get
3909            rid of it.  */
3910
3911       case bp_watchpoint_scope:
3912
3913         /* Also get rid of scope breakpoints.  */
3914
3915       case bp_shlib_event:
3916
3917         /* Also remove solib event breakpoints.  Their addresses may
3918            have changed since the last time we ran the program.
3919            Actually we may now be debugging against different target;
3920            and so the solib backend that installed this breakpoint may
3921            not be used in by the target.  E.g.,
3922
3923            (gdb) file prog-linux
3924            (gdb) run               # native linux target
3925            ...
3926            (gdb) kill
3927            (gdb) file prog-win.exe
3928            (gdb) tar rem :9999     # remote Windows gdbserver.
3929         */
3930
3931       case bp_step_resume:
3932
3933         /* Also remove step-resume breakpoints.  */
3934
3935       case bp_single_step:
3936
3937         /* Also remove single-step breakpoints.  */
3938
3939         delete_breakpoint (b);
3940         break;
3941
3942       case bp_watchpoint:
3943       case bp_hardware_watchpoint:
3944       case bp_read_watchpoint:
3945       case bp_access_watchpoint:
3946         {
3947           struct watchpoint *w = (struct watchpoint *) b;
3948
3949           /* Likewise for watchpoints on local expressions.  */
3950           if (w->exp_valid_block != NULL)
3951             delete_breakpoint (b);
3952           else
3953             {
3954               /* Get rid of existing locations, which are no longer
3955                  valid.  New ones will be created in
3956                  update_watchpoint, when the inferior is restarted.
3957                  The next update_global_location_list call will
3958                  garbage collect them.  */
3959               b->loc = NULL;
3960
3961               if (context == inf_starting)
3962                 {
3963                   /* Reset val field to force reread of starting value in
3964                      insert_breakpoints.  */
3965                   if (w->val)
3966                     value_free (w->val);
3967                   w->val = NULL;
3968                   w->val_valid = 0;
3969                 }
3970             }
3971         }
3972         break;
3973       default:
3974         break;
3975       }
3976   }
3977
3978   /* Get rid of the moribund locations.  */
3979   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3980     decref_bp_location (&bl);
3981   VEC_free (bp_location_p, moribund_locations);
3982 }
3983
3984 /* These functions concern about actual breakpoints inserted in the
3985    target --- to e.g. check if we need to do decr_pc adjustment or if
3986    we need to hop over the bkpt --- so we check for address space
3987    match, not program space.  */
3988
3989 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3990    exists at PC.  It returns ordinary_breakpoint_here if it's an
3991    ordinary breakpoint, or permanent_breakpoint_here if it's a
3992    permanent breakpoint.
3993    - When continuing from a location with an ordinary breakpoint, we
3994      actually single step once before calling insert_breakpoints.
3995    - When continuing from a location with a permanent breakpoint, we
3996      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3997      the target, to advance the PC past the breakpoint.  */
3998
3999 enum breakpoint_here
4000 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4001 {
4002   struct bp_location *bl, **blp_tmp;
4003   int any_breakpoint_here = 0;
4004
4005   ALL_BP_LOCATIONS (bl, blp_tmp)
4006     {
4007       if (bl->loc_type != bp_loc_software_breakpoint
4008           && bl->loc_type != bp_loc_hardware_breakpoint)
4009         continue;
4010
4011       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4012       if ((breakpoint_enabled (bl->owner)
4013            || bl->permanent)
4014           && breakpoint_location_address_match (bl, aspace, pc))
4015         {
4016           if (overlay_debugging 
4017               && section_is_overlay (bl->section)
4018               && !section_is_mapped (bl->section))
4019             continue;           /* unmapped overlay -- can't be a match */
4020           else if (bl->permanent)
4021             return permanent_breakpoint_here;
4022           else
4023             any_breakpoint_here = 1;
4024         }
4025     }
4026
4027   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4028 }
4029
4030 /* See breakpoint.h.  */
4031
4032 int
4033 breakpoint_in_range_p (const address_space *aspace,
4034                        CORE_ADDR addr, ULONGEST len)
4035 {
4036   struct bp_location *bl, **blp_tmp;
4037
4038   ALL_BP_LOCATIONS (bl, blp_tmp)
4039     {
4040       if (bl->loc_type != bp_loc_software_breakpoint
4041           && bl->loc_type != bp_loc_hardware_breakpoint)
4042         continue;
4043
4044       if ((breakpoint_enabled (bl->owner)
4045            || bl->permanent)
4046           && breakpoint_location_address_range_overlap (bl, aspace,
4047                                                         addr, len))
4048         {
4049           if (overlay_debugging
4050               && section_is_overlay (bl->section)
4051               && !section_is_mapped (bl->section))
4052             {
4053               /* Unmapped overlay -- can't be a match.  */
4054               continue;
4055             }
4056
4057           return 1;
4058         }
4059     }
4060
4061   return 0;
4062 }
4063
4064 /* Return true if there's a moribund breakpoint at PC.  */
4065
4066 int
4067 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4068 {
4069   struct bp_location *loc;
4070   int ix;
4071
4072   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4073     if (breakpoint_location_address_match (loc, aspace, pc))
4074       return 1;
4075
4076   return 0;
4077 }
4078
4079 /* Returns non-zero iff BL is inserted at PC, in address space
4080    ASPACE.  */
4081
4082 static int
4083 bp_location_inserted_here_p (struct bp_location *bl,
4084                              const address_space *aspace, CORE_ADDR pc)
4085 {
4086   if (bl->inserted
4087       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4088                                    aspace, pc))
4089     {
4090       if (overlay_debugging
4091           && section_is_overlay (bl->section)
4092           && !section_is_mapped (bl->section))
4093         return 0;               /* unmapped overlay -- can't be a match */
4094       else
4095         return 1;
4096     }
4097   return 0;
4098 }
4099
4100 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4101
4102 int
4103 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4104 {
4105   struct bp_location **blp, **blp_tmp = NULL;
4106
4107   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4108     {
4109       struct bp_location *bl = *blp;
4110
4111       if (bl->loc_type != bp_loc_software_breakpoint
4112           && bl->loc_type != bp_loc_hardware_breakpoint)
4113         continue;
4114
4115       if (bp_location_inserted_here_p (bl, aspace, pc))
4116         return 1;
4117     }
4118   return 0;
4119 }
4120
4121 /* This function returns non-zero iff there is a software breakpoint
4122    inserted at PC.  */
4123
4124 int
4125 software_breakpoint_inserted_here_p (const address_space *aspace,
4126                                      CORE_ADDR pc)
4127 {
4128   struct bp_location **blp, **blp_tmp = NULL;
4129
4130   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4131     {
4132       struct bp_location *bl = *blp;
4133
4134       if (bl->loc_type != bp_loc_software_breakpoint)
4135         continue;
4136
4137       if (bp_location_inserted_here_p (bl, aspace, pc))
4138         return 1;
4139     }
4140
4141   return 0;
4142 }
4143
4144 /* See breakpoint.h.  */
4145
4146 int
4147 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4148                                      CORE_ADDR pc)
4149 {
4150   struct bp_location **blp, **blp_tmp = NULL;
4151
4152   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4153     {
4154       struct bp_location *bl = *blp;
4155
4156       if (bl->loc_type != bp_loc_hardware_breakpoint)
4157         continue;
4158
4159       if (bp_location_inserted_here_p (bl, aspace, pc))
4160         return 1;
4161     }
4162
4163   return 0;
4164 }
4165
4166 int
4167 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4168                                        CORE_ADDR addr, ULONGEST len)
4169 {
4170   struct breakpoint *bpt;
4171
4172   ALL_BREAKPOINTS (bpt)
4173     {
4174       struct bp_location *loc;
4175
4176       if (bpt->type != bp_hardware_watchpoint
4177           && bpt->type != bp_access_watchpoint)
4178         continue;
4179
4180       if (!breakpoint_enabled (bpt))
4181         continue;
4182
4183       for (loc = bpt->loc; loc; loc = loc->next)
4184         if (loc->pspace->aspace == aspace && loc->inserted)
4185           {
4186             CORE_ADDR l, h;
4187
4188             /* Check for intersection.  */
4189             l = std::max<CORE_ADDR> (loc->address, addr);
4190             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4191             if (l < h)
4192               return 1;
4193           }
4194     }
4195   return 0;
4196 }
4197 \f
4198
4199 /* bpstat stuff.  External routines' interfaces are documented
4200    in breakpoint.h.  */
4201
4202 int
4203 is_catchpoint (struct breakpoint *ep)
4204 {
4205   return (ep->type == bp_catchpoint);
4206 }
4207
4208 /* Frees any storage that is part of a bpstat.  Does not walk the
4209    'next' chain.  */
4210
4211 bpstats::~bpstats ()
4212 {
4213   if (old_val != NULL)
4214     value_free (old_val);
4215   if (bp_location_at != NULL)
4216     decref_bp_location (&bp_location_at);
4217 }
4218
4219 /* Clear a bpstat so that it says we are not at any breakpoint.
4220    Also free any storage that is part of a bpstat.  */
4221
4222 void
4223 bpstat_clear (bpstat *bsp)
4224 {
4225   bpstat p;
4226   bpstat q;
4227
4228   if (bsp == 0)
4229     return;
4230   p = *bsp;
4231   while (p != NULL)
4232     {
4233       q = p->next;
4234       delete p;
4235       p = q;
4236     }
4237   *bsp = NULL;
4238 }
4239
4240 bpstats::bpstats (const bpstats &other)
4241   : next (NULL),
4242     bp_location_at (other.bp_location_at),
4243     breakpoint_at (other.breakpoint_at),
4244     commands (other.commands),
4245     old_val (other.old_val),
4246     print (other.print),
4247     stop (other.stop),
4248     print_it (other.print_it)
4249 {
4250   if (old_val != NULL)
4251     {
4252       old_val = value_copy (old_val);
4253       release_value (old_val);
4254     }
4255   incref_bp_location (bp_location_at);
4256 }
4257
4258 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4259    is part of the bpstat is copied as well.  */
4260
4261 bpstat
4262 bpstat_copy (bpstat bs)
4263 {
4264   bpstat p = NULL;
4265   bpstat tmp;
4266   bpstat retval = NULL;
4267
4268   if (bs == NULL)
4269     return bs;
4270
4271   for (; bs != NULL; bs = bs->next)
4272     {
4273       tmp = new bpstats (*bs);
4274
4275       if (p == NULL)
4276         /* This is the first thing in the chain.  */
4277         retval = tmp;
4278       else
4279         p->next = tmp;
4280       p = tmp;
4281     }
4282   p->next = NULL;
4283   return retval;
4284 }
4285
4286 /* Find the bpstat associated with this breakpoint.  */
4287
4288 bpstat
4289 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4290 {
4291   if (bsp == NULL)
4292     return NULL;
4293
4294   for (; bsp != NULL; bsp = bsp->next)
4295     {
4296       if (bsp->breakpoint_at == breakpoint)
4297         return bsp;
4298     }
4299   return NULL;
4300 }
4301
4302 /* See breakpoint.h.  */
4303
4304 int
4305 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4306 {
4307   for (; bsp != NULL; bsp = bsp->next)
4308     {
4309       if (bsp->breakpoint_at == NULL)
4310         {
4311           /* A moribund location can never explain a signal other than
4312              GDB_SIGNAL_TRAP.  */
4313           if (sig == GDB_SIGNAL_TRAP)
4314             return 1;
4315         }
4316       else
4317         {
4318           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4319                                                         sig))
4320             return 1;
4321         }
4322     }
4323
4324   return 0;
4325 }
4326
4327 /* Put in *NUM the breakpoint number of the first breakpoint we are
4328    stopped at.  *BSP upon return is a bpstat which points to the
4329    remaining breakpoints stopped at (but which is not guaranteed to be
4330    good for anything but further calls to bpstat_num).
4331
4332    Return 0 if passed a bpstat which does not indicate any breakpoints.
4333    Return -1 if stopped at a breakpoint that has been deleted since
4334    we set it.
4335    Return 1 otherwise.  */
4336
4337 int
4338 bpstat_num (bpstat *bsp, int *num)
4339 {
4340   struct breakpoint *b;
4341
4342   if ((*bsp) == NULL)
4343     return 0;                   /* No more breakpoint values */
4344
4345   /* We assume we'll never have several bpstats that correspond to a
4346      single breakpoint -- otherwise, this function might return the
4347      same number more than once and this will look ugly.  */
4348   b = (*bsp)->breakpoint_at;
4349   *bsp = (*bsp)->next;
4350   if (b == NULL)
4351     return -1;                  /* breakpoint that's been deleted since */
4352
4353   *num = b->number;             /* We have its number */
4354   return 1;
4355 }
4356
4357 /* See breakpoint.h.  */
4358
4359 void
4360 bpstat_clear_actions (void)
4361 {
4362   struct thread_info *tp;
4363   bpstat bs;
4364
4365   if (ptid_equal (inferior_ptid, null_ptid))
4366     return;
4367
4368   tp = find_thread_ptid (inferior_ptid);
4369   if (tp == NULL)
4370     return;
4371
4372   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4373     {
4374       bs->commands = NULL;
4375
4376       if (bs->old_val != NULL)
4377         {
4378           value_free (bs->old_val);
4379           bs->old_val = NULL;
4380         }
4381     }
4382 }
4383
4384 /* Called when a command is about to proceed the inferior.  */
4385
4386 static void
4387 breakpoint_about_to_proceed (void)
4388 {
4389   if (!ptid_equal (inferior_ptid, null_ptid))
4390     {
4391       struct thread_info *tp = inferior_thread ();
4392
4393       /* Allow inferior function calls in breakpoint commands to not
4394          interrupt the command list.  When the call finishes
4395          successfully, the inferior will be standing at the same
4396          breakpoint as if nothing happened.  */
4397       if (tp->control.in_infcall)
4398         return;
4399     }
4400
4401   breakpoint_proceeded = 1;
4402 }
4403
4404 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4405    or its equivalent.  */
4406
4407 static int
4408 command_line_is_silent (struct command_line *cmd)
4409 {
4410   return cmd && (strcmp ("silent", cmd->line) == 0);
4411 }
4412
4413 /* Execute all the commands associated with all the breakpoints at
4414    this location.  Any of these commands could cause the process to
4415    proceed beyond this point, etc.  We look out for such changes by
4416    checking the global "breakpoint_proceeded" after each command.
4417
4418    Returns true if a breakpoint command resumed the inferior.  In that
4419    case, it is the caller's responsibility to recall it again with the
4420    bpstat of the current thread.  */
4421
4422 static int
4423 bpstat_do_actions_1 (bpstat *bsp)
4424 {
4425   bpstat bs;
4426   int again = 0;
4427
4428   /* Avoid endless recursion if a `source' command is contained
4429      in bs->commands.  */
4430   if (executing_breakpoint_commands)
4431     return 0;
4432
4433   scoped_restore save_executing
4434     = make_scoped_restore (&executing_breakpoint_commands, 1);
4435
4436   scoped_restore preventer = prevent_dont_repeat ();
4437
4438   /* This pointer will iterate over the list of bpstat's.  */
4439   bs = *bsp;
4440
4441   breakpoint_proceeded = 0;
4442   for (; bs != NULL; bs = bs->next)
4443     {
4444       struct command_line *cmd = NULL;
4445
4446       /* Take ownership of the BSP's command tree, if it has one.
4447
4448          The command tree could legitimately contain commands like
4449          'step' and 'next', which call clear_proceed_status, which
4450          frees stop_bpstat's command tree.  To make sure this doesn't
4451          free the tree we're executing out from under us, we need to
4452          take ownership of the tree ourselves.  Since a given bpstat's
4453          commands are only executed once, we don't need to copy it; we
4454          can clear the pointer in the bpstat, and make sure we free
4455          the tree when we're done.  */
4456       counted_command_line ccmd = bs->commands;
4457       bs->commands = NULL;
4458       if (ccmd != NULL)
4459         cmd = ccmd.get ();
4460       if (command_line_is_silent (cmd))
4461         {
4462           /* The action has been already done by bpstat_stop_status.  */
4463           cmd = cmd->next;
4464         }
4465
4466       while (cmd != NULL)
4467         {
4468           execute_control_command (cmd);
4469
4470           if (breakpoint_proceeded)
4471             break;
4472           else
4473             cmd = cmd->next;
4474         }
4475
4476       if (breakpoint_proceeded)
4477         {
4478           if (current_ui->async)
4479             /* If we are in async mode, then the target might be still
4480                running, not stopped at any breakpoint, so nothing for
4481                us to do here -- just return to the event loop.  */
4482             ;
4483           else
4484             /* In sync mode, when execute_control_command returns
4485                we're already standing on the next breakpoint.
4486                Breakpoint commands for that stop were not run, since
4487                execute_command does not run breakpoint commands --
4488                only command_line_handler does, but that one is not
4489                involved in execution of breakpoint commands.  So, we
4490                can now execute breakpoint commands.  It should be
4491                noted that making execute_command do bpstat actions is
4492                not an option -- in this case we'll have recursive
4493                invocation of bpstat for each breakpoint with a
4494                command, and can easily blow up GDB stack.  Instead, we
4495                return true, which will trigger the caller to recall us
4496                with the new stop_bpstat.  */
4497             again = 1;
4498           break;
4499         }
4500     }
4501   return again;
4502 }
4503
4504 void
4505 bpstat_do_actions (void)
4506 {
4507   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4508
4509   /* Do any commands attached to breakpoint we are stopped at.  */
4510   while (!ptid_equal (inferior_ptid, null_ptid)
4511          && target_has_execution
4512          && !is_exited (inferior_ptid)
4513          && !is_executing (inferior_ptid))
4514     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4515        and only return when it is stopped at the next breakpoint, we
4516        keep doing breakpoint actions until it returns false to
4517        indicate the inferior was not resumed.  */
4518     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4519       break;
4520
4521   discard_cleanups (cleanup_if_error);
4522 }
4523
4524 /* Print out the (old or new) value associated with a watchpoint.  */
4525
4526 static void
4527 watchpoint_value_print (struct value *val, struct ui_file *stream)
4528 {
4529   if (val == NULL)
4530     fprintf_unfiltered (stream, _("<unreadable>"));
4531   else
4532     {
4533       struct value_print_options opts;
4534       get_user_print_options (&opts);
4535       value_print (val, stream, &opts);
4536     }
4537 }
4538
4539 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4540    debugging multiple threads.  */
4541
4542 void
4543 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4544 {
4545   if (uiout->is_mi_like_p ())
4546     return;
4547
4548   uiout->text ("\n");
4549
4550   if (show_thread_that_caused_stop ())
4551     {
4552       const char *name;
4553       struct thread_info *thr = inferior_thread ();
4554
4555       uiout->text ("Thread ");
4556       uiout->field_fmt ("thread-id", "%s", print_thread_id (thr));
4557
4558       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4559       if (name != NULL)
4560         {
4561           uiout->text (" \"");
4562           uiout->field_fmt ("name", "%s", name);
4563           uiout->text ("\"");
4564         }
4565
4566       uiout->text (" hit ");
4567     }
4568 }
4569
4570 /* Generic routine for printing messages indicating why we
4571    stopped.  The behavior of this function depends on the value
4572    'print_it' in the bpstat structure.  Under some circumstances we
4573    may decide not to print anything here and delegate the task to
4574    normal_stop().  */
4575
4576 static enum print_stop_action
4577 print_bp_stop_message (bpstat bs)
4578 {
4579   switch (bs->print_it)
4580     {
4581     case print_it_noop:
4582       /* Nothing should be printed for this bpstat entry.  */
4583       return PRINT_UNKNOWN;
4584       break;
4585
4586     case print_it_done:
4587       /* We still want to print the frame, but we already printed the
4588          relevant messages.  */
4589       return PRINT_SRC_AND_LOC;
4590       break;
4591
4592     case print_it_normal:
4593       {
4594         struct breakpoint *b = bs->breakpoint_at;
4595
4596         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4597            which has since been deleted.  */
4598         if (b == NULL)
4599           return PRINT_UNKNOWN;
4600
4601         /* Normal case.  Call the breakpoint's print_it method.  */
4602         return b->ops->print_it (bs);
4603       }
4604       break;
4605
4606     default:
4607       internal_error (__FILE__, __LINE__,
4608                       _("print_bp_stop_message: unrecognized enum value"));
4609       break;
4610     }
4611 }
4612
4613 /* A helper function that prints a shared library stopped event.  */
4614
4615 static void
4616 print_solib_event (int is_catchpoint)
4617 {
4618   int any_deleted
4619     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4620   int any_added
4621     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4622
4623   if (!is_catchpoint)
4624     {
4625       if (any_added || any_deleted)
4626         current_uiout->text (_("Stopped due to shared library event:\n"));
4627       else
4628         current_uiout->text (_("Stopped due to shared library event (no "
4629                                "libraries added or removed)\n"));
4630     }
4631
4632   if (current_uiout->is_mi_like_p ())
4633     current_uiout->field_string ("reason",
4634                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4635
4636   if (any_deleted)
4637     {
4638       char *name;
4639       int ix;
4640
4641       current_uiout->text (_("  Inferior unloaded "));
4642       ui_out_emit_list list_emitter (current_uiout, "removed");
4643       for (ix = 0;
4644            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4645                         ix, name);
4646            ++ix)
4647         {
4648           if (ix > 0)
4649             current_uiout->text ("    ");
4650           current_uiout->field_string ("library", name);
4651           current_uiout->text ("\n");
4652         }
4653     }
4654
4655   if (any_added)
4656     {
4657       struct so_list *iter;
4658       int ix;
4659
4660       current_uiout->text (_("  Inferior loaded "));
4661       ui_out_emit_list list_emitter (current_uiout, "added");
4662       for (ix = 0;
4663            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4664                         ix, iter);
4665            ++ix)
4666         {
4667           if (ix > 0)
4668             current_uiout->text ("    ");
4669           current_uiout->field_string ("library", iter->so_name);
4670           current_uiout->text ("\n");
4671         }
4672     }
4673 }
4674
4675 /* Print a message indicating what happened.  This is called from
4676    normal_stop().  The input to this routine is the head of the bpstat
4677    list - a list of the eventpoints that caused this stop.  KIND is
4678    the target_waitkind for the stopping event.  This
4679    routine calls the generic print routine for printing a message
4680    about reasons for stopping.  This will print (for example) the
4681    "Breakpoint n," part of the output.  The return value of this
4682    routine is one of:
4683
4684    PRINT_UNKNOWN: Means we printed nothing.
4685    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4686    code to print the location.  An example is 
4687    "Breakpoint 1, " which should be followed by
4688    the location.
4689    PRINT_SRC_ONLY: Means we printed something, but there is no need
4690    to also print the location part of the message.
4691    An example is the catch/throw messages, which
4692    don't require a location appended to the end.
4693    PRINT_NOTHING: We have done some printing and we don't need any 
4694    further info to be printed.  */
4695
4696 enum print_stop_action
4697 bpstat_print (bpstat bs, int kind)
4698 {
4699   enum print_stop_action val;
4700
4701   /* Maybe another breakpoint in the chain caused us to stop.
4702      (Currently all watchpoints go on the bpstat whether hit or not.
4703      That probably could (should) be changed, provided care is taken
4704      with respect to bpstat_explains_signal).  */
4705   for (; bs; bs = bs->next)
4706     {
4707       val = print_bp_stop_message (bs);
4708       if (val == PRINT_SRC_ONLY 
4709           || val == PRINT_SRC_AND_LOC 
4710           || val == PRINT_NOTHING)
4711         return val;
4712     }
4713
4714   /* If we had hit a shared library event breakpoint,
4715      print_bp_stop_message would print out this message.  If we hit an
4716      OS-level shared library event, do the same thing.  */
4717   if (kind == TARGET_WAITKIND_LOADED)
4718     {
4719       print_solib_event (0);
4720       return PRINT_NOTHING;
4721     }
4722
4723   /* We reached the end of the chain, or we got a null BS to start
4724      with and nothing was printed.  */
4725   return PRINT_UNKNOWN;
4726 }
4727
4728 /* Evaluate the boolean expression EXP and return the result.  */
4729
4730 static bool
4731 breakpoint_cond_eval (expression *exp)
4732 {
4733   struct value *mark = value_mark ();
4734   bool res = value_true (evaluate_expression (exp));
4735
4736   value_free_to_mark (mark);
4737   return res;
4738 }
4739
4740 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4741
4742 bpstats::bpstats (struct bp_location *bl, bpstat **bs_link_pointer)
4743   : next (NULL),
4744     bp_location_at (bl),
4745     breakpoint_at (bl->owner),
4746     commands (NULL),
4747     old_val (NULL),
4748     print (0),
4749     stop (0),
4750     print_it (print_it_normal)
4751 {
4752   incref_bp_location (bl);
4753   **bs_link_pointer = this;
4754   *bs_link_pointer = &next;
4755 }
4756
4757 bpstats::bpstats ()
4758   : next (NULL),
4759     bp_location_at (NULL),
4760     breakpoint_at (NULL),
4761     commands (NULL),
4762     old_val (NULL),
4763     print (0),
4764     stop (0),
4765     print_it (print_it_normal)
4766 {
4767 }
4768 \f
4769 /* The target has stopped with waitstatus WS.  Check if any hardware
4770    watchpoints have triggered, according to the target.  */
4771
4772 int
4773 watchpoints_triggered (struct target_waitstatus *ws)
4774 {
4775   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4776   CORE_ADDR addr;
4777   struct breakpoint *b;
4778
4779   if (!stopped_by_watchpoint)
4780     {
4781       /* We were not stopped by a watchpoint.  Mark all watchpoints
4782          as not triggered.  */
4783       ALL_BREAKPOINTS (b)
4784         if (is_hardware_watchpoint (b))
4785           {
4786             struct watchpoint *w = (struct watchpoint *) b;
4787
4788             w->watchpoint_triggered = watch_triggered_no;
4789           }
4790
4791       return 0;
4792     }
4793
4794   if (!target_stopped_data_address (&current_target, &addr))
4795     {
4796       /* We were stopped by a watchpoint, but we don't know where.
4797          Mark all watchpoints as unknown.  */
4798       ALL_BREAKPOINTS (b)
4799         if (is_hardware_watchpoint (b))
4800           {
4801             struct watchpoint *w = (struct watchpoint *) b;
4802
4803             w->watchpoint_triggered = watch_triggered_unknown;
4804           }
4805
4806       return 1;
4807     }
4808
4809   /* The target could report the data address.  Mark watchpoints
4810      affected by this data address as triggered, and all others as not
4811      triggered.  */
4812
4813   ALL_BREAKPOINTS (b)
4814     if (is_hardware_watchpoint (b))
4815       {
4816         struct watchpoint *w = (struct watchpoint *) b;
4817         struct bp_location *loc;
4818
4819         w->watchpoint_triggered = watch_triggered_no;
4820         for (loc = b->loc; loc; loc = loc->next)
4821           {
4822             if (is_masked_watchpoint (b))
4823               {
4824                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4825                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4826
4827                 if (newaddr == start)
4828                   {
4829                     w->watchpoint_triggered = watch_triggered_yes;
4830                     break;
4831                   }
4832               }
4833             /* Exact match not required.  Within range is sufficient.  */
4834             else if (target_watchpoint_addr_within_range (&current_target,
4835                                                          addr, loc->address,
4836                                                          loc->length))
4837               {
4838                 w->watchpoint_triggered = watch_triggered_yes;
4839                 break;
4840               }
4841           }
4842       }
4843
4844   return 1;
4845 }
4846
4847 /* Possible return values for watchpoint_check.  */
4848 enum wp_check_result
4849   {
4850     /* The watchpoint has been deleted.  */
4851     WP_DELETED = 1,
4852
4853     /* The value has changed.  */
4854     WP_VALUE_CHANGED = 2,
4855
4856     /* The value has not changed.  */
4857     WP_VALUE_NOT_CHANGED = 3,
4858
4859     /* Ignore this watchpoint, no matter if the value changed or not.  */
4860     WP_IGNORE = 4,
4861   };
4862
4863 #define BP_TEMPFLAG 1
4864 #define BP_HARDWAREFLAG 2
4865
4866 /* Evaluate watchpoint condition expression and check if its value
4867    changed.  */
4868
4869 static wp_check_result
4870 watchpoint_check (bpstat bs)
4871 {
4872   struct watchpoint *b;
4873   struct frame_info *fr;
4874   int within_current_scope;
4875
4876   /* BS is built from an existing struct breakpoint.  */
4877   gdb_assert (bs->breakpoint_at != NULL);
4878   b = (struct watchpoint *) bs->breakpoint_at;
4879
4880   /* If this is a local watchpoint, we only want to check if the
4881      watchpoint frame is in scope if the current thread is the thread
4882      that was used to create the watchpoint.  */
4883   if (!watchpoint_in_thread_scope (b))
4884     return WP_IGNORE;
4885
4886   if (b->exp_valid_block == NULL)
4887     within_current_scope = 1;
4888   else
4889     {
4890       struct frame_info *frame = get_current_frame ();
4891       struct gdbarch *frame_arch = get_frame_arch (frame);
4892       CORE_ADDR frame_pc = get_frame_pc (frame);
4893
4894       /* stack_frame_destroyed_p() returns a non-zero value if we're
4895          still in the function but the stack frame has already been
4896          invalidated.  Since we can't rely on the values of local
4897          variables after the stack has been destroyed, we are treating
4898          the watchpoint in that state as `not changed' without further
4899          checking.  Don't mark watchpoints as changed if the current
4900          frame is in an epilogue - even if they are in some other
4901          frame, our view of the stack is likely to be wrong and
4902          frame_find_by_id could error out.  */
4903       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
4904         return WP_IGNORE;
4905
4906       fr = frame_find_by_id (b->watchpoint_frame);
4907       within_current_scope = (fr != NULL);
4908
4909       /* If we've gotten confused in the unwinder, we might have
4910          returned a frame that can't describe this variable.  */
4911       if (within_current_scope)
4912         {
4913           struct symbol *function;
4914
4915           function = get_frame_function (fr);
4916           if (function == NULL
4917               || !contained_in (b->exp_valid_block,
4918                                 SYMBOL_BLOCK_VALUE (function)))
4919             within_current_scope = 0;
4920         }
4921
4922       if (within_current_scope)
4923         /* If we end up stopping, the current frame will get selected
4924            in normal_stop.  So this call to select_frame won't affect
4925            the user.  */
4926         select_frame (fr);
4927     }
4928
4929   if (within_current_scope)
4930     {
4931       /* We use value_{,free_to_}mark because it could be a *long*
4932          time before we return to the command level and call
4933          free_all_values.  We can't call free_all_values because we
4934          might be in the middle of evaluating a function call.  */
4935
4936       int pc = 0;
4937       struct value *mark;
4938       struct value *new_val;
4939
4940       if (is_masked_watchpoint (b))
4941         /* Since we don't know the exact trigger address (from
4942            stopped_data_address), just tell the user we've triggered
4943            a mask watchpoint.  */
4944         return WP_VALUE_CHANGED;
4945
4946       mark = value_mark ();
4947       fetch_subexp_value (b->exp.get (), &pc, &new_val, NULL, NULL, 0);
4948
4949       if (b->val_bitsize != 0)
4950         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
4951
4952       /* We use value_equal_contents instead of value_equal because
4953          the latter coerces an array to a pointer, thus comparing just
4954          the address of the array instead of its contents.  This is
4955          not what we want.  */
4956       if ((b->val != NULL) != (new_val != NULL)
4957           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4958         {
4959           if (new_val != NULL)
4960             {
4961               release_value (new_val);
4962               value_free_to_mark (mark);
4963             }
4964           bs->old_val = b->val;
4965           b->val = new_val;
4966           b->val_valid = 1;
4967           return WP_VALUE_CHANGED;
4968         }
4969       else
4970         {
4971           /* Nothing changed.  */
4972           value_free_to_mark (mark);
4973           return WP_VALUE_NOT_CHANGED;
4974         }
4975     }
4976   else
4977     {
4978       /* This seems like the only logical thing to do because
4979          if we temporarily ignored the watchpoint, then when
4980          we reenter the block in which it is valid it contains
4981          garbage (in the case of a function, it may have two
4982          garbage values, one before and one after the prologue).
4983          So we can't even detect the first assignment to it and
4984          watch after that (since the garbage may or may not equal
4985          the first value assigned).  */
4986       /* We print all the stop information in
4987          breakpoint_ops->print_it, but in this case, by the time we
4988          call breakpoint_ops->print_it this bp will be deleted
4989          already.  So we have no choice but print the information
4990          here.  */
4991
4992       SWITCH_THRU_ALL_UIS ()
4993         {
4994           struct ui_out *uiout = current_uiout;
4995
4996           if (uiout->is_mi_like_p ())
4997             uiout->field_string
4998               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4999           uiout->text ("\nWatchpoint ");
5000           uiout->field_int ("wpnum", b->number);
5001           uiout->text (" deleted because the program has left the block in\n"
5002                        "which its expression is valid.\n");
5003         }
5004
5005       /* Make sure the watchpoint's commands aren't executed.  */
5006       b->commands = NULL;
5007       watchpoint_del_at_next_stop (b);
5008
5009       return WP_DELETED;
5010     }
5011 }
5012
5013 /* Return true if it looks like target has stopped due to hitting
5014    breakpoint location BL.  This function does not check if we should
5015    stop, only if BL explains the stop.  */
5016
5017 static int
5018 bpstat_check_location (const struct bp_location *bl,
5019                        const address_space *aspace, CORE_ADDR bp_addr,
5020                        const struct target_waitstatus *ws)
5021 {
5022   struct breakpoint *b = bl->owner;
5023
5024   /* BL is from an existing breakpoint.  */
5025   gdb_assert (b != NULL);
5026
5027   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5028 }
5029
5030 /* Determine if the watched values have actually changed, and we
5031    should stop.  If not, set BS->stop to 0.  */
5032
5033 static void
5034 bpstat_check_watchpoint (bpstat bs)
5035 {
5036   const struct bp_location *bl;
5037   struct watchpoint *b;
5038
5039   /* BS is built for existing struct breakpoint.  */
5040   bl = bs->bp_location_at;
5041   gdb_assert (bl != NULL);
5042   b = (struct watchpoint *) bs->breakpoint_at;
5043   gdb_assert (b != NULL);
5044
5045     {
5046       int must_check_value = 0;
5047       
5048       if (b->type == bp_watchpoint)
5049         /* For a software watchpoint, we must always check the
5050            watched value.  */
5051         must_check_value = 1;
5052       else if (b->watchpoint_triggered == watch_triggered_yes)
5053         /* We have a hardware watchpoint (read, write, or access)
5054            and the target earlier reported an address watched by
5055            this watchpoint.  */
5056         must_check_value = 1;
5057       else if (b->watchpoint_triggered == watch_triggered_unknown
5058                && b->type == bp_hardware_watchpoint)
5059         /* We were stopped by a hardware watchpoint, but the target could
5060            not report the data address.  We must check the watchpoint's
5061            value.  Access and read watchpoints are out of luck; without
5062            a data address, we can't figure it out.  */
5063         must_check_value = 1;
5064
5065       if (must_check_value)
5066         {
5067           wp_check_result e;
5068
5069           TRY
5070             {
5071               e = watchpoint_check (bs);
5072             }
5073           CATCH (ex, RETURN_MASK_ALL)
5074             {
5075               exception_fprintf (gdb_stderr, ex,
5076                                  "Error evaluating expression "
5077                                  "for watchpoint %d\n",
5078                                  b->number);
5079
5080               SWITCH_THRU_ALL_UIS ()
5081                 {
5082                   printf_filtered (_("Watchpoint %d deleted.\n"),
5083                                    b->number);
5084                 }
5085               watchpoint_del_at_next_stop (b);
5086               e = WP_DELETED;
5087             }
5088           END_CATCH
5089
5090           switch (e)
5091             {
5092             case WP_DELETED:
5093               /* We've already printed what needs to be printed.  */
5094               bs->print_it = print_it_done;
5095               /* Stop.  */
5096               break;
5097             case WP_IGNORE:
5098               bs->print_it = print_it_noop;
5099               bs->stop = 0;
5100               break;
5101             case WP_VALUE_CHANGED:
5102               if (b->type == bp_read_watchpoint)
5103                 {
5104                   /* There are two cases to consider here:
5105
5106                      1. We're watching the triggered memory for reads.
5107                      In that case, trust the target, and always report
5108                      the watchpoint hit to the user.  Even though
5109                      reads don't cause value changes, the value may
5110                      have changed since the last time it was read, and
5111                      since we're not trapping writes, we will not see
5112                      those, and as such we should ignore our notion of
5113                      old value.
5114
5115                      2. We're watching the triggered memory for both
5116                      reads and writes.  There are two ways this may
5117                      happen:
5118
5119                      2.1. This is a target that can't break on data
5120                      reads only, but can break on accesses (reads or
5121                      writes), such as e.g., x86.  We detect this case
5122                      at the time we try to insert read watchpoints.
5123
5124                      2.2. Otherwise, the target supports read
5125                      watchpoints, but, the user set an access or write
5126                      watchpoint watching the same memory as this read
5127                      watchpoint.
5128
5129                      If we're watching memory writes as well as reads,
5130                      ignore watchpoint hits when we find that the
5131                      value hasn't changed, as reads don't cause
5132                      changes.  This still gives false positives when
5133                      the program writes the same value to memory as
5134                      what there was already in memory (we will confuse
5135                      it for a read), but it's much better than
5136                      nothing.  */
5137
5138                   int other_write_watchpoint = 0;
5139
5140                   if (bl->watchpoint_type == hw_read)
5141                     {
5142                       struct breakpoint *other_b;
5143
5144                       ALL_BREAKPOINTS (other_b)
5145                         if (other_b->type == bp_hardware_watchpoint
5146                             || other_b->type == bp_access_watchpoint)
5147                           {
5148                             struct watchpoint *other_w =
5149                               (struct watchpoint *) other_b;
5150
5151                             if (other_w->watchpoint_triggered
5152                                 == watch_triggered_yes)
5153                               {
5154                                 other_write_watchpoint = 1;
5155                                 break;
5156                               }
5157                           }
5158                     }
5159
5160                   if (other_write_watchpoint
5161                       || bl->watchpoint_type == hw_access)
5162                     {
5163                       /* We're watching the same memory for writes,
5164                          and the value changed since the last time we
5165                          updated it, so this trap must be for a write.
5166                          Ignore it.  */
5167                       bs->print_it = print_it_noop;
5168                       bs->stop = 0;
5169                     }
5170                 }
5171               break;
5172             case WP_VALUE_NOT_CHANGED:
5173               if (b->type == bp_hardware_watchpoint
5174                   || b->type == bp_watchpoint)
5175                 {
5176                   /* Don't stop: write watchpoints shouldn't fire if
5177                      the value hasn't changed.  */
5178                   bs->print_it = print_it_noop;
5179                   bs->stop = 0;
5180                 }
5181               /* Stop.  */
5182               break;
5183             default:
5184               /* Can't happen.  */
5185               break;
5186             }
5187         }
5188       else      /* must_check_value == 0 */
5189         {
5190           /* This is a case where some watchpoint(s) triggered, but
5191              not at the address of this watchpoint, or else no
5192              watchpoint triggered after all.  So don't print
5193              anything for this watchpoint.  */
5194           bs->print_it = print_it_noop;
5195           bs->stop = 0;
5196         }
5197     }
5198 }
5199
5200 /* For breakpoints that are currently marked as telling gdb to stop,
5201    check conditions (condition proper, frame, thread and ignore count)
5202    of breakpoint referred to by BS.  If we should not stop for this
5203    breakpoint, set BS->stop to 0.  */
5204
5205 static void
5206 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5207 {
5208   const struct bp_location *bl;
5209   struct breakpoint *b;
5210   /* Assume stop.  */
5211   bool condition_result = true;
5212   struct expression *cond;
5213
5214   gdb_assert (bs->stop);
5215
5216   /* BS is built for existing struct breakpoint.  */
5217   bl = bs->bp_location_at;
5218   gdb_assert (bl != NULL);
5219   b = bs->breakpoint_at;
5220   gdb_assert (b != NULL);
5221
5222   /* Even if the target evaluated the condition on its end and notified GDB, we
5223      need to do so again since GDB does not know if we stopped due to a
5224      breakpoint or a single step breakpoint.  */
5225
5226   if (frame_id_p (b->frame_id)
5227       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5228     {
5229       bs->stop = 0;
5230       return;
5231     }
5232
5233   /* If this is a thread/task-specific breakpoint, don't waste cpu
5234      evaluating the condition if this isn't the specified
5235      thread/task.  */
5236   if ((b->thread != -1 && b->thread != ptid_to_global_thread_id (ptid))
5237       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5238
5239     {
5240       bs->stop = 0;
5241       return;
5242     }
5243
5244   /* Evaluate extension language breakpoints that have a "stop" method
5245      implemented.  */
5246   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5247
5248   if (is_watchpoint (b))
5249     {
5250       struct watchpoint *w = (struct watchpoint *) b;
5251
5252       cond = w->cond_exp.get ();
5253     }
5254   else
5255     cond = bl->cond.get ();
5256
5257   if (cond && b->disposition != disp_del_at_next_stop)
5258     {
5259       int within_current_scope = 1;
5260       struct watchpoint * w;
5261
5262       /* We use value_mark and value_free_to_mark because it could
5263          be a long time before we return to the command level and
5264          call free_all_values.  We can't call free_all_values
5265          because we might be in the middle of evaluating a
5266          function call.  */
5267       struct value *mark = value_mark ();
5268
5269       if (is_watchpoint (b))
5270         w = (struct watchpoint *) b;
5271       else
5272         w = NULL;
5273
5274       /* Need to select the frame, with all that implies so that
5275          the conditions will have the right context.  Because we
5276          use the frame, we will not see an inlined function's
5277          variables when we arrive at a breakpoint at the start
5278          of the inlined function; the current frame will be the
5279          call site.  */
5280       if (w == NULL || w->cond_exp_valid_block == NULL)
5281         select_frame (get_current_frame ());
5282       else
5283         {
5284           struct frame_info *frame;
5285
5286           /* For local watchpoint expressions, which particular
5287              instance of a local is being watched matters, so we
5288              keep track of the frame to evaluate the expression
5289              in.  To evaluate the condition however, it doesn't
5290              really matter which instantiation of the function
5291              where the condition makes sense triggers the
5292              watchpoint.  This allows an expression like "watch
5293              global if q > 10" set in `func', catch writes to
5294              global on all threads that call `func', or catch
5295              writes on all recursive calls of `func' by a single
5296              thread.  We simply always evaluate the condition in
5297              the innermost frame that's executing where it makes
5298              sense to evaluate the condition.  It seems
5299              intuitive.  */
5300           frame = block_innermost_frame (w->cond_exp_valid_block);
5301           if (frame != NULL)
5302             select_frame (frame);
5303           else
5304             within_current_scope = 0;
5305         }
5306       if (within_current_scope)
5307         {
5308           TRY
5309             {
5310               condition_result = breakpoint_cond_eval (cond);
5311             }
5312           CATCH (ex, RETURN_MASK_ALL)
5313             {
5314               exception_fprintf (gdb_stderr, ex,
5315                                  "Error in testing breakpoint condition:\n");
5316             }
5317           END_CATCH
5318         }
5319       else
5320         {
5321           warning (_("Watchpoint condition cannot be tested "
5322                      "in the current scope"));
5323           /* If we failed to set the right context for this
5324              watchpoint, unconditionally report it.  */
5325         }
5326       /* FIXME-someday, should give breakpoint #.  */
5327       value_free_to_mark (mark);
5328     }
5329
5330   if (cond && !condition_result)
5331     {
5332       bs->stop = 0;
5333     }
5334   else if (b->ignore_count > 0)
5335     {
5336       b->ignore_count--;
5337       bs->stop = 0;
5338       /* Increase the hit count even though we don't stop.  */
5339       ++(b->hit_count);
5340       observer_notify_breakpoint_modified (b);
5341     }   
5342 }
5343
5344 /* Returns true if we need to track moribund locations of LOC's type
5345    on the current target.  */
5346
5347 static int
5348 need_moribund_for_location_type (struct bp_location *loc)
5349 {
5350   return ((loc->loc_type == bp_loc_software_breakpoint
5351            && !target_supports_stopped_by_sw_breakpoint ())
5352           || (loc->loc_type == bp_loc_hardware_breakpoint
5353               && !target_supports_stopped_by_hw_breakpoint ()));
5354 }
5355
5356
5357 /* Get a bpstat associated with having just stopped at address
5358    BP_ADDR in thread PTID.
5359
5360    Determine whether we stopped at a breakpoint, etc, or whether we
5361    don't understand this stop.  Result is a chain of bpstat's such
5362    that:
5363
5364    if we don't understand the stop, the result is a null pointer.
5365
5366    if we understand why we stopped, the result is not null.
5367
5368    Each element of the chain refers to a particular breakpoint or
5369    watchpoint at which we have stopped.  (We may have stopped for
5370    several reasons concurrently.)
5371
5372    Each element of the chain has valid next, breakpoint_at,
5373    commands, FIXME??? fields.  */
5374
5375 bpstat
5376 bpstat_stop_status (const address_space *aspace,
5377                     CORE_ADDR bp_addr, ptid_t ptid,
5378                     const struct target_waitstatus *ws)
5379 {
5380   struct breakpoint *b = NULL;
5381   struct bp_location *bl;
5382   struct bp_location *loc;
5383   /* First item of allocated bpstat's.  */
5384   bpstat bs_head = NULL, *bs_link = &bs_head;
5385   /* Pointer to the last thing in the chain currently.  */
5386   bpstat bs;
5387   int ix;
5388   int need_remove_insert;
5389   int removed_any;
5390
5391   /* First, build the bpstat chain with locations that explain a
5392      target stop, while being careful to not set the target running,
5393      as that may invalidate locations (in particular watchpoint
5394      locations are recreated).  Resuming will happen here with
5395      breakpoint conditions or watchpoint expressions that include
5396      inferior function calls.  */
5397
5398   ALL_BREAKPOINTS (b)
5399     {
5400       if (!breakpoint_enabled (b))
5401         continue;
5402
5403       for (bl = b->loc; bl != NULL; bl = bl->next)
5404         {
5405           /* For hardware watchpoints, we look only at the first
5406              location.  The watchpoint_check function will work on the
5407              entire expression, not the individual locations.  For
5408              read watchpoints, the watchpoints_triggered function has
5409              checked all locations already.  */
5410           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5411             break;
5412
5413           if (!bl->enabled || bl->shlib_disabled)
5414             continue;
5415
5416           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5417             continue;
5418
5419           /* Come here if it's a watchpoint, or if the break address
5420              matches.  */
5421
5422           bs = new bpstats (bl, &bs_link);      /* Alloc a bpstat to
5423                                                    explain stop.  */
5424
5425           /* Assume we stop.  Should we find a watchpoint that is not
5426              actually triggered, or if the condition of the breakpoint
5427              evaluates as false, we'll reset 'stop' to 0.  */
5428           bs->stop = 1;
5429           bs->print = 1;
5430
5431           /* If this is a scope breakpoint, mark the associated
5432              watchpoint as triggered so that we will handle the
5433              out-of-scope event.  We'll get to the watchpoint next
5434              iteration.  */
5435           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5436             {
5437               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5438
5439               w->watchpoint_triggered = watch_triggered_yes;
5440             }
5441         }
5442     }
5443
5444   /* Check if a moribund breakpoint explains the stop.  */
5445   if (!target_supports_stopped_by_sw_breakpoint ()
5446       || !target_supports_stopped_by_hw_breakpoint ())
5447     {
5448       for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5449         {
5450           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5451               && need_moribund_for_location_type (loc))
5452             {
5453               bs = new bpstats (loc, &bs_link);
5454               /* For hits of moribund locations, we should just proceed.  */
5455               bs->stop = 0;
5456               bs->print = 0;
5457               bs->print_it = print_it_noop;
5458             }
5459         }
5460     }
5461
5462   /* A bit of special processing for shlib breakpoints.  We need to
5463      process solib loading here, so that the lists of loaded and
5464      unloaded libraries are correct before we handle "catch load" and
5465      "catch unload".  */
5466   for (bs = bs_head; bs != NULL; bs = bs->next)
5467     {
5468       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5469         {
5470           handle_solib_event ();
5471           break;
5472         }
5473     }
5474
5475   /* Now go through the locations that caused the target to stop, and
5476      check whether we're interested in reporting this stop to higher
5477      layers, or whether we should resume the target transparently.  */
5478
5479   removed_any = 0;
5480
5481   for (bs = bs_head; bs != NULL; bs = bs->next)
5482     {
5483       if (!bs->stop)
5484         continue;
5485
5486       b = bs->breakpoint_at;
5487       b->ops->check_status (bs);
5488       if (bs->stop)
5489         {
5490           bpstat_check_breakpoint_conditions (bs, ptid);
5491
5492           if (bs->stop)
5493             {
5494               ++(b->hit_count);
5495               observer_notify_breakpoint_modified (b);
5496
5497               /* We will stop here.  */
5498               if (b->disposition == disp_disable)
5499                 {
5500                   --(b->enable_count);
5501                   if (b->enable_count <= 0)
5502                     b->enable_state = bp_disabled;
5503                   removed_any = 1;
5504                 }
5505               if (b->silent)
5506                 bs->print = 0;
5507               bs->commands = b->commands;
5508               if (command_line_is_silent (bs->commands
5509                                           ? bs->commands.get () : NULL))
5510                 bs->print = 0;
5511
5512               b->ops->after_condition_true (bs);
5513             }
5514
5515         }
5516
5517       /* Print nothing for this entry if we don't stop or don't
5518          print.  */
5519       if (!bs->stop || !bs->print)
5520         bs->print_it = print_it_noop;
5521     }
5522
5523   /* If we aren't stopping, the value of some hardware watchpoint may
5524      not have changed, but the intermediate memory locations we are
5525      watching may have.  Don't bother if we're stopping; this will get
5526      done later.  */
5527   need_remove_insert = 0;
5528   if (! bpstat_causes_stop (bs_head))
5529     for (bs = bs_head; bs != NULL; bs = bs->next)
5530       if (!bs->stop
5531           && bs->breakpoint_at
5532           && is_hardware_watchpoint (bs->breakpoint_at))
5533         {
5534           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5535
5536           update_watchpoint (w, 0 /* don't reparse.  */);
5537           need_remove_insert = 1;
5538         }
5539
5540   if (need_remove_insert)
5541     update_global_location_list (UGLL_MAY_INSERT);
5542   else if (removed_any)
5543     update_global_location_list (UGLL_DONT_INSERT);
5544
5545   return bs_head;
5546 }
5547
5548 static void
5549 handle_jit_event (void)
5550 {
5551   struct frame_info *frame;
5552   struct gdbarch *gdbarch;
5553
5554   if (debug_infrun)
5555     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5556
5557   /* Switch terminal for any messages produced by
5558      breakpoint_re_set.  */
5559   target_terminal::ours_for_output ();
5560
5561   frame = get_current_frame ();
5562   gdbarch = get_frame_arch (frame);
5563
5564   jit_event_handler (gdbarch);
5565
5566   target_terminal::inferior ();
5567 }
5568
5569 /* Prepare WHAT final decision for infrun.  */
5570
5571 /* Decide what infrun needs to do with this bpstat.  */
5572
5573 struct bpstat_what
5574 bpstat_what (bpstat bs_head)
5575 {
5576   struct bpstat_what retval;
5577   bpstat bs;
5578
5579   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5580   retval.call_dummy = STOP_NONE;
5581   retval.is_longjmp = 0;
5582
5583   for (bs = bs_head; bs != NULL; bs = bs->next)
5584     {
5585       /* Extract this BS's action.  After processing each BS, we check
5586          if its action overrides all we've seem so far.  */
5587       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5588       enum bptype bptype;
5589
5590       if (bs->breakpoint_at == NULL)
5591         {
5592           /* I suspect this can happen if it was a momentary
5593              breakpoint which has since been deleted.  */
5594           bptype = bp_none;
5595         }
5596       else
5597         bptype = bs->breakpoint_at->type;
5598
5599       switch (bptype)
5600         {
5601         case bp_none:
5602           break;
5603         case bp_breakpoint:
5604         case bp_hardware_breakpoint:
5605         case bp_single_step:
5606         case bp_until:
5607         case bp_finish:
5608         case bp_shlib_event:
5609           if (bs->stop)
5610             {
5611               if (bs->print)
5612                 this_action = BPSTAT_WHAT_STOP_NOISY;
5613               else
5614                 this_action = BPSTAT_WHAT_STOP_SILENT;
5615             }
5616           else
5617             this_action = BPSTAT_WHAT_SINGLE;
5618           break;
5619         case bp_watchpoint:
5620         case bp_hardware_watchpoint:
5621         case bp_read_watchpoint:
5622         case bp_access_watchpoint:
5623           if (bs->stop)
5624             {
5625               if (bs->print)
5626                 this_action = BPSTAT_WHAT_STOP_NOISY;
5627               else
5628                 this_action = BPSTAT_WHAT_STOP_SILENT;
5629             }
5630           else
5631             {
5632               /* There was a watchpoint, but we're not stopping.
5633                  This requires no further action.  */
5634             }
5635           break;
5636         case bp_longjmp:
5637         case bp_longjmp_call_dummy:
5638         case bp_exception:
5639           if (bs->stop)
5640             {
5641               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5642               retval.is_longjmp = bptype != bp_exception;
5643             }
5644           else
5645             this_action = BPSTAT_WHAT_SINGLE;
5646           break;
5647         case bp_longjmp_resume:
5648         case bp_exception_resume:
5649           if (bs->stop)
5650             {
5651               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5652               retval.is_longjmp = bptype == bp_longjmp_resume;
5653             }
5654           else
5655             this_action = BPSTAT_WHAT_SINGLE;
5656           break;
5657         case bp_step_resume:
5658           if (bs->stop)
5659             this_action = BPSTAT_WHAT_STEP_RESUME;
5660           else
5661             {
5662               /* It is for the wrong frame.  */
5663               this_action = BPSTAT_WHAT_SINGLE;
5664             }
5665           break;
5666         case bp_hp_step_resume:
5667           if (bs->stop)
5668             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5669           else
5670             {
5671               /* It is for the wrong frame.  */
5672               this_action = BPSTAT_WHAT_SINGLE;
5673             }
5674           break;
5675         case bp_watchpoint_scope:
5676         case bp_thread_event:
5677         case bp_overlay_event:
5678         case bp_longjmp_master:
5679         case bp_std_terminate_master:
5680         case bp_exception_master:
5681           this_action = BPSTAT_WHAT_SINGLE;
5682           break;
5683         case bp_catchpoint:
5684           if (bs->stop)
5685             {
5686               if (bs->print)
5687                 this_action = BPSTAT_WHAT_STOP_NOISY;
5688               else
5689                 this_action = BPSTAT_WHAT_STOP_SILENT;
5690             }
5691           else
5692             {
5693               /* There was a catchpoint, but we're not stopping.
5694                  This requires no further action.  */
5695             }
5696           break;
5697         case bp_jit_event:
5698           this_action = BPSTAT_WHAT_SINGLE;
5699           break;
5700         case bp_call_dummy:
5701           /* Make sure the action is stop (silent or noisy),
5702              so infrun.c pops the dummy frame.  */
5703           retval.call_dummy = STOP_STACK_DUMMY;
5704           this_action = BPSTAT_WHAT_STOP_SILENT;
5705           break;
5706         case bp_std_terminate:
5707           /* Make sure the action is stop (silent or noisy),
5708              so infrun.c pops the dummy frame.  */
5709           retval.call_dummy = STOP_STD_TERMINATE;
5710           this_action = BPSTAT_WHAT_STOP_SILENT;
5711           break;
5712         case bp_tracepoint:
5713         case bp_fast_tracepoint:
5714         case bp_static_tracepoint:
5715           /* Tracepoint hits should not be reported back to GDB, and
5716              if one got through somehow, it should have been filtered
5717              out already.  */
5718           internal_error (__FILE__, __LINE__,
5719                           _("bpstat_what: tracepoint encountered"));
5720           break;
5721         case bp_gnu_ifunc_resolver:
5722           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5723           this_action = BPSTAT_WHAT_SINGLE;
5724           break;
5725         case bp_gnu_ifunc_resolver_return:
5726           /* The breakpoint will be removed, execution will restart from the
5727              PC of the former breakpoint.  */
5728           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5729           break;
5730
5731         case bp_dprintf:
5732           if (bs->stop)
5733             this_action = BPSTAT_WHAT_STOP_SILENT;
5734           else
5735             this_action = BPSTAT_WHAT_SINGLE;
5736           break;
5737
5738         default:
5739           internal_error (__FILE__, __LINE__,
5740                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5741         }
5742
5743       retval.main_action = std::max (retval.main_action, this_action);
5744     }
5745
5746   return retval;
5747 }
5748
5749 void
5750 bpstat_run_callbacks (bpstat bs_head)
5751 {
5752   bpstat bs;
5753
5754   for (bs = bs_head; bs != NULL; bs = bs->next)
5755     {
5756       struct breakpoint *b = bs->breakpoint_at;
5757
5758       if (b == NULL)
5759         continue;
5760       switch (b->type)
5761         {
5762         case bp_jit_event:
5763           handle_jit_event ();
5764           break;
5765         case bp_gnu_ifunc_resolver:
5766           gnu_ifunc_resolver_stop (b);
5767           break;
5768         case bp_gnu_ifunc_resolver_return:
5769           gnu_ifunc_resolver_return_stop (b);
5770           break;
5771         }
5772     }
5773 }
5774
5775 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5776    without hardware support).  This isn't related to a specific bpstat,
5777    just to things like whether watchpoints are set.  */
5778
5779 int
5780 bpstat_should_step (void)
5781 {
5782   struct breakpoint *b;
5783
5784   ALL_BREAKPOINTS (b)
5785     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5786       return 1;
5787   return 0;
5788 }
5789
5790 int
5791 bpstat_causes_stop (bpstat bs)
5792 {
5793   for (; bs != NULL; bs = bs->next)
5794     if (bs->stop)
5795       return 1;
5796
5797   return 0;
5798 }
5799
5800 \f
5801
5802 /* Compute a string of spaces suitable to indent the next line
5803    so it starts at the position corresponding to the table column
5804    named COL_NAME in the currently active table of UIOUT.  */
5805
5806 static char *
5807 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5808 {
5809   static char wrap_indent[80];
5810   int i, total_width, width, align;
5811   const char *text;
5812
5813   total_width = 0;
5814   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
5815     {
5816       if (strcmp (text, col_name) == 0)
5817         {
5818           gdb_assert (total_width < sizeof wrap_indent);
5819           memset (wrap_indent, ' ', total_width);
5820           wrap_indent[total_width] = 0;
5821
5822           return wrap_indent;
5823         }
5824
5825       total_width += width + 1;
5826     }
5827
5828   return NULL;
5829 }
5830
5831 /* Determine if the locations of this breakpoint will have their conditions
5832    evaluated by the target, host or a mix of both.  Returns the following:
5833
5834     "host": Host evals condition.
5835     "host or target": Host or Target evals condition.
5836     "target": Target evals condition.
5837 */
5838
5839 static const char *
5840 bp_condition_evaluator (struct breakpoint *b)
5841 {
5842   struct bp_location *bl;
5843   char host_evals = 0;
5844   char target_evals = 0;
5845
5846   if (!b)
5847     return NULL;
5848
5849   if (!is_breakpoint (b))
5850     return NULL;
5851
5852   if (gdb_evaluates_breakpoint_condition_p ()
5853       || !target_supports_evaluation_of_breakpoint_conditions ())
5854     return condition_evaluation_host;
5855
5856   for (bl = b->loc; bl; bl = bl->next)
5857     {
5858       if (bl->cond_bytecode)
5859         target_evals++;
5860       else
5861         host_evals++;
5862     }
5863
5864   if (host_evals && target_evals)
5865     return condition_evaluation_both;
5866   else if (target_evals)
5867     return condition_evaluation_target;
5868   else
5869     return condition_evaluation_host;
5870 }
5871
5872 /* Determine the breakpoint location's condition evaluator.  This is
5873    similar to bp_condition_evaluator, but for locations.  */
5874
5875 static const char *
5876 bp_location_condition_evaluator (struct bp_location *bl)
5877 {
5878   if (bl && !is_breakpoint (bl->owner))
5879     return NULL;
5880
5881   if (gdb_evaluates_breakpoint_condition_p ()
5882       || !target_supports_evaluation_of_breakpoint_conditions ())
5883     return condition_evaluation_host;
5884
5885   if (bl && bl->cond_bytecode)
5886     return condition_evaluation_target;
5887   else
5888     return condition_evaluation_host;
5889 }
5890
5891 /* Print the LOC location out of the list of B->LOC locations.  */
5892
5893 static void
5894 print_breakpoint_location (struct breakpoint *b,
5895                            struct bp_location *loc)
5896 {
5897   struct ui_out *uiout = current_uiout;
5898
5899   scoped_restore_current_program_space restore_pspace;
5900
5901   if (loc != NULL && loc->shlib_disabled)
5902     loc = NULL;
5903
5904   if (loc != NULL)
5905     set_current_program_space (loc->pspace);
5906
5907   if (b->display_canonical)
5908     uiout->field_string ("what", event_location_to_string (b->location.get ()));
5909   else if (loc && loc->symtab)
5910     {
5911       const struct symbol *sym = loc->symbol;
5912
5913       if (sym == NULL)
5914         sym = find_pc_sect_function (loc->address, loc->section);
5915
5916       if (sym)
5917         {
5918           uiout->text ("in ");
5919           uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
5920           uiout->text (" ");
5921           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
5922           uiout->text ("at ");
5923         }
5924       uiout->field_string ("file",
5925                            symtab_to_filename_for_display (loc->symtab));
5926       uiout->text (":");
5927
5928       if (uiout->is_mi_like_p ())
5929         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
5930       
5931       uiout->field_int ("line", loc->line_number);
5932     }
5933   else if (loc)
5934     {
5935       string_file stb;
5936
5937       print_address_symbolic (loc->gdbarch, loc->address, &stb,
5938                               demangle, "");
5939       uiout->field_stream ("at", stb);
5940     }
5941   else
5942     {
5943       uiout->field_string ("pending",
5944                            event_location_to_string (b->location.get ()));
5945       /* If extra_string is available, it could be holding a condition
5946          or dprintf arguments.  In either case, make sure it is printed,
5947          too, but only for non-MI streams.  */
5948       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
5949         {
5950           if (b->type == bp_dprintf)
5951             uiout->text (",");
5952           else
5953             uiout->text (" ");
5954           uiout->text (b->extra_string);
5955         }
5956     }
5957
5958   if (loc && is_breakpoint (b)
5959       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5960       && bp_condition_evaluator (b) == condition_evaluation_both)
5961     {
5962       uiout->text (" (");
5963       uiout->field_string ("evaluated-by",
5964                            bp_location_condition_evaluator (loc));
5965       uiout->text (")");
5966     }
5967 }
5968
5969 static const char *
5970 bptype_string (enum bptype type)
5971 {
5972   struct ep_type_description
5973     {
5974       enum bptype type;
5975       const char *description;
5976     };
5977   static struct ep_type_description bptypes[] =
5978   {
5979     {bp_none, "?deleted?"},
5980     {bp_breakpoint, "breakpoint"},
5981     {bp_hardware_breakpoint, "hw breakpoint"},
5982     {bp_single_step, "sw single-step"},
5983     {bp_until, "until"},
5984     {bp_finish, "finish"},
5985     {bp_watchpoint, "watchpoint"},
5986     {bp_hardware_watchpoint, "hw watchpoint"},
5987     {bp_read_watchpoint, "read watchpoint"},
5988     {bp_access_watchpoint, "acc watchpoint"},
5989     {bp_longjmp, "longjmp"},
5990     {bp_longjmp_resume, "longjmp resume"},
5991     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5992     {bp_exception, "exception"},
5993     {bp_exception_resume, "exception resume"},
5994     {bp_step_resume, "step resume"},
5995     {bp_hp_step_resume, "high-priority step resume"},
5996     {bp_watchpoint_scope, "watchpoint scope"},
5997     {bp_call_dummy, "call dummy"},
5998     {bp_std_terminate, "std::terminate"},
5999     {bp_shlib_event, "shlib events"},
6000     {bp_thread_event, "thread events"},
6001     {bp_overlay_event, "overlay events"},
6002     {bp_longjmp_master, "longjmp master"},
6003     {bp_std_terminate_master, "std::terminate master"},
6004     {bp_exception_master, "exception master"},
6005     {bp_catchpoint, "catchpoint"},
6006     {bp_tracepoint, "tracepoint"},
6007     {bp_fast_tracepoint, "fast tracepoint"},
6008     {bp_static_tracepoint, "static tracepoint"},
6009     {bp_dprintf, "dprintf"},
6010     {bp_jit_event, "jit events"},
6011     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6012     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6013   };
6014
6015   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6016       || ((int) type != bptypes[(int) type].type))
6017     internal_error (__FILE__, __LINE__,
6018                     _("bptypes table does not describe type #%d."),
6019                     (int) type);
6020
6021   return bptypes[(int) type].description;
6022 }
6023
6024 /* For MI, output a field named 'thread-groups' with a list as the value.
6025    For CLI, prefix the list with the string 'inf'. */
6026
6027 static void
6028 output_thread_groups (struct ui_out *uiout,
6029                       const char *field_name,
6030                       const std::vector<int> &inf_nums,
6031                       int mi_only)
6032 {
6033   int is_mi = uiout->is_mi_like_p ();
6034
6035   /* For backward compatibility, don't display inferiors in CLI unless
6036      there are several.  Always display them for MI. */
6037   if (!is_mi && mi_only)
6038     return;
6039
6040   ui_out_emit_list list_emitter (uiout, field_name);
6041
6042   for (size_t i = 0; i < inf_nums.size (); i++)
6043     {
6044       if (is_mi)
6045         {
6046           char mi_group[10];
6047
6048           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf_nums[i]);
6049           uiout->field_string (NULL, mi_group);
6050         }
6051       else
6052         {
6053           if (i == 0)
6054             uiout->text (" inf ");
6055           else
6056             uiout->text (", ");
6057         
6058           uiout->text (plongest (inf_nums[i]));
6059         }
6060     }
6061 }
6062
6063 /* Print B to gdb_stdout.  */
6064
6065 static void
6066 print_one_breakpoint_location (struct breakpoint *b,
6067                                struct bp_location *loc,
6068                                int loc_number,
6069                                struct bp_location **last_loc,
6070                                int allflag)
6071 {
6072   struct command_line *l;
6073   static char bpenables[] = "nynny";
6074
6075   struct ui_out *uiout = current_uiout;
6076   int header_of_multiple = 0;
6077   int part_of_multiple = (loc != NULL);
6078   struct value_print_options opts;
6079
6080   get_user_print_options (&opts);
6081
6082   gdb_assert (!loc || loc_number != 0);
6083   /* See comment in print_one_breakpoint concerning treatment of
6084      breakpoints with single disabled location.  */
6085   if (loc == NULL 
6086       && (b->loc != NULL 
6087           && (b->loc->next != NULL || !b->loc->enabled)))
6088     header_of_multiple = 1;
6089   if (loc == NULL)
6090     loc = b->loc;
6091
6092   annotate_record ();
6093
6094   /* 1 */
6095   annotate_field (0);
6096   if (part_of_multiple)
6097     {
6098       char *formatted;
6099       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6100       uiout->field_string ("number", formatted);
6101       xfree (formatted);
6102     }
6103   else
6104     {
6105       uiout->field_int ("number", b->number);
6106     }
6107
6108   /* 2 */
6109   annotate_field (1);
6110   if (part_of_multiple)
6111     uiout->field_skip ("type");
6112   else
6113     uiout->field_string ("type", bptype_string (b->type));
6114
6115   /* 3 */
6116   annotate_field (2);
6117   if (part_of_multiple)
6118     uiout->field_skip ("disp");
6119   else
6120     uiout->field_string ("disp", bpdisp_text (b->disposition));
6121
6122
6123   /* 4 */
6124   annotate_field (3);
6125   if (part_of_multiple)
6126     uiout->field_string ("enabled", loc->enabled ? "y" : "n");
6127   else
6128     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6129   uiout->spaces (2);
6130
6131   
6132   /* 5 and 6 */
6133   if (b->ops != NULL && b->ops->print_one != NULL)
6134     {
6135       /* Although the print_one can possibly print all locations,
6136          calling it here is not likely to get any nice result.  So,
6137          make sure there's just one location.  */
6138       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6139       b->ops->print_one (b, last_loc);
6140     }
6141   else
6142     switch (b->type)
6143       {
6144       case bp_none:
6145         internal_error (__FILE__, __LINE__,
6146                         _("print_one_breakpoint: bp_none encountered\n"));
6147         break;
6148
6149       case bp_watchpoint:
6150       case bp_hardware_watchpoint:
6151       case bp_read_watchpoint:
6152       case bp_access_watchpoint:
6153         {
6154           struct watchpoint *w = (struct watchpoint *) b;
6155
6156           /* Field 4, the address, is omitted (which makes the columns
6157              not line up too nicely with the headers, but the effect
6158              is relatively readable).  */
6159           if (opts.addressprint)
6160             uiout->field_skip ("addr");
6161           annotate_field (5);
6162           uiout->field_string ("what", w->exp_string);
6163         }
6164         break;
6165
6166       case bp_breakpoint:
6167       case bp_hardware_breakpoint:
6168       case bp_single_step:
6169       case bp_until:
6170       case bp_finish:
6171       case bp_longjmp:
6172       case bp_longjmp_resume:
6173       case bp_longjmp_call_dummy:
6174       case bp_exception:
6175       case bp_exception_resume:
6176       case bp_step_resume:
6177       case bp_hp_step_resume:
6178       case bp_watchpoint_scope:
6179       case bp_call_dummy:
6180       case bp_std_terminate:
6181       case bp_shlib_event:
6182       case bp_thread_event:
6183       case bp_overlay_event:
6184       case bp_longjmp_master:
6185       case bp_std_terminate_master:
6186       case bp_exception_master:
6187       case bp_tracepoint:
6188       case bp_fast_tracepoint:
6189       case bp_static_tracepoint:
6190       case bp_dprintf:
6191       case bp_jit_event:
6192       case bp_gnu_ifunc_resolver:
6193       case bp_gnu_ifunc_resolver_return:
6194         if (opts.addressprint)
6195           {
6196             annotate_field (4);
6197             if (header_of_multiple)
6198               uiout->field_string ("addr", "<MULTIPLE>");
6199             else if (b->loc == NULL || loc->shlib_disabled)
6200               uiout->field_string ("addr", "<PENDING>");
6201             else
6202               uiout->field_core_addr ("addr",
6203                                       loc->gdbarch, loc->address);
6204           }
6205         annotate_field (5);
6206         if (!header_of_multiple)
6207           print_breakpoint_location (b, loc);
6208         if (b->loc)
6209           *last_loc = b->loc;
6210         break;
6211       }
6212
6213
6214   if (loc != NULL && !header_of_multiple)
6215     {
6216       struct inferior *inf;
6217       std::vector<int> inf_nums;
6218       int mi_only = 1;
6219
6220       ALL_INFERIORS (inf)
6221         {
6222           if (inf->pspace == loc->pspace)
6223             inf_nums.push_back (inf->num);
6224         }
6225
6226         /* For backward compatibility, don't display inferiors in CLI unless
6227            there are several.  Always display for MI. */
6228         if (allflag
6229             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6230                 && (number_of_program_spaces () > 1
6231                     || number_of_inferiors () > 1)
6232                 /* LOC is for existing B, it cannot be in
6233                    moribund_locations and thus having NULL OWNER.  */
6234                 && loc->owner->type != bp_catchpoint))
6235         mi_only = 0;
6236       output_thread_groups (uiout, "thread-groups", inf_nums, mi_only);
6237     }
6238
6239   if (!part_of_multiple)
6240     {
6241       if (b->thread != -1)
6242         {
6243           /* FIXME: This seems to be redundant and lost here; see the
6244              "stop only in" line a little further down.  */
6245           uiout->text (" thread ");
6246           uiout->field_int ("thread", b->thread);
6247         }
6248       else if (b->task != 0)
6249         {
6250           uiout->text (" task ");
6251           uiout->field_int ("task", b->task);
6252         }
6253     }
6254
6255   uiout->text ("\n");
6256
6257   if (!part_of_multiple)
6258     b->ops->print_one_detail (b, uiout);
6259
6260   if (part_of_multiple && frame_id_p (b->frame_id))
6261     {
6262       annotate_field (6);
6263       uiout->text ("\tstop only in stack frame at ");
6264       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6265          the frame ID.  */
6266       uiout->field_core_addr ("frame",
6267                               b->gdbarch, b->frame_id.stack_addr);
6268       uiout->text ("\n");
6269     }
6270   
6271   if (!part_of_multiple && b->cond_string)
6272     {
6273       annotate_field (7);
6274       if (is_tracepoint (b))
6275         uiout->text ("\ttrace only if ");
6276       else
6277         uiout->text ("\tstop only if ");
6278       uiout->field_string ("cond", b->cond_string);
6279
6280       /* Print whether the target is doing the breakpoint's condition
6281          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6282       if (is_breakpoint (b)
6283           && breakpoint_condition_evaluation_mode ()
6284           == condition_evaluation_target)
6285         {
6286           uiout->text (" (");
6287           uiout->field_string ("evaluated-by",
6288                                bp_condition_evaluator (b));
6289           uiout->text (" evals)");
6290         }
6291       uiout->text ("\n");
6292     }
6293
6294   if (!part_of_multiple && b->thread != -1)
6295     {
6296       /* FIXME should make an annotation for this.  */
6297       uiout->text ("\tstop only in thread ");
6298       if (uiout->is_mi_like_p ())
6299         uiout->field_int ("thread", b->thread);
6300       else
6301         {
6302           struct thread_info *thr = find_thread_global_id (b->thread);
6303
6304           uiout->field_string ("thread", print_thread_id (thr));
6305         }
6306       uiout->text ("\n");
6307     }
6308   
6309   if (!part_of_multiple)
6310     {
6311       if (b->hit_count)
6312         {
6313           /* FIXME should make an annotation for this.  */
6314           if (is_catchpoint (b))
6315             uiout->text ("\tcatchpoint");
6316           else if (is_tracepoint (b))
6317             uiout->text ("\ttracepoint");
6318           else
6319             uiout->text ("\tbreakpoint");
6320           uiout->text (" already hit ");
6321           uiout->field_int ("times", b->hit_count);
6322           if (b->hit_count == 1)
6323             uiout->text (" time\n");
6324           else
6325             uiout->text (" times\n");
6326         }
6327       else
6328         {
6329           /* Output the count also if it is zero, but only if this is mi.  */
6330           if (uiout->is_mi_like_p ())
6331             uiout->field_int ("times", b->hit_count);
6332         }
6333     }
6334
6335   if (!part_of_multiple && b->ignore_count)
6336     {
6337       annotate_field (8);
6338       uiout->text ("\tignore next ");
6339       uiout->field_int ("ignore", b->ignore_count);
6340       uiout->text (" hits\n");
6341     }
6342
6343   /* Note that an enable count of 1 corresponds to "enable once"
6344      behavior, which is reported by the combination of enablement and
6345      disposition, so we don't need to mention it here.  */
6346   if (!part_of_multiple && b->enable_count > 1)
6347     {
6348       annotate_field (8);
6349       uiout->text ("\tdisable after ");
6350       /* Tweak the wording to clarify that ignore and enable counts
6351          are distinct, and have additive effect.  */
6352       if (b->ignore_count)
6353         uiout->text ("additional ");
6354       else
6355         uiout->text ("next ");
6356       uiout->field_int ("enable", b->enable_count);
6357       uiout->text (" hits\n");
6358     }
6359
6360   if (!part_of_multiple && is_tracepoint (b))
6361     {
6362       struct tracepoint *tp = (struct tracepoint *) b;
6363
6364       if (tp->traceframe_usage)
6365         {
6366           uiout->text ("\ttrace buffer usage ");
6367           uiout->field_int ("traceframe-usage", tp->traceframe_usage);
6368           uiout->text (" bytes\n");
6369         }
6370     }
6371
6372   l = b->commands ? b->commands.get () : NULL;
6373   if (!part_of_multiple && l)
6374     {
6375       annotate_field (9);
6376       ui_out_emit_tuple tuple_emitter (uiout, "script");
6377       print_command_lines (uiout, l, 4);
6378     }
6379
6380   if (is_tracepoint (b))
6381     {
6382       struct tracepoint *t = (struct tracepoint *) b;
6383
6384       if (!part_of_multiple && t->pass_count)
6385         {
6386           annotate_field (10);
6387           uiout->text ("\tpass count ");
6388           uiout->field_int ("pass", t->pass_count);
6389           uiout->text (" \n");
6390         }
6391
6392       /* Don't display it when tracepoint or tracepoint location is
6393          pending.   */
6394       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6395         {
6396           annotate_field (11);
6397
6398           if (uiout->is_mi_like_p ())
6399             uiout->field_string ("installed",
6400                                  loc->inserted ? "y" : "n");
6401           else
6402             {
6403               if (loc->inserted)
6404                 uiout->text ("\t");
6405               else
6406                 uiout->text ("\tnot ");
6407               uiout->text ("installed on target\n");
6408             }
6409         }
6410     }
6411
6412   if (uiout->is_mi_like_p () && !part_of_multiple)
6413     {
6414       if (is_watchpoint (b))
6415         {
6416           struct watchpoint *w = (struct watchpoint *) b;
6417
6418           uiout->field_string ("original-location", w->exp_string);
6419         }
6420       else if (b->location != NULL
6421                && event_location_to_string (b->location.get ()) != NULL)
6422         uiout->field_string ("original-location",
6423                              event_location_to_string (b->location.get ()));
6424     }
6425 }
6426
6427 static void
6428 print_one_breakpoint (struct breakpoint *b,
6429                       struct bp_location **last_loc, 
6430                       int allflag)
6431 {
6432   struct ui_out *uiout = current_uiout;
6433
6434   {
6435     ui_out_emit_tuple tuple_emitter (uiout, "bkpt");
6436
6437     print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6438   }
6439
6440   /* If this breakpoint has custom print function,
6441      it's already printed.  Otherwise, print individual
6442      locations, if any.  */
6443   if (b->ops == NULL || b->ops->print_one == NULL)
6444     {
6445       /* If breakpoint has a single location that is disabled, we
6446          print it as if it had several locations, since otherwise it's
6447          hard to represent "breakpoint enabled, location disabled"
6448          situation.
6449
6450          Note that while hardware watchpoints have several locations
6451          internally, that's not a property exposed to user.  */
6452       if (b->loc 
6453           && !is_hardware_watchpoint (b)
6454           && (b->loc->next || !b->loc->enabled))
6455         {
6456           struct bp_location *loc;
6457           int n = 1;
6458
6459           for (loc = b->loc; loc; loc = loc->next, ++n)
6460             {
6461               ui_out_emit_tuple tuple_emitter (uiout, NULL);
6462               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6463             }
6464         }
6465     }
6466 }
6467
6468 static int
6469 breakpoint_address_bits (struct breakpoint *b)
6470 {
6471   int print_address_bits = 0;
6472   struct bp_location *loc;
6473
6474   /* Software watchpoints that aren't watching memory don't have an
6475      address to print.  */
6476   if (is_no_memory_software_watchpoint (b))
6477     return 0;
6478
6479   for (loc = b->loc; loc; loc = loc->next)
6480     {
6481       int addr_bit;
6482
6483       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6484       if (addr_bit > print_address_bits)
6485         print_address_bits = addr_bit;
6486     }
6487
6488   return print_address_bits;
6489 }
6490
6491 /* See breakpoint.h.  */
6492
6493 void
6494 print_breakpoint (breakpoint *b)
6495 {
6496   struct bp_location *dummy_loc = NULL;
6497   print_one_breakpoint (b, &dummy_loc, 0);
6498 }
6499
6500 /* Return true if this breakpoint was set by the user, false if it is
6501    internal or momentary.  */
6502
6503 int
6504 user_breakpoint_p (struct breakpoint *b)
6505 {
6506   return b->number > 0;
6507 }
6508
6509 /* See breakpoint.h.  */
6510
6511 int
6512 pending_breakpoint_p (struct breakpoint *b)
6513 {
6514   return b->loc == NULL;
6515 }
6516
6517 /* Print information on user settable breakpoint (watchpoint, etc)
6518    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6519    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6520    FILTER is non-NULL, call it on each breakpoint and only include the
6521    ones for which it returns non-zero.  Return the total number of
6522    breakpoints listed.  */
6523
6524 static int
6525 breakpoint_1 (const char *args, int allflag, 
6526               int (*filter) (const struct breakpoint *))
6527 {
6528   struct breakpoint *b;
6529   struct bp_location *last_loc = NULL;
6530   int nr_printable_breakpoints;
6531   struct value_print_options opts;
6532   int print_address_bits = 0;
6533   int print_type_col_width = 14;
6534   struct ui_out *uiout = current_uiout;
6535
6536   get_user_print_options (&opts);
6537
6538   /* Compute the number of rows in the table, as well as the size
6539      required for address fields.  */
6540   nr_printable_breakpoints = 0;
6541   ALL_BREAKPOINTS (b)
6542     {
6543       /* If we have a filter, only list the breakpoints it accepts.  */
6544       if (filter && !filter (b))
6545         continue;
6546
6547       /* If we have an "args" string, it is a list of breakpoints to 
6548          accept.  Skip the others.  */
6549       if (args != NULL && *args != '\0')
6550         {
6551           if (allflag && parse_and_eval_long (args) != b->number)
6552             continue;
6553           if (!allflag && !number_is_in_list (args, b->number))
6554             continue;
6555         }
6556
6557       if (allflag || user_breakpoint_p (b))
6558         {
6559           int addr_bit, type_len;
6560
6561           addr_bit = breakpoint_address_bits (b);
6562           if (addr_bit > print_address_bits)
6563             print_address_bits = addr_bit;
6564
6565           type_len = strlen (bptype_string (b->type));
6566           if (type_len > print_type_col_width)
6567             print_type_col_width = type_len;
6568
6569           nr_printable_breakpoints++;
6570         }
6571     }
6572
6573   {
6574     ui_out_emit_table table_emitter (uiout,
6575                                      opts.addressprint ? 6 : 5,
6576                                      nr_printable_breakpoints,
6577                                      "BreakpointTable");
6578
6579     if (nr_printable_breakpoints > 0)
6580       annotate_breakpoints_headers ();
6581     if (nr_printable_breakpoints > 0)
6582       annotate_field (0);
6583     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6584     if (nr_printable_breakpoints > 0)
6585       annotate_field (1);
6586     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6587     if (nr_printable_breakpoints > 0)
6588       annotate_field (2);
6589     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6590     if (nr_printable_breakpoints > 0)
6591       annotate_field (3);
6592     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6593     if (opts.addressprint)
6594       {
6595         if (nr_printable_breakpoints > 0)
6596           annotate_field (4);
6597         if (print_address_bits <= 32)
6598           uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6599         else
6600           uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6601       }
6602     if (nr_printable_breakpoints > 0)
6603       annotate_field (5);
6604     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6605     uiout->table_body ();
6606     if (nr_printable_breakpoints > 0)
6607       annotate_breakpoints_table ();
6608
6609     ALL_BREAKPOINTS (b)
6610       {
6611         QUIT;
6612         /* If we have a filter, only list the breakpoints it accepts.  */
6613         if (filter && !filter (b))
6614           continue;
6615
6616         /* If we have an "args" string, it is a list of breakpoints to 
6617            accept.  Skip the others.  */
6618
6619         if (args != NULL && *args != '\0')
6620           {
6621             if (allflag)        /* maintenance info breakpoint */
6622               {
6623                 if (parse_and_eval_long (args) != b->number)
6624                   continue;
6625               }
6626             else                /* all others */
6627               {
6628                 if (!number_is_in_list (args, b->number))
6629                   continue;
6630               }
6631           }
6632         /* We only print out user settable breakpoints unless the
6633            allflag is set.  */
6634         if (allflag || user_breakpoint_p (b))
6635           print_one_breakpoint (b, &last_loc, allflag);
6636       }
6637   }
6638
6639   if (nr_printable_breakpoints == 0)
6640     {
6641       /* If there's a filter, let the caller decide how to report
6642          empty list.  */
6643       if (!filter)
6644         {
6645           if (args == NULL || *args == '\0')
6646             uiout->message ("No breakpoints or watchpoints.\n");
6647           else
6648             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6649                             args);
6650         }
6651     }
6652   else
6653     {
6654       if (last_loc && !server_command)
6655         set_next_address (last_loc->gdbarch, last_loc->address);
6656     }
6657
6658   /* FIXME?  Should this be moved up so that it is only called when
6659      there have been breakpoints? */
6660   annotate_breakpoints_table_end ();
6661
6662   return nr_printable_breakpoints;
6663 }
6664
6665 /* Display the value of default-collect in a way that is generally
6666    compatible with the breakpoint list.  */
6667
6668 static void
6669 default_collect_info (void)
6670 {
6671   struct ui_out *uiout = current_uiout;
6672
6673   /* If it has no value (which is frequently the case), say nothing; a
6674      message like "No default-collect." gets in user's face when it's
6675      not wanted.  */
6676   if (!*default_collect)
6677     return;
6678
6679   /* The following phrase lines up nicely with per-tracepoint collect
6680      actions.  */
6681   uiout->text ("default collect ");
6682   uiout->field_string ("default-collect", default_collect);
6683   uiout->text (" \n");
6684 }
6685   
6686 static void
6687 info_breakpoints_command (const char *args, int from_tty)
6688 {
6689   breakpoint_1 (args, 0, NULL);
6690
6691   default_collect_info ();
6692 }
6693
6694 static void
6695 info_watchpoints_command (const char *args, int from_tty)
6696 {
6697   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6698   struct ui_out *uiout = current_uiout;
6699
6700   if (num_printed == 0)
6701     {
6702       if (args == NULL || *args == '\0')
6703         uiout->message ("No watchpoints.\n");
6704       else
6705         uiout->message ("No watchpoint matching '%s'.\n", args);
6706     }
6707 }
6708
6709 static void
6710 maintenance_info_breakpoints (const char *args, int from_tty)
6711 {
6712   breakpoint_1 (args, 1, NULL);
6713
6714   default_collect_info ();
6715 }
6716
6717 static int
6718 breakpoint_has_pc (struct breakpoint *b,
6719                    struct program_space *pspace,
6720                    CORE_ADDR pc, struct obj_section *section)
6721 {
6722   struct bp_location *bl = b->loc;
6723
6724   for (; bl; bl = bl->next)
6725     {
6726       if (bl->pspace == pspace
6727           && bl->address == pc
6728           && (!overlay_debugging || bl->section == section))
6729         return 1;         
6730     }
6731   return 0;
6732 }
6733
6734 /* Print a message describing any user-breakpoints set at PC.  This
6735    concerns with logical breakpoints, so we match program spaces, not
6736    address spaces.  */
6737
6738 static void
6739 describe_other_breakpoints (struct gdbarch *gdbarch,
6740                             struct program_space *pspace, CORE_ADDR pc,
6741                             struct obj_section *section, int thread)
6742 {
6743   int others = 0;
6744   struct breakpoint *b;
6745
6746   ALL_BREAKPOINTS (b)
6747     others += (user_breakpoint_p (b)
6748                && breakpoint_has_pc (b, pspace, pc, section));
6749   if (others > 0)
6750     {
6751       if (others == 1)
6752         printf_filtered (_("Note: breakpoint "));
6753       else /* if (others == ???) */
6754         printf_filtered (_("Note: breakpoints "));
6755       ALL_BREAKPOINTS (b)
6756         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6757           {
6758             others--;
6759             printf_filtered ("%d", b->number);
6760             if (b->thread == -1 && thread != -1)
6761               printf_filtered (" (all threads)");
6762             else if (b->thread != -1)
6763               printf_filtered (" (thread %d)", b->thread);
6764             printf_filtered ("%s%s ",
6765                              ((b->enable_state == bp_disabled
6766                                || b->enable_state == bp_call_disabled)
6767                               ? " (disabled)"
6768                               : ""),
6769                              (others > 1) ? "," 
6770                              : ((others == 1) ? " and" : ""));
6771           }
6772       printf_filtered (_("also set at pc "));
6773       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6774       printf_filtered (".\n");
6775     }
6776 }
6777 \f
6778
6779 /* Return true iff it is meaningful to use the address member of
6780    BPT locations.  For some breakpoint types, the locations' address members
6781    are irrelevant and it makes no sense to attempt to compare them to other
6782    addresses (or use them for any other purpose either).
6783
6784    More specifically, each of the following breakpoint types will
6785    always have a zero valued location address and we don't want to mark
6786    breakpoints of any of these types to be a duplicate of an actual
6787    breakpoint location at address zero:
6788
6789       bp_watchpoint
6790       bp_catchpoint
6791
6792 */
6793
6794 static int
6795 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6796 {
6797   enum bptype type = bpt->type;
6798
6799   return (type != bp_watchpoint && type != bp_catchpoint);
6800 }
6801
6802 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6803    true if LOC1 and LOC2 represent the same watchpoint location.  */
6804
6805 static int
6806 watchpoint_locations_match (struct bp_location *loc1, 
6807                             struct bp_location *loc2)
6808 {
6809   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6810   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6811
6812   /* Both of them must exist.  */
6813   gdb_assert (w1 != NULL);
6814   gdb_assert (w2 != NULL);
6815
6816   /* If the target can evaluate the condition expression in hardware,
6817      then we we need to insert both watchpoints even if they are at
6818      the same place.  Otherwise the watchpoint will only trigger when
6819      the condition of whichever watchpoint was inserted evaluates to
6820      true, not giving a chance for GDB to check the condition of the
6821      other watchpoint.  */
6822   if ((w1->cond_exp
6823        && target_can_accel_watchpoint_condition (loc1->address, 
6824                                                  loc1->length,
6825                                                  loc1->watchpoint_type,
6826                                                  w1->cond_exp.get ()))
6827       || (w2->cond_exp
6828           && target_can_accel_watchpoint_condition (loc2->address, 
6829                                                     loc2->length,
6830                                                     loc2->watchpoint_type,
6831                                                     w2->cond_exp.get ())))
6832     return 0;
6833
6834   /* Note that this checks the owner's type, not the location's.  In
6835      case the target does not support read watchpoints, but does
6836      support access watchpoints, we'll have bp_read_watchpoint
6837      watchpoints with hw_access locations.  Those should be considered
6838      duplicates of hw_read locations.  The hw_read locations will
6839      become hw_access locations later.  */
6840   return (loc1->owner->type == loc2->owner->type
6841           && loc1->pspace->aspace == loc2->pspace->aspace
6842           && loc1->address == loc2->address
6843           && loc1->length == loc2->length);
6844 }
6845
6846 /* See breakpoint.h.  */
6847
6848 int
6849 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
6850                           const address_space *aspace2, CORE_ADDR addr2)
6851 {
6852   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6853            || aspace1 == aspace2)
6854           && addr1 == addr2);
6855 }
6856
6857 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6858    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6859    matches ASPACE2.  On targets that have global breakpoints, the address
6860    space doesn't really matter.  */
6861
6862 static int
6863 breakpoint_address_match_range (const address_space *aspace1,
6864                                 CORE_ADDR addr1,
6865                                 int len1, const address_space *aspace2,
6866                                 CORE_ADDR addr2)
6867 {
6868   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6869            || aspace1 == aspace2)
6870           && addr2 >= addr1 && addr2 < addr1 + len1);
6871 }
6872
6873 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6874    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6875    matches the breakpoint's address space.  On targets that have global
6876    breakpoints, the address space doesn't really matter.  */
6877
6878 static int
6879 breakpoint_location_address_match (struct bp_location *bl,
6880                                    const address_space *aspace,
6881                                    CORE_ADDR addr)
6882 {
6883   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6884                                     aspace, addr)
6885           || (bl->length
6886               && breakpoint_address_match_range (bl->pspace->aspace,
6887                                                  bl->address, bl->length,
6888                                                  aspace, addr)));
6889 }
6890
6891 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
6892    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
6893    match happens only if ASPACE matches the breakpoint's address
6894    space.  On targets that have global breakpoints, the address space
6895    doesn't really matter.  */
6896
6897 static int
6898 breakpoint_location_address_range_overlap (struct bp_location *bl,
6899                                            const address_space *aspace,
6900                                            CORE_ADDR addr, int len)
6901 {
6902   if (gdbarch_has_global_breakpoints (target_gdbarch ())
6903       || bl->pspace->aspace == aspace)
6904     {
6905       int bl_len = bl->length != 0 ? bl->length : 1;
6906
6907       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
6908         return 1;
6909     }
6910   return 0;
6911 }
6912
6913 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6914    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6915    true, otherwise returns false.  */
6916
6917 static int
6918 tracepoint_locations_match (struct bp_location *loc1,
6919                             struct bp_location *loc2)
6920 {
6921   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6922     /* Since tracepoint locations are never duplicated with others', tracepoint
6923        locations at the same address of different tracepoints are regarded as
6924        different locations.  */
6925     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6926   else
6927     return 0;
6928 }
6929
6930 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6931    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6932    represent the same location.  */
6933
6934 static int
6935 breakpoint_locations_match (struct bp_location *loc1, 
6936                             struct bp_location *loc2)
6937 {
6938   int hw_point1, hw_point2;
6939
6940   /* Both of them must not be in moribund_locations.  */
6941   gdb_assert (loc1->owner != NULL);
6942   gdb_assert (loc2->owner != NULL);
6943
6944   hw_point1 = is_hardware_watchpoint (loc1->owner);
6945   hw_point2 = is_hardware_watchpoint (loc2->owner);
6946
6947   if (hw_point1 != hw_point2)
6948     return 0;
6949   else if (hw_point1)
6950     return watchpoint_locations_match (loc1, loc2);
6951   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6952     return tracepoint_locations_match (loc1, loc2);
6953   else
6954     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6955     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6956                                      loc2->pspace->aspace, loc2->address)
6957             && loc1->length == loc2->length);
6958 }
6959
6960 static void
6961 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6962                                int bnum, int have_bnum)
6963 {
6964   /* The longest string possibly returned by hex_string_custom
6965      is 50 chars.  These must be at least that big for safety.  */
6966   char astr1[64];
6967   char astr2[64];
6968
6969   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6970   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6971   if (have_bnum)
6972     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6973              bnum, astr1, astr2);
6974   else
6975     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6976 }
6977
6978 /* Adjust a breakpoint's address to account for architectural
6979    constraints on breakpoint placement.  Return the adjusted address.
6980    Note: Very few targets require this kind of adjustment.  For most
6981    targets, this function is simply the identity function.  */
6982
6983 static CORE_ADDR
6984 adjust_breakpoint_address (struct gdbarch *gdbarch,
6985                            CORE_ADDR bpaddr, enum bptype bptype)
6986 {
6987   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6988     {
6989       /* Very few targets need any kind of breakpoint adjustment.  */
6990       return bpaddr;
6991     }
6992   else if (bptype == bp_watchpoint
6993            || bptype == bp_hardware_watchpoint
6994            || bptype == bp_read_watchpoint
6995            || bptype == bp_access_watchpoint
6996            || bptype == bp_catchpoint)
6997     {
6998       /* Watchpoints and the various bp_catch_* eventpoints should not
6999          have their addresses modified.  */
7000       return bpaddr;
7001     }
7002   else if (bptype == bp_single_step)
7003     {
7004       /* Single-step breakpoints should not have their addresses
7005          modified.  If there's any architectural constrain that
7006          applies to this address, then it should have already been
7007          taken into account when the breakpoint was created in the
7008          first place.  If we didn't do this, stepping through e.g.,
7009          Thumb-2 IT blocks would break.  */
7010       return bpaddr;
7011     }
7012   else
7013     {
7014       CORE_ADDR adjusted_bpaddr;
7015
7016       /* Some targets have architectural constraints on the placement
7017          of breakpoint instructions.  Obtain the adjusted address.  */
7018       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7019
7020       /* An adjusted breakpoint address can significantly alter
7021          a user's expectations.  Print a warning if an adjustment
7022          is required.  */
7023       if (adjusted_bpaddr != bpaddr)
7024         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7025
7026       return adjusted_bpaddr;
7027     }
7028 }
7029
7030 bp_location::bp_location (const bp_location_ops *ops, breakpoint *owner)
7031 {
7032   bp_location *loc = this;
7033
7034   gdb_assert (ops != NULL);
7035
7036   loc->ops = ops;
7037   loc->owner = owner;
7038   loc->cond_bytecode = NULL;
7039   loc->shlib_disabled = 0;
7040   loc->enabled = 1;
7041
7042   switch (owner->type)
7043     {
7044     case bp_breakpoint:
7045     case bp_single_step:
7046     case bp_until:
7047     case bp_finish:
7048     case bp_longjmp:
7049     case bp_longjmp_resume:
7050     case bp_longjmp_call_dummy:
7051     case bp_exception:
7052     case bp_exception_resume:
7053     case bp_step_resume:
7054     case bp_hp_step_resume:
7055     case bp_watchpoint_scope:
7056     case bp_call_dummy:
7057     case bp_std_terminate:
7058     case bp_shlib_event:
7059     case bp_thread_event:
7060     case bp_overlay_event:
7061     case bp_jit_event:
7062     case bp_longjmp_master:
7063     case bp_std_terminate_master:
7064     case bp_exception_master:
7065     case bp_gnu_ifunc_resolver:
7066     case bp_gnu_ifunc_resolver_return:
7067     case bp_dprintf:
7068       loc->loc_type = bp_loc_software_breakpoint;
7069       mark_breakpoint_location_modified (loc);
7070       break;
7071     case bp_hardware_breakpoint:
7072       loc->loc_type = bp_loc_hardware_breakpoint;
7073       mark_breakpoint_location_modified (loc);
7074       break;
7075     case bp_hardware_watchpoint:
7076     case bp_read_watchpoint:
7077     case bp_access_watchpoint:
7078       loc->loc_type = bp_loc_hardware_watchpoint;
7079       break;
7080     case bp_watchpoint:
7081     case bp_catchpoint:
7082     case bp_tracepoint:
7083     case bp_fast_tracepoint:
7084     case bp_static_tracepoint:
7085       loc->loc_type = bp_loc_other;
7086       break;
7087     default:
7088       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7089     }
7090
7091   loc->refc = 1;
7092 }
7093
7094 /* Allocate a struct bp_location.  */
7095
7096 static struct bp_location *
7097 allocate_bp_location (struct breakpoint *bpt)
7098 {
7099   return bpt->ops->allocate_location (bpt);
7100 }
7101
7102 static void
7103 free_bp_location (struct bp_location *loc)
7104 {
7105   loc->ops->dtor (loc);
7106   delete loc;
7107 }
7108
7109 /* Increment reference count.  */
7110
7111 static void
7112 incref_bp_location (struct bp_location *bl)
7113 {
7114   ++bl->refc;
7115 }
7116
7117 /* Decrement reference count.  If the reference count reaches 0,
7118    destroy the bp_location.  Sets *BLP to NULL.  */
7119
7120 static void
7121 decref_bp_location (struct bp_location **blp)
7122 {
7123   gdb_assert ((*blp)->refc > 0);
7124
7125   if (--(*blp)->refc == 0)
7126     free_bp_location (*blp);
7127   *blp = NULL;
7128 }
7129
7130 /* Add breakpoint B at the end of the global breakpoint chain.  */
7131
7132 static breakpoint *
7133 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7134 {
7135   struct breakpoint *b1;
7136   struct breakpoint *result = b.get ();
7137
7138   /* Add this breakpoint to the end of the chain so that a list of
7139      breakpoints will come out in order of increasing numbers.  */
7140
7141   b1 = breakpoint_chain;
7142   if (b1 == 0)
7143     breakpoint_chain = b.release ();
7144   else
7145     {
7146       while (b1->next)
7147         b1 = b1->next;
7148       b1->next = b.release ();
7149     }
7150
7151   return result;
7152 }
7153
7154 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7155
7156 static void
7157 init_raw_breakpoint_without_location (struct breakpoint *b,
7158                                       struct gdbarch *gdbarch,
7159                                       enum bptype bptype,
7160                                       const struct breakpoint_ops *ops)
7161 {
7162   gdb_assert (ops != NULL);
7163
7164   b->ops = ops;
7165   b->type = bptype;
7166   b->gdbarch = gdbarch;
7167   b->language = current_language->la_language;
7168   b->input_radix = input_radix;
7169   b->related_breakpoint = b;
7170 }
7171
7172 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7173    that has type BPTYPE and has no locations as yet.  */
7174
7175 static struct breakpoint *
7176 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7177                                      enum bptype bptype,
7178                                      const struct breakpoint_ops *ops)
7179 {
7180   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7181
7182   init_raw_breakpoint_without_location (b.get (), gdbarch, bptype, ops);
7183   return add_to_breakpoint_chain (std::move (b));
7184 }
7185
7186 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7187    resolutions should be made as the user specified the location explicitly
7188    enough.  */
7189
7190 static void
7191 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7192 {
7193   gdb_assert (loc->owner != NULL);
7194
7195   if (loc->owner->type == bp_breakpoint
7196       || loc->owner->type == bp_hardware_breakpoint
7197       || is_tracepoint (loc->owner))
7198     {
7199       int is_gnu_ifunc;
7200       const char *function_name;
7201       CORE_ADDR func_addr;
7202
7203       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7204                                           &func_addr, NULL, &is_gnu_ifunc);
7205
7206       if (is_gnu_ifunc && !explicit_loc)
7207         {
7208           struct breakpoint *b = loc->owner;
7209
7210           gdb_assert (loc->pspace == current_program_space);
7211           if (gnu_ifunc_resolve_name (function_name,
7212                                       &loc->requested_address))
7213             {
7214               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7215               loc->address = adjust_breakpoint_address (loc->gdbarch,
7216                                                         loc->requested_address,
7217                                                         b->type);
7218             }
7219           else if (b->type == bp_breakpoint && b->loc == loc
7220                    && loc->next == NULL && b->related_breakpoint == b)
7221             {
7222               /* Create only the whole new breakpoint of this type but do not
7223                  mess more complicated breakpoints with multiple locations.  */
7224               b->type = bp_gnu_ifunc_resolver;
7225               /* Remember the resolver's address for use by the return
7226                  breakpoint.  */
7227               loc->related_address = func_addr;
7228             }
7229         }
7230
7231       if (function_name)
7232         loc->function_name = xstrdup (function_name);
7233     }
7234 }
7235
7236 /* Attempt to determine architecture of location identified by SAL.  */
7237 struct gdbarch *
7238 get_sal_arch (struct symtab_and_line sal)
7239 {
7240   if (sal.section)
7241     return get_objfile_arch (sal.section->objfile);
7242   if (sal.symtab)
7243     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7244
7245   return NULL;
7246 }
7247
7248 /* Low level routine for partially initializing a breakpoint of type
7249    BPTYPE.  The newly created breakpoint's address, section, source
7250    file name, and line number are provided by SAL.
7251
7252    It is expected that the caller will complete the initialization of
7253    the newly created breakpoint struct as well as output any status
7254    information regarding the creation of a new breakpoint.  */
7255
7256 static void
7257 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7258                      struct symtab_and_line sal, enum bptype bptype,
7259                      const struct breakpoint_ops *ops)
7260 {
7261   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7262
7263   add_location_to_breakpoint (b, &sal);
7264
7265   if (bptype != bp_catchpoint)
7266     gdb_assert (sal.pspace != NULL);
7267
7268   /* Store the program space that was used to set the breakpoint,
7269      except for ordinary breakpoints, which are independent of the
7270      program space.  */
7271   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7272     b->pspace = sal.pspace;
7273 }
7274
7275 /* set_raw_breakpoint is a low level routine for allocating and
7276    partially initializing a breakpoint of type BPTYPE.  The newly
7277    created breakpoint's address, section, source file name, and line
7278    number are provided by SAL.  The newly created and partially
7279    initialized breakpoint is added to the breakpoint chain and
7280    is also returned as the value of this function.
7281
7282    It is expected that the caller will complete the initialization of
7283    the newly created breakpoint struct as well as output any status
7284    information regarding the creation of a new breakpoint.  In
7285    particular, set_raw_breakpoint does NOT set the breakpoint
7286    number!  Care should be taken to not allow an error to occur
7287    prior to completing the initialization of the breakpoint.  If this
7288    should happen, a bogus breakpoint will be left on the chain.  */
7289
7290 struct breakpoint *
7291 set_raw_breakpoint (struct gdbarch *gdbarch,
7292                     struct symtab_and_line sal, enum bptype bptype,
7293                     const struct breakpoint_ops *ops)
7294 {
7295   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7296
7297   init_raw_breakpoint (b.get (), gdbarch, sal, bptype, ops);
7298   return add_to_breakpoint_chain (std::move (b));
7299 }
7300
7301 /* Call this routine when stepping and nexting to enable a breakpoint
7302    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7303    initiated the operation.  */
7304
7305 void
7306 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7307 {
7308   struct breakpoint *b, *b_tmp;
7309   int thread = tp->global_num;
7310
7311   /* To avoid having to rescan all objfile symbols at every step,
7312      we maintain a list of continually-inserted but always disabled
7313      longjmp "master" breakpoints.  Here, we simply create momentary
7314      clones of those and enable them for the requested thread.  */
7315   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7316     if (b->pspace == current_program_space
7317         && (b->type == bp_longjmp_master
7318             || b->type == bp_exception_master))
7319       {
7320         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7321         struct breakpoint *clone;
7322
7323         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7324            after their removal.  */
7325         clone = momentary_breakpoint_from_master (b, type,
7326                                                   &momentary_breakpoint_ops, 1);
7327         clone->thread = thread;
7328       }
7329
7330   tp->initiating_frame = frame;
7331 }
7332
7333 /* Delete all longjmp breakpoints from THREAD.  */
7334 void
7335 delete_longjmp_breakpoint (int thread)
7336 {
7337   struct breakpoint *b, *b_tmp;
7338
7339   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7340     if (b->type == bp_longjmp || b->type == bp_exception)
7341       {
7342         if (b->thread == thread)
7343           delete_breakpoint (b);
7344       }
7345 }
7346
7347 void
7348 delete_longjmp_breakpoint_at_next_stop (int thread)
7349 {
7350   struct breakpoint *b, *b_tmp;
7351
7352   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7353     if (b->type == bp_longjmp || b->type == bp_exception)
7354       {
7355         if (b->thread == thread)
7356           b->disposition = disp_del_at_next_stop;
7357       }
7358 }
7359
7360 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7361    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7362    pointer to any of them.  Return NULL if this system cannot place longjmp
7363    breakpoints.  */
7364
7365 struct breakpoint *
7366 set_longjmp_breakpoint_for_call_dummy (void)
7367 {
7368   struct breakpoint *b, *retval = NULL;
7369
7370   ALL_BREAKPOINTS (b)
7371     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7372       {
7373         struct breakpoint *new_b;
7374
7375         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7376                                                   &momentary_breakpoint_ops,
7377                                                   1);
7378         new_b->thread = ptid_to_global_thread_id (inferior_ptid);
7379
7380         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7381
7382         gdb_assert (new_b->related_breakpoint == new_b);
7383         if (retval == NULL)
7384           retval = new_b;
7385         new_b->related_breakpoint = retval;
7386         while (retval->related_breakpoint != new_b->related_breakpoint)
7387           retval = retval->related_breakpoint;
7388         retval->related_breakpoint = new_b;
7389       }
7390
7391   return retval;
7392 }
7393
7394 /* Verify all existing dummy frames and their associated breakpoints for
7395    TP.  Remove those which can no longer be found in the current frame
7396    stack.
7397
7398    You should call this function only at places where it is safe to currently
7399    unwind the whole stack.  Failed stack unwind would discard live dummy
7400    frames.  */
7401
7402 void
7403 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7404 {
7405   struct breakpoint *b, *b_tmp;
7406
7407   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7408     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7409       {
7410         struct breakpoint *dummy_b = b->related_breakpoint;
7411
7412         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7413           dummy_b = dummy_b->related_breakpoint;
7414         if (dummy_b->type != bp_call_dummy
7415             || frame_find_by_id (dummy_b->frame_id) != NULL)
7416           continue;
7417         
7418         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7419
7420         while (b->related_breakpoint != b)
7421           {
7422             if (b_tmp == b->related_breakpoint)
7423               b_tmp = b->related_breakpoint->next;
7424             delete_breakpoint (b->related_breakpoint);
7425           }
7426         delete_breakpoint (b);
7427       }
7428 }
7429
7430 void
7431 enable_overlay_breakpoints (void)
7432 {
7433   struct breakpoint *b;
7434
7435   ALL_BREAKPOINTS (b)
7436     if (b->type == bp_overlay_event)
7437     {
7438       b->enable_state = bp_enabled;
7439       update_global_location_list (UGLL_MAY_INSERT);
7440       overlay_events_enabled = 1;
7441     }
7442 }
7443
7444 void
7445 disable_overlay_breakpoints (void)
7446 {
7447   struct breakpoint *b;
7448
7449   ALL_BREAKPOINTS (b)
7450     if (b->type == bp_overlay_event)
7451     {
7452       b->enable_state = bp_disabled;
7453       update_global_location_list (UGLL_DONT_INSERT);
7454       overlay_events_enabled = 0;
7455     }
7456 }
7457
7458 /* Set an active std::terminate breakpoint for each std::terminate
7459    master breakpoint.  */
7460 void
7461 set_std_terminate_breakpoint (void)
7462 {
7463   struct breakpoint *b, *b_tmp;
7464
7465   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7466     if (b->pspace == current_program_space
7467         && b->type == bp_std_terminate_master)
7468       {
7469         momentary_breakpoint_from_master (b, bp_std_terminate,
7470                                           &momentary_breakpoint_ops, 1);
7471       }
7472 }
7473
7474 /* Delete all the std::terminate breakpoints.  */
7475 void
7476 delete_std_terminate_breakpoint (void)
7477 {
7478   struct breakpoint *b, *b_tmp;
7479
7480   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7481     if (b->type == bp_std_terminate)
7482       delete_breakpoint (b);
7483 }
7484
7485 struct breakpoint *
7486 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7487 {
7488   struct breakpoint *b;
7489
7490   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7491                                   &internal_breakpoint_ops);
7492
7493   b->enable_state = bp_enabled;
7494   /* location has to be used or breakpoint_re_set will delete me.  */
7495   b->location = new_address_location (b->loc->address, NULL, 0);
7496
7497   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7498
7499   return b;
7500 }
7501
7502 struct lang_and_radix
7503   {
7504     enum language lang;
7505     int radix;
7506   };
7507
7508 /* Create a breakpoint for JIT code registration and unregistration.  */
7509
7510 struct breakpoint *
7511 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7512 {
7513   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7514                                      &internal_breakpoint_ops);
7515 }
7516
7517 /* Remove JIT code registration and unregistration breakpoint(s).  */
7518
7519 void
7520 remove_jit_event_breakpoints (void)
7521 {
7522   struct breakpoint *b, *b_tmp;
7523
7524   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7525     if (b->type == bp_jit_event
7526         && b->loc->pspace == current_program_space)
7527       delete_breakpoint (b);
7528 }
7529
7530 void
7531 remove_solib_event_breakpoints (void)
7532 {
7533   struct breakpoint *b, *b_tmp;
7534
7535   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7536     if (b->type == bp_shlib_event
7537         && b->loc->pspace == current_program_space)
7538       delete_breakpoint (b);
7539 }
7540
7541 /* See breakpoint.h.  */
7542
7543 void
7544 remove_solib_event_breakpoints_at_next_stop (void)
7545 {
7546   struct breakpoint *b, *b_tmp;
7547
7548   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7549     if (b->type == bp_shlib_event
7550         && b->loc->pspace == current_program_space)
7551       b->disposition = disp_del_at_next_stop;
7552 }
7553
7554 /* Helper for create_solib_event_breakpoint /
7555    create_and_insert_solib_event_breakpoint.  Allows specifying which
7556    INSERT_MODE to pass through to update_global_location_list.  */
7557
7558 static struct breakpoint *
7559 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7560                                  enum ugll_insert_mode insert_mode)
7561 {
7562   struct breakpoint *b;
7563
7564   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7565                                   &internal_breakpoint_ops);
7566   update_global_location_list_nothrow (insert_mode);
7567   return b;
7568 }
7569
7570 struct breakpoint *
7571 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7572 {
7573   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7574 }
7575
7576 /* See breakpoint.h.  */
7577
7578 struct breakpoint *
7579 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7580 {
7581   struct breakpoint *b;
7582
7583   /* Explicitly tell update_global_location_list to insert
7584      locations.  */
7585   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7586   if (!b->loc->inserted)
7587     {
7588       delete_breakpoint (b);
7589       return NULL;
7590     }
7591   return b;
7592 }
7593
7594 /* Disable any breakpoints that are on code in shared libraries.  Only
7595    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7596
7597 void
7598 disable_breakpoints_in_shlibs (void)
7599 {
7600   struct bp_location *loc, **locp_tmp;
7601
7602   ALL_BP_LOCATIONS (loc, locp_tmp)
7603   {
7604     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7605     struct breakpoint *b = loc->owner;
7606
7607     /* We apply the check to all breakpoints, including disabled for
7608        those with loc->duplicate set.  This is so that when breakpoint
7609        becomes enabled, or the duplicate is removed, gdb will try to
7610        insert all breakpoints.  If we don't set shlib_disabled here,
7611        we'll try to insert those breakpoints and fail.  */
7612     if (((b->type == bp_breakpoint)
7613          || (b->type == bp_jit_event)
7614          || (b->type == bp_hardware_breakpoint)
7615          || (is_tracepoint (b)))
7616         && loc->pspace == current_program_space
7617         && !loc->shlib_disabled
7618         && solib_name_from_address (loc->pspace, loc->address)
7619         )
7620       {
7621         loc->shlib_disabled = 1;
7622       }
7623   }
7624 }
7625
7626 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7627    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7628    disabled ones can just stay disabled.  */
7629
7630 static void
7631 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7632 {
7633   struct bp_location *loc, **locp_tmp;
7634   int disabled_shlib_breaks = 0;
7635
7636   ALL_BP_LOCATIONS (loc, locp_tmp)
7637   {
7638     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7639     struct breakpoint *b = loc->owner;
7640
7641     if (solib->pspace == loc->pspace
7642         && !loc->shlib_disabled
7643         && (((b->type == bp_breakpoint
7644               || b->type == bp_jit_event
7645               || b->type == bp_hardware_breakpoint)
7646              && (loc->loc_type == bp_loc_hardware_breakpoint
7647                  || loc->loc_type == bp_loc_software_breakpoint))
7648             || is_tracepoint (b))
7649         && solib_contains_address_p (solib, loc->address))
7650       {
7651         loc->shlib_disabled = 1;
7652         /* At this point, we cannot rely on remove_breakpoint
7653            succeeding so we must mark the breakpoint as not inserted
7654            to prevent future errors occurring in remove_breakpoints.  */
7655         loc->inserted = 0;
7656
7657         /* This may cause duplicate notifications for the same breakpoint.  */
7658         observer_notify_breakpoint_modified (b);
7659
7660         if (!disabled_shlib_breaks)
7661           {
7662             target_terminal::ours_for_output ();
7663             warning (_("Temporarily disabling breakpoints "
7664                        "for unloaded shared library \"%s\""),
7665                      solib->so_name);
7666           }
7667         disabled_shlib_breaks = 1;
7668       }
7669   }
7670 }
7671
7672 /* Disable any breakpoints and tracepoints in OBJFILE upon
7673    notification of free_objfile.  Only apply to enabled breakpoints,
7674    disabled ones can just stay disabled.  */
7675
7676 static void
7677 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7678 {
7679   struct breakpoint *b;
7680
7681   if (objfile == NULL)
7682     return;
7683
7684   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7685      managed by the user with add-symbol-file/remove-symbol-file.
7686      Similarly to how breakpoints in shared libraries are handled in
7687      response to "nosharedlibrary", mark breakpoints in such modules
7688      shlib_disabled so they end up uninserted on the next global
7689      location list update.  Shared libraries not loaded by the user
7690      aren't handled here -- they're already handled in
7691      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7692      solib_unloaded observer.  We skip objfiles that are not
7693      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7694      main objfile).  */
7695   if ((objfile->flags & OBJF_SHARED) == 0
7696       || (objfile->flags & OBJF_USERLOADED) == 0)
7697     return;
7698
7699   ALL_BREAKPOINTS (b)
7700     {
7701       struct bp_location *loc;
7702       int bp_modified = 0;
7703
7704       if (!is_breakpoint (b) && !is_tracepoint (b))
7705         continue;
7706
7707       for (loc = b->loc; loc != NULL; loc = loc->next)
7708         {
7709           CORE_ADDR loc_addr = loc->address;
7710
7711           if (loc->loc_type != bp_loc_hardware_breakpoint
7712               && loc->loc_type != bp_loc_software_breakpoint)
7713             continue;
7714
7715           if (loc->shlib_disabled != 0)
7716             continue;
7717
7718           if (objfile->pspace != loc->pspace)
7719             continue;
7720
7721           if (loc->loc_type != bp_loc_hardware_breakpoint
7722               && loc->loc_type != bp_loc_software_breakpoint)
7723             continue;
7724
7725           if (is_addr_in_objfile (loc_addr, objfile))
7726             {
7727               loc->shlib_disabled = 1;
7728               /* At this point, we don't know whether the object was
7729                  unmapped from the inferior or not, so leave the
7730                  inserted flag alone.  We'll handle failure to
7731                  uninsert quietly, in case the object was indeed
7732                  unmapped.  */
7733
7734               mark_breakpoint_location_modified (loc);
7735
7736               bp_modified = 1;
7737             }
7738         }
7739
7740       if (bp_modified)
7741         observer_notify_breakpoint_modified (b);
7742     }
7743 }
7744
7745 /* FORK & VFORK catchpoints.  */
7746
7747 /* An instance of this type is used to represent a fork or vfork
7748    catchpoint.  A breakpoint is really of this type iff its ops pointer points
7749    to CATCH_FORK_BREAKPOINT_OPS.  */
7750
7751 struct fork_catchpoint : public breakpoint
7752 {
7753   /* Process id of a child process whose forking triggered this
7754      catchpoint.  This field is only valid immediately after this
7755      catchpoint has triggered.  */
7756   ptid_t forked_inferior_pid;
7757 };
7758
7759 /* Implement the "insert" breakpoint_ops method for fork
7760    catchpoints.  */
7761
7762 static int
7763 insert_catch_fork (struct bp_location *bl)
7764 {
7765   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7766 }
7767
7768 /* Implement the "remove" breakpoint_ops method for fork
7769    catchpoints.  */
7770
7771 static int
7772 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
7773 {
7774   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7775 }
7776
7777 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7778    catchpoints.  */
7779
7780 static int
7781 breakpoint_hit_catch_fork (const struct bp_location *bl,
7782                            const address_space *aspace, CORE_ADDR bp_addr,
7783                            const struct target_waitstatus *ws)
7784 {
7785   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7786
7787   if (ws->kind != TARGET_WAITKIND_FORKED)
7788     return 0;
7789
7790   c->forked_inferior_pid = ws->value.related_pid;
7791   return 1;
7792 }
7793
7794 /* Implement the "print_it" breakpoint_ops method for fork
7795    catchpoints.  */
7796
7797 static enum print_stop_action
7798 print_it_catch_fork (bpstat bs)
7799 {
7800   struct ui_out *uiout = current_uiout;
7801   struct breakpoint *b = bs->breakpoint_at;
7802   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7803
7804   annotate_catchpoint (b->number);
7805   maybe_print_thread_hit_breakpoint (uiout);
7806   if (b->disposition == disp_del)
7807     uiout->text ("Temporary catchpoint ");
7808   else
7809     uiout->text ("Catchpoint ");
7810   if (uiout->is_mi_like_p ())
7811     {
7812       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
7813       uiout->field_string ("disp", bpdisp_text (b->disposition));
7814     }
7815   uiout->field_int ("bkptno", b->number);
7816   uiout->text (" (forked process ");
7817   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
7818   uiout->text ("), ");
7819   return PRINT_SRC_AND_LOC;
7820 }
7821
7822 /* Implement the "print_one" breakpoint_ops method for fork
7823    catchpoints.  */
7824
7825 static void
7826 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7827 {
7828   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7829   struct value_print_options opts;
7830   struct ui_out *uiout = current_uiout;
7831
7832   get_user_print_options (&opts);
7833
7834   /* Field 4, the address, is omitted (which makes the columns not
7835      line up too nicely with the headers, but the effect is relatively
7836      readable).  */
7837   if (opts.addressprint)
7838     uiout->field_skip ("addr");
7839   annotate_field (5);
7840   uiout->text ("fork");
7841   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7842     {
7843       uiout->text (", process ");
7844       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
7845       uiout->spaces (1);
7846     }
7847
7848   if (uiout->is_mi_like_p ())
7849     uiout->field_string ("catch-type", "fork");
7850 }
7851
7852 /* Implement the "print_mention" breakpoint_ops method for fork
7853    catchpoints.  */
7854
7855 static void
7856 print_mention_catch_fork (struct breakpoint *b)
7857 {
7858   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7859 }
7860
7861 /* Implement the "print_recreate" breakpoint_ops method for fork
7862    catchpoints.  */
7863
7864 static void
7865 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7866 {
7867   fprintf_unfiltered (fp, "catch fork");
7868   print_recreate_thread (b, fp);
7869 }
7870
7871 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7872
7873 static struct breakpoint_ops catch_fork_breakpoint_ops;
7874
7875 /* Implement the "insert" breakpoint_ops method for vfork
7876    catchpoints.  */
7877
7878 static int
7879 insert_catch_vfork (struct bp_location *bl)
7880 {
7881   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7882 }
7883
7884 /* Implement the "remove" breakpoint_ops method for vfork
7885    catchpoints.  */
7886
7887 static int
7888 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
7889 {
7890   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7891 }
7892
7893 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7894    catchpoints.  */
7895
7896 static int
7897 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7898                             const address_space *aspace, CORE_ADDR bp_addr,
7899                             const struct target_waitstatus *ws)
7900 {
7901   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7902
7903   if (ws->kind != TARGET_WAITKIND_VFORKED)
7904     return 0;
7905
7906   c->forked_inferior_pid = ws->value.related_pid;
7907   return 1;
7908 }
7909
7910 /* Implement the "print_it" breakpoint_ops method for vfork
7911    catchpoints.  */
7912
7913 static enum print_stop_action
7914 print_it_catch_vfork (bpstat bs)
7915 {
7916   struct ui_out *uiout = current_uiout;
7917   struct breakpoint *b = bs->breakpoint_at;
7918   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7919
7920   annotate_catchpoint (b->number);
7921   maybe_print_thread_hit_breakpoint (uiout);
7922   if (b->disposition == disp_del)
7923     uiout->text ("Temporary catchpoint ");
7924   else
7925     uiout->text ("Catchpoint ");
7926   if (uiout->is_mi_like_p ())
7927     {
7928       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
7929       uiout->field_string ("disp", bpdisp_text (b->disposition));
7930     }
7931   uiout->field_int ("bkptno", b->number);
7932   uiout->text (" (vforked process ");
7933   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
7934   uiout->text ("), ");
7935   return PRINT_SRC_AND_LOC;
7936 }
7937
7938 /* Implement the "print_one" breakpoint_ops method for vfork
7939    catchpoints.  */
7940
7941 static void
7942 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7943 {
7944   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7945   struct value_print_options opts;
7946   struct ui_out *uiout = current_uiout;
7947
7948   get_user_print_options (&opts);
7949   /* Field 4, the address, is omitted (which makes the columns not
7950      line up too nicely with the headers, but the effect is relatively
7951      readable).  */
7952   if (opts.addressprint)
7953     uiout->field_skip ("addr");
7954   annotate_field (5);
7955   uiout->text ("vfork");
7956   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7957     {
7958       uiout->text (", process ");
7959       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
7960       uiout->spaces (1);
7961     }
7962
7963   if (uiout->is_mi_like_p ())
7964     uiout->field_string ("catch-type", "vfork");
7965 }
7966
7967 /* Implement the "print_mention" breakpoint_ops method for vfork
7968    catchpoints.  */
7969
7970 static void
7971 print_mention_catch_vfork (struct breakpoint *b)
7972 {
7973   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7974 }
7975
7976 /* Implement the "print_recreate" breakpoint_ops method for vfork
7977    catchpoints.  */
7978
7979 static void
7980 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7981 {
7982   fprintf_unfiltered (fp, "catch vfork");
7983   print_recreate_thread (b, fp);
7984 }
7985
7986 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7987
7988 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7989
7990 /* An instance of this type is used to represent an solib catchpoint.
7991    A breakpoint is really of this type iff its ops pointer points to
7992    CATCH_SOLIB_BREAKPOINT_OPS.  */
7993
7994 struct solib_catchpoint : public breakpoint
7995 {
7996   ~solib_catchpoint () override;
7997
7998   /* True for "catch load", false for "catch unload".  */
7999   unsigned char is_load;
8000
8001   /* Regular expression to match, if any.  COMPILED is only valid when
8002      REGEX is non-NULL.  */
8003   char *regex;
8004   std::unique_ptr<compiled_regex> compiled;
8005 };
8006
8007 solib_catchpoint::~solib_catchpoint ()
8008 {
8009   xfree (this->regex);
8010 }
8011
8012 static int
8013 insert_catch_solib (struct bp_location *ignore)
8014 {
8015   return 0;
8016 }
8017
8018 static int
8019 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
8020 {
8021   return 0;
8022 }
8023
8024 static int
8025 breakpoint_hit_catch_solib (const struct bp_location *bl,
8026                             const address_space *aspace,
8027                             CORE_ADDR bp_addr,
8028                             const struct target_waitstatus *ws)
8029 {
8030   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8031   struct breakpoint *other;
8032
8033   if (ws->kind == TARGET_WAITKIND_LOADED)
8034     return 1;
8035
8036   ALL_BREAKPOINTS (other)
8037   {
8038     struct bp_location *other_bl;
8039
8040     if (other == bl->owner)
8041       continue;
8042
8043     if (other->type != bp_shlib_event)
8044       continue;
8045
8046     if (self->pspace != NULL && other->pspace != self->pspace)
8047       continue;
8048
8049     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8050       {
8051         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8052           return 1;
8053       }
8054   }
8055
8056   return 0;
8057 }
8058
8059 static void
8060 check_status_catch_solib (struct bpstats *bs)
8061 {
8062   struct solib_catchpoint *self
8063     = (struct solib_catchpoint *) bs->breakpoint_at;
8064   int ix;
8065
8066   if (self->is_load)
8067     {
8068       struct so_list *iter;
8069
8070       for (ix = 0;
8071            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8072                         ix, iter);
8073            ++ix)
8074         {
8075           if (!self->regex
8076               || self->compiled->exec (iter->so_name, 0, NULL, 0) == 0)
8077             return;
8078         }
8079     }
8080   else
8081     {
8082       char *iter;
8083
8084       for (ix = 0;
8085            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8086                         ix, iter);
8087            ++ix)
8088         {
8089           if (!self->regex
8090               || self->compiled->exec (iter, 0, NULL, 0) == 0)
8091             return;
8092         }
8093     }
8094
8095   bs->stop = 0;
8096   bs->print_it = print_it_noop;
8097 }
8098
8099 static enum print_stop_action
8100 print_it_catch_solib (bpstat bs)
8101 {
8102   struct breakpoint *b = bs->breakpoint_at;
8103   struct ui_out *uiout = current_uiout;
8104
8105   annotate_catchpoint (b->number);
8106   maybe_print_thread_hit_breakpoint (uiout);
8107   if (b->disposition == disp_del)
8108     uiout->text ("Temporary catchpoint ");
8109   else
8110     uiout->text ("Catchpoint ");
8111   uiout->field_int ("bkptno", b->number);
8112   uiout->text ("\n");
8113   if (uiout->is_mi_like_p ())
8114     uiout->field_string ("disp", bpdisp_text (b->disposition));
8115   print_solib_event (1);
8116   return PRINT_SRC_AND_LOC;
8117 }
8118
8119 static void
8120 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8121 {
8122   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8123   struct value_print_options opts;
8124   struct ui_out *uiout = current_uiout;
8125   char *msg;
8126
8127   get_user_print_options (&opts);
8128   /* Field 4, the address, is omitted (which makes the columns not
8129      line up too nicely with the headers, but the effect is relatively
8130      readable).  */
8131   if (opts.addressprint)
8132     {
8133       annotate_field (4);
8134       uiout->field_skip ("addr");
8135     }
8136
8137   annotate_field (5);
8138   if (self->is_load)
8139     {
8140       if (self->regex)
8141         msg = xstrprintf (_("load of library matching %s"), self->regex);
8142       else
8143         msg = xstrdup (_("load of library"));
8144     }
8145   else
8146     {
8147       if (self->regex)
8148         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8149       else
8150         msg = xstrdup (_("unload of library"));
8151     }
8152   uiout->field_string ("what", msg);
8153   xfree (msg);
8154
8155   if (uiout->is_mi_like_p ())
8156     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8157 }
8158
8159 static void
8160 print_mention_catch_solib (struct breakpoint *b)
8161 {
8162   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8163
8164   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8165                    self->is_load ? "load" : "unload");
8166 }
8167
8168 static void
8169 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8170 {
8171   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8172
8173   fprintf_unfiltered (fp, "%s %s",
8174                       b->disposition == disp_del ? "tcatch" : "catch",
8175                       self->is_load ? "load" : "unload");
8176   if (self->regex)
8177     fprintf_unfiltered (fp, " %s", self->regex);
8178   fprintf_unfiltered (fp, "\n");
8179 }
8180
8181 static struct breakpoint_ops catch_solib_breakpoint_ops;
8182
8183 /* Shared helper function (MI and CLI) for creating and installing
8184    a shared object event catchpoint.  If IS_LOAD is non-zero then
8185    the events to be caught are load events, otherwise they are
8186    unload events.  If IS_TEMP is non-zero the catchpoint is a
8187    temporary one.  If ENABLED is non-zero the catchpoint is
8188    created in an enabled state.  */
8189
8190 void
8191 add_solib_catchpoint (const char *arg, int is_load, int is_temp, int enabled)
8192 {
8193   struct gdbarch *gdbarch = get_current_arch ();
8194
8195   if (!arg)
8196     arg = "";
8197   arg = skip_spaces (arg);
8198
8199   std::unique_ptr<solib_catchpoint> c (new solib_catchpoint ());
8200
8201   if (*arg != '\0')
8202     {
8203       c->compiled.reset (new compiled_regex (arg, REG_NOSUB,
8204                                              _("Invalid regexp")));
8205       c->regex = xstrdup (arg);
8206     }
8207
8208   c->is_load = is_load;
8209   init_catchpoint (c.get (), gdbarch, is_temp, NULL,
8210                    &catch_solib_breakpoint_ops);
8211
8212   c->enable_state = enabled ? bp_enabled : bp_disabled;
8213
8214   install_breakpoint (0, std::move (c), 1);
8215 }
8216
8217 /* A helper function that does all the work for "catch load" and
8218    "catch unload".  */
8219
8220 static void
8221 catch_load_or_unload (const char *arg, int from_tty, int is_load,
8222                       struct cmd_list_element *command)
8223 {
8224   int tempflag;
8225   const int enabled = 1;
8226
8227   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8228
8229   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8230 }
8231
8232 static void
8233 catch_load_command_1 (const char *arg, int from_tty,
8234                       struct cmd_list_element *command)
8235 {
8236   catch_load_or_unload (arg, from_tty, 1, command);
8237 }
8238
8239 static void
8240 catch_unload_command_1 (const char *arg, int from_tty,
8241                         struct cmd_list_element *command)
8242 {
8243   catch_load_or_unload (arg, from_tty, 0, command);
8244 }
8245
8246 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8247    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8248    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8249    the breakpoint_ops structure associated to the catchpoint.  */
8250
8251 void
8252 init_catchpoint (struct breakpoint *b,
8253                  struct gdbarch *gdbarch, int tempflag,
8254                  const char *cond_string,
8255                  const struct breakpoint_ops *ops)
8256 {
8257   symtab_and_line sal;
8258   sal.pspace = current_program_space;
8259
8260   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8261
8262   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8263   b->disposition = tempflag ? disp_del : disp_donttouch;
8264 }
8265
8266 void
8267 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8268 {
8269   breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8270   set_breakpoint_number (internal, b);
8271   if (is_tracepoint (b))
8272     set_tracepoint_count (breakpoint_count);
8273   if (!internal)
8274     mention (b);
8275   observer_notify_breakpoint_created (b);
8276
8277   if (update_gll)
8278     update_global_location_list (UGLL_MAY_INSERT);
8279 }
8280
8281 static void
8282 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8283                                     int tempflag, const char *cond_string,
8284                                     const struct breakpoint_ops *ops)
8285 {
8286   std::unique_ptr<fork_catchpoint> c (new fork_catchpoint ());
8287
8288   init_catchpoint (c.get (), gdbarch, tempflag, cond_string, ops);
8289
8290   c->forked_inferior_pid = null_ptid;
8291
8292   install_breakpoint (0, std::move (c), 1);
8293 }
8294
8295 /* Exec catchpoints.  */
8296
8297 /* An instance of this type is used to represent an exec catchpoint.
8298    A breakpoint is really of this type iff its ops pointer points to
8299    CATCH_EXEC_BREAKPOINT_OPS.  */
8300
8301 struct exec_catchpoint : public breakpoint
8302 {
8303   ~exec_catchpoint () override;
8304
8305   /* Filename of a program whose exec triggered this catchpoint.
8306      This field is only valid immediately after this catchpoint has
8307      triggered.  */
8308   char *exec_pathname;
8309 };
8310
8311 /* Exec catchpoint destructor.  */
8312
8313 exec_catchpoint::~exec_catchpoint ()
8314 {
8315   xfree (this->exec_pathname);
8316 }
8317
8318 static int
8319 insert_catch_exec (struct bp_location *bl)
8320 {
8321   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8322 }
8323
8324 static int
8325 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8326 {
8327   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8328 }
8329
8330 static int
8331 breakpoint_hit_catch_exec (const struct bp_location *bl,
8332                            const address_space *aspace, CORE_ADDR bp_addr,
8333                            const struct target_waitstatus *ws)
8334 {
8335   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8336
8337   if (ws->kind != TARGET_WAITKIND_EXECD)
8338     return 0;
8339
8340   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8341   return 1;
8342 }
8343
8344 static enum print_stop_action
8345 print_it_catch_exec (bpstat bs)
8346 {
8347   struct ui_out *uiout = current_uiout;
8348   struct breakpoint *b = bs->breakpoint_at;
8349   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8350
8351   annotate_catchpoint (b->number);
8352   maybe_print_thread_hit_breakpoint (uiout);
8353   if (b->disposition == disp_del)
8354     uiout->text ("Temporary catchpoint ");
8355   else
8356     uiout->text ("Catchpoint ");
8357   if (uiout->is_mi_like_p ())
8358     {
8359       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8360       uiout->field_string ("disp", bpdisp_text (b->disposition));
8361     }
8362   uiout->field_int ("bkptno", b->number);
8363   uiout->text (" (exec'd ");
8364   uiout->field_string ("new-exec", c->exec_pathname);
8365   uiout->text ("), ");
8366
8367   return PRINT_SRC_AND_LOC;
8368 }
8369
8370 static void
8371 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8372 {
8373   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8374   struct value_print_options opts;
8375   struct ui_out *uiout = current_uiout;
8376
8377   get_user_print_options (&opts);
8378
8379   /* Field 4, the address, is omitted (which makes the columns
8380      not line up too nicely with the headers, but the effect
8381      is relatively readable).  */
8382   if (opts.addressprint)
8383     uiout->field_skip ("addr");
8384   annotate_field (5);
8385   uiout->text ("exec");
8386   if (c->exec_pathname != NULL)
8387     {
8388       uiout->text (", program \"");
8389       uiout->field_string ("what", c->exec_pathname);
8390       uiout->text ("\" ");
8391     }
8392
8393   if (uiout->is_mi_like_p ())
8394     uiout->field_string ("catch-type", "exec");
8395 }
8396
8397 static void
8398 print_mention_catch_exec (struct breakpoint *b)
8399 {
8400   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8401 }
8402
8403 /* Implement the "print_recreate" breakpoint_ops method for exec
8404    catchpoints.  */
8405
8406 static void
8407 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8408 {
8409   fprintf_unfiltered (fp, "catch exec");
8410   print_recreate_thread (b, fp);
8411 }
8412
8413 static struct breakpoint_ops catch_exec_breakpoint_ops;
8414
8415 static int
8416 hw_breakpoint_used_count (void)
8417 {
8418   int i = 0;
8419   struct breakpoint *b;
8420   struct bp_location *bl;
8421
8422   ALL_BREAKPOINTS (b)
8423   {
8424     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8425       for (bl = b->loc; bl; bl = bl->next)
8426         {
8427           /* Special types of hardware breakpoints may use more than
8428              one register.  */
8429           i += b->ops->resources_needed (bl);
8430         }
8431   }
8432
8433   return i;
8434 }
8435
8436 /* Returns the resources B would use if it were a hardware
8437    watchpoint.  */
8438
8439 static int
8440 hw_watchpoint_use_count (struct breakpoint *b)
8441 {
8442   int i = 0;
8443   struct bp_location *bl;
8444
8445   if (!breakpoint_enabled (b))
8446     return 0;
8447
8448   for (bl = b->loc; bl; bl = bl->next)
8449     {
8450       /* Special types of hardware watchpoints may use more than
8451          one register.  */
8452       i += b->ops->resources_needed (bl);
8453     }
8454
8455   return i;
8456 }
8457
8458 /* Returns the sum the used resources of all hardware watchpoints of
8459    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8460    the sum of the used resources of all hardware watchpoints of other
8461    types _not_ TYPE.  */
8462
8463 static int
8464 hw_watchpoint_used_count_others (struct breakpoint *except,
8465                                  enum bptype type, int *other_type_used)
8466 {
8467   int i = 0;
8468   struct breakpoint *b;
8469
8470   *other_type_used = 0;
8471   ALL_BREAKPOINTS (b)
8472     {
8473       if (b == except)
8474         continue;
8475       if (!breakpoint_enabled (b))
8476         continue;
8477
8478       if (b->type == type)
8479         i += hw_watchpoint_use_count (b);
8480       else if (is_hardware_watchpoint (b))
8481         *other_type_used = 1;
8482     }
8483
8484   return i;
8485 }
8486
8487 void
8488 disable_watchpoints_before_interactive_call_start (void)
8489 {
8490   struct breakpoint *b;
8491
8492   ALL_BREAKPOINTS (b)
8493   {
8494     if (is_watchpoint (b) && breakpoint_enabled (b))
8495       {
8496         b->enable_state = bp_call_disabled;
8497         update_global_location_list (UGLL_DONT_INSERT);
8498       }
8499   }
8500 }
8501
8502 void
8503 enable_watchpoints_after_interactive_call_stop (void)
8504 {
8505   struct breakpoint *b;
8506
8507   ALL_BREAKPOINTS (b)
8508   {
8509     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8510       {
8511         b->enable_state = bp_enabled;
8512         update_global_location_list (UGLL_MAY_INSERT);
8513       }
8514   }
8515 }
8516
8517 void
8518 disable_breakpoints_before_startup (void)
8519 {
8520   current_program_space->executing_startup = 1;
8521   update_global_location_list (UGLL_DONT_INSERT);
8522 }
8523
8524 void
8525 enable_breakpoints_after_startup (void)
8526 {
8527   current_program_space->executing_startup = 0;
8528   breakpoint_re_set ();
8529 }
8530
8531 /* Create a new single-step breakpoint for thread THREAD, with no
8532    locations.  */
8533
8534 static struct breakpoint *
8535 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8536 {
8537   std::unique_ptr<breakpoint> b (new breakpoint ());
8538
8539   init_raw_breakpoint_without_location (b.get (), gdbarch, bp_single_step,
8540                                         &momentary_breakpoint_ops);
8541
8542   b->disposition = disp_donttouch;
8543   b->frame_id = null_frame_id;
8544
8545   b->thread = thread;
8546   gdb_assert (b->thread != 0);
8547
8548   return add_to_breakpoint_chain (std::move (b));
8549 }
8550
8551 /* Set a momentary breakpoint of type TYPE at address specified by
8552    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8553    frame.  */
8554
8555 breakpoint_up
8556 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8557                           struct frame_id frame_id, enum bptype type)
8558 {
8559   struct breakpoint *b;
8560
8561   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8562      tail-called one.  */
8563   gdb_assert (!frame_id_artificial_p (frame_id));
8564
8565   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8566   b->enable_state = bp_enabled;
8567   b->disposition = disp_donttouch;
8568   b->frame_id = frame_id;
8569
8570   /* If we're debugging a multi-threaded program, then we want
8571      momentary breakpoints to be active in only a single thread of
8572      control.  */
8573   if (in_thread_list (inferior_ptid))
8574     b->thread = ptid_to_global_thread_id (inferior_ptid);
8575
8576   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8577
8578   return breakpoint_up (b);
8579 }
8580
8581 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8582    The new breakpoint will have type TYPE, use OPS as its
8583    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8584
8585 static struct breakpoint *
8586 momentary_breakpoint_from_master (struct breakpoint *orig,
8587                                   enum bptype type,
8588                                   const struct breakpoint_ops *ops,
8589                                   int loc_enabled)
8590 {
8591   struct breakpoint *copy;
8592
8593   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8594   copy->loc = allocate_bp_location (copy);
8595   set_breakpoint_location_function (copy->loc, 1);
8596
8597   copy->loc->gdbarch = orig->loc->gdbarch;
8598   copy->loc->requested_address = orig->loc->requested_address;
8599   copy->loc->address = orig->loc->address;
8600   copy->loc->section = orig->loc->section;
8601   copy->loc->pspace = orig->loc->pspace;
8602   copy->loc->probe = orig->loc->probe;
8603   copy->loc->line_number = orig->loc->line_number;
8604   copy->loc->symtab = orig->loc->symtab;
8605   copy->loc->enabled = loc_enabled;
8606   copy->frame_id = orig->frame_id;
8607   copy->thread = orig->thread;
8608   copy->pspace = orig->pspace;
8609
8610   copy->enable_state = bp_enabled;
8611   copy->disposition = disp_donttouch;
8612   copy->number = internal_breakpoint_number--;
8613
8614   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8615   return copy;
8616 }
8617
8618 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8619    ORIG is NULL.  */
8620
8621 struct breakpoint *
8622 clone_momentary_breakpoint (struct breakpoint *orig)
8623 {
8624   /* If there's nothing to clone, then return nothing.  */
8625   if (orig == NULL)
8626     return NULL;
8627
8628   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8629 }
8630
8631 breakpoint_up
8632 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8633                                 enum bptype type)
8634 {
8635   struct symtab_and_line sal;
8636
8637   sal = find_pc_line (pc, 0);
8638   sal.pc = pc;
8639   sal.section = find_pc_overlay (pc);
8640   sal.explicit_pc = 1;
8641
8642   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8643 }
8644 \f
8645
8646 /* Tell the user we have just set a breakpoint B.  */
8647
8648 static void
8649 mention (struct breakpoint *b)
8650 {
8651   b->ops->print_mention (b);
8652   if (current_uiout->is_mi_like_p ())
8653     return;
8654   printf_filtered ("\n");
8655 }
8656 \f
8657
8658 static int bp_loc_is_permanent (struct bp_location *loc);
8659
8660 static struct bp_location *
8661 add_location_to_breakpoint (struct breakpoint *b,
8662                             const struct symtab_and_line *sal)
8663 {
8664   struct bp_location *loc, **tmp;
8665   CORE_ADDR adjusted_address;
8666   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8667
8668   if (loc_gdbarch == NULL)
8669     loc_gdbarch = b->gdbarch;
8670
8671   /* Adjust the breakpoint's address prior to allocating a location.
8672      Once we call allocate_bp_location(), that mostly uninitialized
8673      location will be placed on the location chain.  Adjustment of the
8674      breakpoint may cause target_read_memory() to be called and we do
8675      not want its scan of the location chain to find a breakpoint and
8676      location that's only been partially initialized.  */
8677   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8678                                                 sal->pc, b->type);
8679
8680   /* Sort the locations by their ADDRESS.  */
8681   loc = allocate_bp_location (b);
8682   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8683        tmp = &((*tmp)->next))
8684     ;
8685   loc->next = *tmp;
8686   *tmp = loc;
8687
8688   loc->requested_address = sal->pc;
8689   loc->address = adjusted_address;
8690   loc->pspace = sal->pspace;
8691   loc->probe.prob = sal->prob;
8692   loc->probe.objfile = sal->objfile;
8693   gdb_assert (loc->pspace != NULL);
8694   loc->section = sal->section;
8695   loc->gdbarch = loc_gdbarch;
8696   loc->line_number = sal->line;
8697   loc->symtab = sal->symtab;
8698   loc->symbol = sal->symbol;
8699
8700   set_breakpoint_location_function (loc,
8701                                     sal->explicit_pc || sal->explicit_line);
8702
8703   /* While by definition, permanent breakpoints are already present in the
8704      code, we don't mark the location as inserted.  Normally one would expect
8705      that GDB could rely on that breakpoint instruction to stop the program,
8706      thus removing the need to insert its own breakpoint, except that executing
8707      the breakpoint instruction can kill the target instead of reporting a
8708      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8709      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8710      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8711      breakpoint be inserted normally results in QEMU knowing about the GDB
8712      breakpoint, and thus trap before the breakpoint instruction is executed.
8713      (If GDB later needs to continue execution past the permanent breakpoint,
8714      it manually increments the PC, thus avoiding executing the breakpoint
8715      instruction.)  */
8716   if (bp_loc_is_permanent (loc))
8717     loc->permanent = 1;
8718
8719   return loc;
8720 }
8721 \f
8722
8723 /* See breakpoint.h.  */
8724
8725 int
8726 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
8727 {
8728   int len;
8729   CORE_ADDR addr;
8730   const gdb_byte *bpoint;
8731   gdb_byte *target_mem;
8732
8733   addr = address;
8734   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
8735
8736   /* Software breakpoints unsupported?  */
8737   if (bpoint == NULL)
8738     return 0;
8739
8740   target_mem = (gdb_byte *) alloca (len);
8741
8742   /* Enable the automatic memory restoration from breakpoints while
8743      we read the memory.  Otherwise we could say about our temporary
8744      breakpoints they are permanent.  */
8745   scoped_restore restore_memory
8746     = make_scoped_restore_show_memory_breakpoints (0);
8747
8748   if (target_read_memory (address, target_mem, len) == 0
8749       && memcmp (target_mem, bpoint, len) == 0)
8750     return 1;
8751
8752   return 0;
8753 }
8754
8755 /* Return 1 if LOC is pointing to a permanent breakpoint,
8756    return 0 otherwise.  */
8757
8758 static int
8759 bp_loc_is_permanent (struct bp_location *loc)
8760 {
8761   gdb_assert (loc != NULL);
8762
8763   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
8764      attempt to read from the addresses the locations of these breakpoint types
8765      point to.  program_breakpoint_here_p, below, will attempt to read
8766      memory.  */
8767   if (!breakpoint_address_is_meaningful (loc->owner))
8768     return 0;
8769
8770   scoped_restore_current_pspace_and_thread restore_pspace_thread;
8771   switch_to_program_space_and_thread (loc->pspace);
8772   return program_breakpoint_here_p (loc->gdbarch, loc->address);
8773 }
8774
8775 /* Build a command list for the dprintf corresponding to the current
8776    settings of the dprintf style options.  */
8777
8778 static void
8779 update_dprintf_command_list (struct breakpoint *b)
8780 {
8781   char *dprintf_args = b->extra_string;
8782   char *printf_line = NULL;
8783
8784   if (!dprintf_args)
8785     return;
8786
8787   dprintf_args = skip_spaces (dprintf_args);
8788
8789   /* Allow a comma, as it may have terminated a location, but don't
8790      insist on it.  */
8791   if (*dprintf_args == ',')
8792     ++dprintf_args;
8793   dprintf_args = skip_spaces (dprintf_args);
8794
8795   if (*dprintf_args != '"')
8796     error (_("Bad format string, missing '\"'."));
8797
8798   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8799     printf_line = xstrprintf ("printf %s", dprintf_args);
8800   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8801     {
8802       if (!dprintf_function)
8803         error (_("No function supplied for dprintf call"));
8804
8805       if (dprintf_channel && strlen (dprintf_channel) > 0)
8806         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8807                                   dprintf_function,
8808                                   dprintf_channel,
8809                                   dprintf_args);
8810       else
8811         printf_line = xstrprintf ("call (void) %s (%s)",
8812                                   dprintf_function,
8813                                   dprintf_args);
8814     }
8815   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8816     {
8817       if (target_can_run_breakpoint_commands ())
8818         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8819       else
8820         {
8821           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8822           printf_line = xstrprintf ("printf %s", dprintf_args);
8823         }
8824     }
8825   else
8826     internal_error (__FILE__, __LINE__,
8827                     _("Invalid dprintf style."));
8828
8829   gdb_assert (printf_line != NULL);
8830   /* Manufacture a printf sequence.  */
8831   {
8832     struct command_line *printf_cmd_line = XNEW (struct command_line);
8833
8834     printf_cmd_line->control_type = simple_control;
8835     printf_cmd_line->body_count = 0;
8836     printf_cmd_line->body_list = NULL;
8837     printf_cmd_line->next = NULL;
8838     printf_cmd_line->line = printf_line;
8839
8840     breakpoint_set_commands (b, command_line_up (printf_cmd_line));
8841   }
8842 }
8843
8844 /* Update all dprintf commands, making their command lists reflect
8845    current style settings.  */
8846
8847 static void
8848 update_dprintf_commands (const char *args, int from_tty,
8849                          struct cmd_list_element *c)
8850 {
8851   struct breakpoint *b;
8852
8853   ALL_BREAKPOINTS (b)
8854     {
8855       if (b->type == bp_dprintf)
8856         update_dprintf_command_list (b);
8857     }
8858 }
8859
8860 /* Create a breakpoint with SAL as location.  Use LOCATION
8861    as a description of the location, and COND_STRING
8862    as condition expression.  If LOCATION is NULL then create an
8863    "address location" from the address in the SAL.  */
8864
8865 static void
8866 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8867                      gdb::array_view<const symtab_and_line> sals,
8868                      event_location_up &&location,
8869                      gdb::unique_xmalloc_ptr<char> filter,
8870                      gdb::unique_xmalloc_ptr<char> cond_string,
8871                      gdb::unique_xmalloc_ptr<char> extra_string,
8872                      enum bptype type, enum bpdisp disposition,
8873                      int thread, int task, int ignore_count,
8874                      const struct breakpoint_ops *ops, int from_tty,
8875                      int enabled, int internal, unsigned flags,
8876                      int display_canonical)
8877 {
8878   int i;
8879
8880   if (type == bp_hardware_breakpoint)
8881     {
8882       int target_resources_ok;
8883
8884       i = hw_breakpoint_used_count ();
8885       target_resources_ok =
8886         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8887                                             i + 1, 0);
8888       if (target_resources_ok == 0)
8889         error (_("No hardware breakpoint support in the target."));
8890       else if (target_resources_ok < 0)
8891         error (_("Hardware breakpoints used exceeds limit."));
8892     }
8893
8894   gdb_assert (!sals.empty ());
8895
8896   for (const auto &sal : sals)
8897     {
8898       struct bp_location *loc;
8899
8900       if (from_tty)
8901         {
8902           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8903           if (!loc_gdbarch)
8904             loc_gdbarch = gdbarch;
8905
8906           describe_other_breakpoints (loc_gdbarch,
8907                                       sal.pspace, sal.pc, sal.section, thread);
8908         }
8909
8910       if (&sal == &sals[0])
8911         {
8912           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8913           b->thread = thread;
8914           b->task = task;
8915
8916           b->cond_string = cond_string.release ();
8917           b->extra_string = extra_string.release ();
8918           b->ignore_count = ignore_count;
8919           b->enable_state = enabled ? bp_enabled : bp_disabled;
8920           b->disposition = disposition;
8921
8922           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8923             b->loc->inserted = 1;
8924
8925           if (type == bp_static_tracepoint)
8926             {
8927               struct tracepoint *t = (struct tracepoint *) b;
8928               struct static_tracepoint_marker marker;
8929
8930               if (strace_marker_p (b))
8931                 {
8932                   /* We already know the marker exists, otherwise, we
8933                      wouldn't see a sal for it.  */
8934                   const char *p
8935                     = &event_location_to_string (b->location.get ())[3];
8936                   const char *endp;
8937                   char *marker_str;
8938
8939                   p = skip_spaces (p);
8940
8941                   endp = skip_to_space (p);
8942
8943                   marker_str = savestring (p, endp - p);
8944                   t->static_trace_marker_id = marker_str;
8945
8946                   printf_filtered (_("Probed static tracepoint "
8947                                      "marker \"%s\"\n"),
8948                                    t->static_trace_marker_id);
8949                 }
8950               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8951                 {
8952                   t->static_trace_marker_id = xstrdup (marker.str_id);
8953                   release_static_tracepoint_marker (&marker);
8954
8955                   printf_filtered (_("Probed static tracepoint "
8956                                      "marker \"%s\"\n"),
8957                                    t->static_trace_marker_id);
8958                 }
8959               else
8960                 warning (_("Couldn't determine the static "
8961                            "tracepoint marker to probe"));
8962             }
8963
8964           loc = b->loc;
8965         }
8966       else
8967         {
8968           loc = add_location_to_breakpoint (b, &sal);
8969           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8970             loc->inserted = 1;
8971         }
8972
8973       if (b->cond_string)
8974         {
8975           const char *arg = b->cond_string;
8976
8977           loc->cond = parse_exp_1 (&arg, loc->address,
8978                                    block_for_pc (loc->address), 0);
8979           if (*arg)
8980               error (_("Garbage '%s' follows condition"), arg);
8981         }
8982
8983       /* Dynamic printf requires and uses additional arguments on the
8984          command line, otherwise it's an error.  */
8985       if (type == bp_dprintf)
8986         {
8987           if (b->extra_string)
8988             update_dprintf_command_list (b);
8989           else
8990             error (_("Format string required"));
8991         }
8992       else if (b->extra_string)
8993         error (_("Garbage '%s' at end of command"), b->extra_string);
8994     }
8995
8996   b->display_canonical = display_canonical;
8997   if (location != NULL)
8998     b->location = std::move (location);
8999   else
9000     b->location = new_address_location (b->loc->address, NULL, 0);
9001   b->filter = filter.release ();
9002 }
9003
9004 static void
9005 create_breakpoint_sal (struct gdbarch *gdbarch,
9006                        gdb::array_view<const symtab_and_line> sals,
9007                        event_location_up &&location,
9008                        gdb::unique_xmalloc_ptr<char> filter,
9009                        gdb::unique_xmalloc_ptr<char> cond_string,
9010                        gdb::unique_xmalloc_ptr<char> extra_string,
9011                        enum bptype type, enum bpdisp disposition,
9012                        int thread, int task, int ignore_count,
9013                        const struct breakpoint_ops *ops, int from_tty,
9014                        int enabled, int internal, unsigned flags,
9015                        int display_canonical)
9016 {
9017   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (type);
9018
9019   init_breakpoint_sal (b.get (), gdbarch,
9020                        sals, std::move (location),
9021                        std::move (filter),
9022                        std::move (cond_string),
9023                        std::move (extra_string),
9024                        type, disposition,
9025                        thread, task, ignore_count,
9026                        ops, from_tty,
9027                        enabled, internal, flags,
9028                        display_canonical);
9029
9030   install_breakpoint (internal, std::move (b), 0);
9031 }
9032
9033 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9034    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9035    value.  COND_STRING, if not NULL, specified the condition to be
9036    used for all breakpoints.  Essentially the only case where
9037    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9038    function.  In that case, it's still not possible to specify
9039    separate conditions for different overloaded functions, so
9040    we take just a single condition string.
9041    
9042    NOTE: If the function succeeds, the caller is expected to cleanup
9043    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9044    array contents).  If the function fails (error() is called), the
9045    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9046    COND and SALS arrays and each of those arrays contents.  */
9047
9048 static void
9049 create_breakpoints_sal (struct gdbarch *gdbarch,
9050                         struct linespec_result *canonical,
9051                         gdb::unique_xmalloc_ptr<char> cond_string,
9052                         gdb::unique_xmalloc_ptr<char> extra_string,
9053                         enum bptype type, enum bpdisp disposition,
9054                         int thread, int task, int ignore_count,
9055                         const struct breakpoint_ops *ops, int from_tty,
9056                         int enabled, int internal, unsigned flags)
9057 {
9058   if (canonical->pre_expanded)
9059     gdb_assert (canonical->lsals.size () == 1);
9060
9061   for (const auto &lsal : canonical->lsals)
9062     {
9063       /* Note that 'location' can be NULL in the case of a plain
9064          'break', without arguments.  */
9065       event_location_up location
9066         = (canonical->location != NULL
9067            ? copy_event_location (canonical->location.get ()) : NULL);
9068       gdb::unique_xmalloc_ptr<char> filter_string
9069         (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
9070
9071       create_breakpoint_sal (gdbarch, lsal.sals,
9072                              std::move (location),
9073                              std::move (filter_string),
9074                              std::move (cond_string),
9075                              std::move (extra_string),
9076                              type, disposition,
9077                              thread, task, ignore_count, ops,
9078                              from_tty, enabled, internal, flags,
9079                              canonical->special_display);
9080     }
9081 }
9082
9083 /* Parse LOCATION which is assumed to be a SAL specification possibly
9084    followed by conditionals.  On return, SALS contains an array of SAL
9085    addresses found.  LOCATION points to the end of the SAL (for
9086    linespec locations).
9087
9088    The array and the line spec strings are allocated on the heap, it is
9089    the caller's responsibility to free them.  */
9090
9091 static void
9092 parse_breakpoint_sals (const struct event_location *location,
9093                        struct linespec_result *canonical)
9094 {
9095   struct symtab_and_line cursal;
9096
9097   if (event_location_type (location) == LINESPEC_LOCATION)
9098     {
9099       const char *spec = get_linespec_location (location)->spec_string;
9100
9101       if (spec == NULL)
9102         {
9103           /* The last displayed codepoint, if it's valid, is our default
9104              breakpoint address.  */
9105           if (last_displayed_sal_is_valid ())
9106             {
9107               /* Set sal's pspace, pc, symtab, and line to the values
9108                  corresponding to the last call to print_frame_info.
9109                  Be sure to reinitialize LINE with NOTCURRENT == 0
9110                  as the breakpoint line number is inappropriate otherwise.
9111                  find_pc_line would adjust PC, re-set it back.  */
9112               symtab_and_line sal = get_last_displayed_sal ();
9113               CORE_ADDR pc = sal.pc;
9114
9115               sal = find_pc_line (pc, 0);
9116
9117               /* "break" without arguments is equivalent to "break *PC"
9118                  where PC is the last displayed codepoint's address.  So
9119                  make sure to set sal.explicit_pc to prevent GDB from
9120                  trying to expand the list of sals to include all other
9121                  instances with the same symtab and line.  */
9122               sal.pc = pc;
9123               sal.explicit_pc = 1;
9124
9125               struct linespec_sals lsal;
9126               lsal.sals = {sal};
9127               lsal.canonical = NULL;
9128
9129               canonical->lsals.push_back (std::move (lsal));
9130               return;
9131             }
9132           else
9133             error (_("No default breakpoint address now."));
9134         }
9135     }
9136
9137   /* Force almost all breakpoints to be in terms of the
9138      current_source_symtab (which is decode_line_1's default).
9139      This should produce the results we want almost all of the
9140      time while leaving default_breakpoint_* alone.
9141
9142      ObjC: However, don't match an Objective-C method name which
9143      may have a '+' or '-' succeeded by a '['.  */
9144   cursal = get_current_source_symtab_and_line ();
9145   if (last_displayed_sal_is_valid ())
9146     {
9147       const char *spec = NULL;
9148
9149       if (event_location_type (location) == LINESPEC_LOCATION)
9150         spec = get_linespec_location (location)->spec_string;
9151
9152       if (!cursal.symtab
9153           || (spec != NULL
9154               && strchr ("+-", spec[0]) != NULL
9155               && spec[1] != '['))
9156         {
9157           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9158                             get_last_displayed_symtab (),
9159                             get_last_displayed_line (),
9160                             canonical, NULL, NULL);
9161           return;
9162         }
9163     }
9164
9165   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9166                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9167 }
9168
9169
9170 /* Convert each SAL into a real PC.  Verify that the PC can be
9171    inserted as a breakpoint.  If it can't throw an error.  */
9172
9173 static void
9174 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
9175 {    
9176   for (auto &sal : sals)
9177     resolve_sal_pc (&sal);
9178 }
9179
9180 /* Fast tracepoints may have restrictions on valid locations.  For
9181    instance, a fast tracepoint using a jump instead of a trap will
9182    likely have to overwrite more bytes than a trap would, and so can
9183    only be placed where the instruction is longer than the jump, or a
9184    multi-instruction sequence does not have a jump into the middle of
9185    it, etc.  */
9186
9187 static void
9188 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9189                             gdb::array_view<const symtab_and_line> sals)
9190 {
9191   int rslt;
9192   char *msg;
9193   struct cleanup *old_chain;
9194
9195   for (const auto &sal : sals)
9196     {
9197       struct gdbarch *sarch;
9198
9199       sarch = get_sal_arch (sal);
9200       /* We fall back to GDBARCH if there is no architecture
9201          associated with SAL.  */
9202       if (sarch == NULL)
9203         sarch = gdbarch;
9204       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg);
9205       old_chain = make_cleanup (xfree, msg);
9206
9207       if (!rslt)
9208         error (_("May not have a fast tracepoint at %s%s"),
9209                paddress (sarch, sal.pc), (msg ? msg : ""));
9210
9211       do_cleanups (old_chain);
9212     }
9213 }
9214
9215 /* Given TOK, a string specification of condition and thread, as
9216    accepted by the 'break' command, extract the condition
9217    string and thread number and set *COND_STRING and *THREAD.
9218    PC identifies the context at which the condition should be parsed.
9219    If no condition is found, *COND_STRING is set to NULL.
9220    If no thread is found, *THREAD is set to -1.  */
9221
9222 static void
9223 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9224                            char **cond_string, int *thread, int *task,
9225                            char **rest)
9226 {
9227   *cond_string = NULL;
9228   *thread = -1;
9229   *task = 0;
9230   *rest = NULL;
9231
9232   while (tok && *tok)
9233     {
9234       const char *end_tok;
9235       int toklen;
9236       const char *cond_start = NULL;
9237       const char *cond_end = NULL;
9238
9239       tok = skip_spaces (tok);
9240
9241       if ((*tok == '"' || *tok == ',') && rest)
9242         {
9243           *rest = savestring (tok, strlen (tok));
9244           return;
9245         }
9246
9247       end_tok = skip_to_space (tok);
9248
9249       toklen = end_tok - tok;
9250
9251       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9252         {
9253           tok = cond_start = end_tok + 1;
9254           parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9255           cond_end = tok;
9256           *cond_string = savestring (cond_start, cond_end - cond_start);
9257         }
9258       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9259         {
9260           const char *tmptok;
9261           struct thread_info *thr;
9262
9263           tok = end_tok + 1;
9264           thr = parse_thread_id (tok, &tmptok);
9265           if (tok == tmptok)
9266             error (_("Junk after thread keyword."));
9267           *thread = thr->global_num;
9268           tok = tmptok;
9269         }
9270       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9271         {
9272           char *tmptok;
9273
9274           tok = end_tok + 1;
9275           *task = strtol (tok, &tmptok, 0);
9276           if (tok == tmptok)
9277             error (_("Junk after task keyword."));
9278           if (!valid_task_id (*task))
9279             error (_("Unknown task %d."), *task);
9280           tok = tmptok;
9281         }
9282       else if (rest)
9283         {
9284           *rest = savestring (tok, strlen (tok));
9285           return;
9286         }
9287       else
9288         error (_("Junk at end of arguments."));
9289     }
9290 }
9291
9292 /* Decode a static tracepoint marker spec.  */
9293
9294 static std::vector<symtab_and_line>
9295 decode_static_tracepoint_spec (const char **arg_p)
9296 {
9297   VEC(static_tracepoint_marker_p) *markers = NULL;
9298   const char *p = &(*arg_p)[3];
9299   const char *endp;
9300   int i;
9301
9302   p = skip_spaces (p);
9303
9304   endp = skip_to_space (p);
9305
9306   std::string marker_str (p, endp - p);
9307
9308   markers = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
9309   if (VEC_empty(static_tracepoint_marker_p, markers))
9310     error (_("No known static tracepoint marker named %s"),
9311            marker_str.c_str ());
9312
9313   std::vector<symtab_and_line> sals;
9314   sals.reserve (VEC_length(static_tracepoint_marker_p, markers));
9315
9316   for (i = 0; i < VEC_length(static_tracepoint_marker_p, markers); i++)
9317     {
9318       struct static_tracepoint_marker *marker;
9319
9320       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9321
9322       symtab_and_line sal = find_pc_line (marker->address, 0);
9323       sal.pc = marker->address;
9324       sals.push_back (sal);
9325
9326       release_static_tracepoint_marker (marker);
9327     }
9328
9329   *arg_p = endp;
9330   return sals;
9331 }
9332
9333 /* See breakpoint.h.  */
9334
9335 int
9336 create_breakpoint (struct gdbarch *gdbarch,
9337                    const struct event_location *location,
9338                    const char *cond_string,
9339                    int thread, const char *extra_string,
9340                    int parse_extra,
9341                    int tempflag, enum bptype type_wanted,
9342                    int ignore_count,
9343                    enum auto_boolean pending_break_support,
9344                    const struct breakpoint_ops *ops,
9345                    int from_tty, int enabled, int internal,
9346                    unsigned flags)
9347 {
9348   struct linespec_result canonical;
9349   struct cleanup *bkpt_chain = NULL;
9350   int pending = 0;
9351   int task = 0;
9352   int prev_bkpt_count = breakpoint_count;
9353
9354   gdb_assert (ops != NULL);
9355
9356   /* If extra_string isn't useful, set it to NULL.  */
9357   if (extra_string != NULL && *extra_string == '\0')
9358     extra_string = NULL;
9359
9360   TRY
9361     {
9362       ops->create_sals_from_location (location, &canonical, type_wanted);
9363     }
9364   CATCH (e, RETURN_MASK_ERROR)
9365     {
9366       /* If caller is interested in rc value from parse, set
9367          value.  */
9368       if (e.error == NOT_FOUND_ERROR)
9369         {
9370           /* If pending breakpoint support is turned off, throw
9371              error.  */
9372
9373           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9374             throw_exception (e);
9375
9376           exception_print (gdb_stderr, e);
9377
9378           /* If pending breakpoint support is auto query and the user
9379              selects no, then simply return the error code.  */
9380           if (pending_break_support == AUTO_BOOLEAN_AUTO
9381               && !nquery (_("Make %s pending on future shared library load? "),
9382                           bptype_string (type_wanted)))
9383             return 0;
9384
9385           /* At this point, either the user was queried about setting
9386              a pending breakpoint and selected yes, or pending
9387              breakpoint behavior is on and thus a pending breakpoint
9388              is defaulted on behalf of the user.  */
9389           pending = 1;
9390         }
9391       else
9392         throw_exception (e);
9393     }
9394   END_CATCH
9395
9396   if (!pending && canonical.lsals.empty ())
9397     return 0;
9398
9399   /* ----------------------------- SNIP -----------------------------
9400      Anything added to the cleanup chain beyond this point is assumed
9401      to be part of a breakpoint.  If the breakpoint create succeeds
9402      then the memory is not reclaimed.  */
9403   bkpt_chain = make_cleanup (null_cleanup, 0);
9404
9405   /* Resolve all line numbers to PC's and verify that the addresses
9406      are ok for the target.  */
9407   if (!pending)
9408     {
9409       for (auto &lsal : canonical.lsals)
9410         breakpoint_sals_to_pc (lsal.sals);
9411     }
9412
9413   /* Fast tracepoints may have additional restrictions on location.  */
9414   if (!pending && type_wanted == bp_fast_tracepoint)
9415     {
9416       for (const auto &lsal : canonical.lsals)
9417         check_fast_tracepoint_sals (gdbarch, lsal.sals);
9418     }
9419
9420   /* Verify that condition can be parsed, before setting any
9421      breakpoints.  Allocate a separate condition expression for each
9422      breakpoint.  */
9423   if (!pending)
9424     {
9425       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9426       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9427
9428       if (parse_extra)
9429         {
9430           char *rest;
9431           char *cond;
9432
9433           const linespec_sals &lsal = canonical.lsals[0];
9434
9435           /* Here we only parse 'arg' to separate condition
9436              from thread number, so parsing in context of first
9437              sal is OK.  When setting the breakpoint we'll
9438              re-parse it in context of each sal.  */
9439
9440           find_condition_and_thread (extra_string, lsal.sals[0].pc,
9441                                      &cond, &thread, &task, &rest);
9442           cond_string_copy.reset (cond);
9443           extra_string_copy.reset (rest);
9444         }
9445       else
9446         {
9447           if (type_wanted != bp_dprintf
9448               && extra_string != NULL && *extra_string != '\0')
9449                 error (_("Garbage '%s' at end of location"), extra_string);
9450
9451           /* Create a private copy of condition string.  */
9452           if (cond_string)
9453             cond_string_copy.reset (xstrdup (cond_string));
9454           /* Create a private copy of any extra string.  */
9455           if (extra_string)
9456             extra_string_copy.reset (xstrdup (extra_string));
9457         }
9458
9459       ops->create_breakpoints_sal (gdbarch, &canonical,
9460                                    std::move (cond_string_copy),
9461                                    std::move (extra_string_copy),
9462                                    type_wanted,
9463                                    tempflag ? disp_del : disp_donttouch,
9464                                    thread, task, ignore_count, ops,
9465                                    from_tty, enabled, internal, flags);
9466     }
9467   else
9468     {
9469       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (type_wanted);
9470
9471       init_raw_breakpoint_without_location (b.get (), gdbarch, type_wanted, ops);
9472       b->location = copy_event_location (location);
9473
9474       if (parse_extra)
9475         b->cond_string = NULL;
9476       else
9477         {
9478           /* Create a private copy of condition string.  */
9479           b->cond_string = cond_string != NULL ? xstrdup (cond_string) : NULL;
9480           b->thread = thread;
9481         }
9482
9483       /* Create a private copy of any extra string.  */
9484       b->extra_string = extra_string != NULL ? xstrdup (extra_string) : NULL;
9485       b->ignore_count = ignore_count;
9486       b->disposition = tempflag ? disp_del : disp_donttouch;
9487       b->condition_not_parsed = 1;
9488       b->enable_state = enabled ? bp_enabled : bp_disabled;
9489       if ((type_wanted != bp_breakpoint
9490            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9491         b->pspace = current_program_space;
9492
9493       install_breakpoint (internal, std::move (b), 0);
9494     }
9495   
9496   if (canonical.lsals.size () > 1)
9497     {
9498       warning (_("Multiple breakpoints were set.\nUse the "
9499                  "\"delete\" command to delete unwanted breakpoints."));
9500       prev_breakpoint_count = prev_bkpt_count;
9501     }
9502
9503   /* That's it.  Discard the cleanups for data inserted into the
9504      breakpoint.  */
9505   discard_cleanups (bkpt_chain);
9506
9507   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9508   update_global_location_list (UGLL_MAY_INSERT);
9509
9510   return 1;
9511 }
9512
9513 /* Set a breakpoint.
9514    ARG is a string describing breakpoint address,
9515    condition, and thread.
9516    FLAG specifies if a breakpoint is hardware on,
9517    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9518    and BP_TEMPFLAG.  */
9519
9520 static void
9521 break_command_1 (const char *arg, int flag, int from_tty)
9522 {
9523   int tempflag = flag & BP_TEMPFLAG;
9524   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9525                              ? bp_hardware_breakpoint
9526                              : bp_breakpoint);
9527   struct breakpoint_ops *ops;
9528
9529   event_location_up location = string_to_event_location (&arg, current_language);
9530
9531   /* Matching breakpoints on probes.  */
9532   if (location != NULL
9533       && event_location_type (location.get ()) == PROBE_LOCATION)
9534     ops = &bkpt_probe_breakpoint_ops;
9535   else
9536     ops = &bkpt_breakpoint_ops;
9537
9538   create_breakpoint (get_current_arch (),
9539                      location.get (),
9540                      NULL, 0, arg, 1 /* parse arg */,
9541                      tempflag, type_wanted,
9542                      0 /* Ignore count */,
9543                      pending_break_support,
9544                      ops,
9545                      from_tty,
9546                      1 /* enabled */,
9547                      0 /* internal */,
9548                      0);
9549 }
9550
9551 /* Helper function for break_command_1 and disassemble_command.  */
9552
9553 void
9554 resolve_sal_pc (struct symtab_and_line *sal)
9555 {
9556   CORE_ADDR pc;
9557
9558   if (sal->pc == 0 && sal->symtab != NULL)
9559     {
9560       if (!find_line_pc (sal->symtab, sal->line, &pc))
9561         error (_("No line %d in file \"%s\"."),
9562                sal->line, symtab_to_filename_for_display (sal->symtab));
9563       sal->pc = pc;
9564
9565       /* If this SAL corresponds to a breakpoint inserted using a line
9566          number, then skip the function prologue if necessary.  */
9567       if (sal->explicit_line)
9568         skip_prologue_sal (sal);
9569     }
9570
9571   if (sal->section == 0 && sal->symtab != NULL)
9572     {
9573       const struct blockvector *bv;
9574       const struct block *b;
9575       struct symbol *sym;
9576
9577       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9578                                     SYMTAB_COMPUNIT (sal->symtab));
9579       if (bv != NULL)
9580         {
9581           sym = block_linkage_function (b);
9582           if (sym != NULL)
9583             {
9584               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9585               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9586                                                  sym);
9587             }
9588           else
9589             {
9590               /* It really is worthwhile to have the section, so we'll
9591                  just have to look harder. This case can be executed
9592                  if we have line numbers but no functions (as can
9593                  happen in assembly source).  */
9594
9595               scoped_restore_current_pspace_and_thread restore_pspace_thread;
9596               switch_to_program_space_and_thread (sal->pspace);
9597
9598               bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9599               if (msym.minsym)
9600                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9601             }
9602         }
9603     }
9604 }
9605
9606 void
9607 break_command (const char *arg, int from_tty)
9608 {
9609   break_command_1 (arg, 0, from_tty);
9610 }
9611
9612 void
9613 tbreak_command (const char *arg, int from_tty)
9614 {
9615   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9616 }
9617
9618 static void
9619 hbreak_command (const char *arg, int from_tty)
9620 {
9621   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9622 }
9623
9624 static void
9625 thbreak_command (const char *arg, int from_tty)
9626 {
9627   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9628 }
9629
9630 static void
9631 stop_command (const char *arg, int from_tty)
9632 {
9633   printf_filtered (_("Specify the type of breakpoint to set.\n\
9634 Usage: stop in <function | address>\n\
9635        stop at <line>\n"));
9636 }
9637
9638 static void
9639 stopin_command (const char *arg, int from_tty)
9640 {
9641   int badInput = 0;
9642
9643   if (arg == (char *) NULL)
9644     badInput = 1;
9645   else if (*arg != '*')
9646     {
9647       const char *argptr = arg;
9648       int hasColon = 0;
9649
9650       /* Look for a ':'.  If this is a line number specification, then
9651          say it is bad, otherwise, it should be an address or
9652          function/method name.  */
9653       while (*argptr && !hasColon)
9654         {
9655           hasColon = (*argptr == ':');
9656           argptr++;
9657         }
9658
9659       if (hasColon)
9660         badInput = (*argptr != ':');    /* Not a class::method */
9661       else
9662         badInput = isdigit (*arg);      /* a simple line number */
9663     }
9664
9665   if (badInput)
9666     printf_filtered (_("Usage: stop in <function | address>\n"));
9667   else
9668     break_command_1 (arg, 0, from_tty);
9669 }
9670
9671 static void
9672 stopat_command (const char *arg, int from_tty)
9673 {
9674   int badInput = 0;
9675
9676   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9677     badInput = 1;
9678   else
9679     {
9680       const char *argptr = arg;
9681       int hasColon = 0;
9682
9683       /* Look for a ':'.  If there is a '::' then get out, otherwise
9684          it is probably a line number.  */
9685       while (*argptr && !hasColon)
9686         {
9687           hasColon = (*argptr == ':');
9688           argptr++;
9689         }
9690
9691       if (hasColon)
9692         badInput = (*argptr == ':');    /* we have class::method */
9693       else
9694         badInput = !isdigit (*arg);     /* not a line number */
9695     }
9696
9697   if (badInput)
9698     printf_filtered (_("Usage: stop at <line>\n"));
9699   else
9700     break_command_1 (arg, 0, from_tty);
9701 }
9702
9703 /* The dynamic printf command is mostly like a regular breakpoint, but
9704    with a prewired command list consisting of a single output command,
9705    built from extra arguments supplied on the dprintf command
9706    line.  */
9707
9708 static void
9709 dprintf_command (const char *arg, int from_tty)
9710 {
9711   event_location_up location = string_to_event_location (&arg, current_language);
9712
9713   /* If non-NULL, ARG should have been advanced past the location;
9714      the next character must be ','.  */
9715   if (arg != NULL)
9716     {
9717       if (arg[0] != ',' || arg[1] == '\0')
9718         error (_("Format string required"));
9719       else
9720         {
9721           /* Skip the comma.  */
9722           ++arg;
9723         }
9724     }
9725
9726   create_breakpoint (get_current_arch (),
9727                      location.get (),
9728                      NULL, 0, arg, 1 /* parse arg */,
9729                      0, bp_dprintf,
9730                      0 /* Ignore count */,
9731                      pending_break_support,
9732                      &dprintf_breakpoint_ops,
9733                      from_tty,
9734                      1 /* enabled */,
9735                      0 /* internal */,
9736                      0);
9737 }
9738
9739 static void
9740 agent_printf_command (const char *arg, int from_tty)
9741 {
9742   error (_("May only run agent-printf on the target"));
9743 }
9744
9745 /* Implement the "breakpoint_hit" breakpoint_ops method for
9746    ranged breakpoints.  */
9747
9748 static int
9749 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9750                                   const address_space *aspace,
9751                                   CORE_ADDR bp_addr,
9752                                   const struct target_waitstatus *ws)
9753 {
9754   if (ws->kind != TARGET_WAITKIND_STOPPED
9755       || ws->value.sig != GDB_SIGNAL_TRAP)
9756     return 0;
9757
9758   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9759                                          bl->length, aspace, bp_addr);
9760 }
9761
9762 /* Implement the "resources_needed" breakpoint_ops method for
9763    ranged breakpoints.  */
9764
9765 static int
9766 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9767 {
9768   return target_ranged_break_num_registers ();
9769 }
9770
9771 /* Implement the "print_it" breakpoint_ops method for
9772    ranged breakpoints.  */
9773
9774 static enum print_stop_action
9775 print_it_ranged_breakpoint (bpstat bs)
9776 {
9777   struct breakpoint *b = bs->breakpoint_at;
9778   struct bp_location *bl = b->loc;
9779   struct ui_out *uiout = current_uiout;
9780
9781   gdb_assert (b->type == bp_hardware_breakpoint);
9782
9783   /* Ranged breakpoints have only one location.  */
9784   gdb_assert (bl && bl->next == NULL);
9785
9786   annotate_breakpoint (b->number);
9787
9788   maybe_print_thread_hit_breakpoint (uiout);
9789
9790   if (b->disposition == disp_del)
9791     uiout->text ("Temporary ranged breakpoint ");
9792   else
9793     uiout->text ("Ranged breakpoint ");
9794   if (uiout->is_mi_like_p ())
9795     {
9796       uiout->field_string ("reason",
9797                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9798       uiout->field_string ("disp", bpdisp_text (b->disposition));
9799     }
9800   uiout->field_int ("bkptno", b->number);
9801   uiout->text (", ");
9802
9803   return PRINT_SRC_AND_LOC;
9804 }
9805
9806 /* Implement the "print_one" breakpoint_ops method for
9807    ranged breakpoints.  */
9808
9809 static void
9810 print_one_ranged_breakpoint (struct breakpoint *b,
9811                              struct bp_location **last_loc)
9812 {
9813   struct bp_location *bl = b->loc;
9814   struct value_print_options opts;
9815   struct ui_out *uiout = current_uiout;
9816
9817   /* Ranged breakpoints have only one location.  */
9818   gdb_assert (bl && bl->next == NULL);
9819
9820   get_user_print_options (&opts);
9821
9822   if (opts.addressprint)
9823     /* We don't print the address range here, it will be printed later
9824        by print_one_detail_ranged_breakpoint.  */
9825     uiout->field_skip ("addr");
9826   annotate_field (5);
9827   print_breakpoint_location (b, bl);
9828   *last_loc = bl;
9829 }
9830
9831 /* Implement the "print_one_detail" breakpoint_ops method for
9832    ranged breakpoints.  */
9833
9834 static void
9835 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9836                                     struct ui_out *uiout)
9837 {
9838   CORE_ADDR address_start, address_end;
9839   struct bp_location *bl = b->loc;
9840   string_file stb;
9841
9842   gdb_assert (bl);
9843
9844   address_start = bl->address;
9845   address_end = address_start + bl->length - 1;
9846
9847   uiout->text ("\taddress range: ");
9848   stb.printf ("[%s, %s]",
9849               print_core_address (bl->gdbarch, address_start),
9850               print_core_address (bl->gdbarch, address_end));
9851   uiout->field_stream ("addr", stb);
9852   uiout->text ("\n");
9853 }
9854
9855 /* Implement the "print_mention" breakpoint_ops method for
9856    ranged breakpoints.  */
9857
9858 static void
9859 print_mention_ranged_breakpoint (struct breakpoint *b)
9860 {
9861   struct bp_location *bl = b->loc;
9862   struct ui_out *uiout = current_uiout;
9863
9864   gdb_assert (bl);
9865   gdb_assert (b->type == bp_hardware_breakpoint);
9866
9867   if (uiout->is_mi_like_p ())
9868     return;
9869
9870   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9871                    b->number, paddress (bl->gdbarch, bl->address),
9872                    paddress (bl->gdbarch, bl->address + bl->length - 1));
9873 }
9874
9875 /* Implement the "print_recreate" breakpoint_ops method for
9876    ranged breakpoints.  */
9877
9878 static void
9879 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9880 {
9881   fprintf_unfiltered (fp, "break-range %s, %s",
9882                       event_location_to_string (b->location.get ()),
9883                       event_location_to_string (b->location_range_end.get ()));
9884   print_recreate_thread (b, fp);
9885 }
9886
9887 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9888
9889 static struct breakpoint_ops ranged_breakpoint_ops;
9890
9891 /* Find the address where the end of the breakpoint range should be
9892    placed, given the SAL of the end of the range.  This is so that if
9893    the user provides a line number, the end of the range is set to the
9894    last instruction of the given line.  */
9895
9896 static CORE_ADDR
9897 find_breakpoint_range_end (struct symtab_and_line sal)
9898 {
9899   CORE_ADDR end;
9900
9901   /* If the user provided a PC value, use it.  Otherwise,
9902      find the address of the end of the given location.  */
9903   if (sal.explicit_pc)
9904     end = sal.pc;
9905   else
9906     {
9907       int ret;
9908       CORE_ADDR start;
9909
9910       ret = find_line_pc_range (sal, &start, &end);
9911       if (!ret)
9912         error (_("Could not find location of the end of the range."));
9913
9914       /* find_line_pc_range returns the start of the next line.  */
9915       end--;
9916     }
9917
9918   return end;
9919 }
9920
9921 /* Implement the "break-range" CLI command.  */
9922
9923 static void
9924 break_range_command (const char *arg, int from_tty)
9925 {
9926   const char *arg_start;
9927   struct linespec_result canonical_start, canonical_end;
9928   int bp_count, can_use_bp, length;
9929   CORE_ADDR end;
9930   struct breakpoint *b;
9931
9932   /* We don't support software ranged breakpoints.  */
9933   if (target_ranged_break_num_registers () < 0)
9934     error (_("This target does not support hardware ranged breakpoints."));
9935
9936   bp_count = hw_breakpoint_used_count ();
9937   bp_count += target_ranged_break_num_registers ();
9938   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9939                                                    bp_count, 0);
9940   if (can_use_bp < 0)
9941     error (_("Hardware breakpoints used exceeds limit."));
9942
9943   arg = skip_spaces (arg);
9944   if (arg == NULL || arg[0] == '\0')
9945     error(_("No address range specified."));
9946
9947   arg_start = arg;
9948   event_location_up start_location = string_to_event_location (&arg,
9949                                                                current_language);
9950   parse_breakpoint_sals (start_location.get (), &canonical_start);
9951
9952   if (arg[0] != ',')
9953     error (_("Too few arguments."));
9954   else if (canonical_start.lsals.empty ())
9955     error (_("Could not find location of the beginning of the range."));
9956
9957   const linespec_sals &lsal_start = canonical_start.lsals[0];
9958
9959   if (canonical_start.lsals.size () > 1
9960       || lsal_start.sals.size () != 1)
9961     error (_("Cannot create a ranged breakpoint with multiple locations."));
9962
9963   const symtab_and_line &sal_start = lsal_start.sals[0];
9964   std::string addr_string_start (arg_start, arg - arg_start);
9965
9966   arg++;        /* Skip the comma.  */
9967   arg = skip_spaces (arg);
9968
9969   /* Parse the end location.  */
9970
9971   arg_start = arg;
9972
9973   /* We call decode_line_full directly here instead of using
9974      parse_breakpoint_sals because we need to specify the start location's
9975      symtab and line as the default symtab and line for the end of the
9976      range.  This makes it possible to have ranges like "foo.c:27, +14",
9977      where +14 means 14 lines from the start location.  */
9978   event_location_up end_location = string_to_event_location (&arg,
9979                                                              current_language);
9980   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
9981                     sal_start.symtab, sal_start.line,
9982                     &canonical_end, NULL, NULL);
9983
9984   if (canonical_end.lsals.empty ())
9985     error (_("Could not find location of the end of the range."));
9986
9987   const linespec_sals &lsal_end = canonical_end.lsals[0];
9988   if (canonical_end.lsals.size () > 1
9989       || lsal_end.sals.size () != 1)
9990     error (_("Cannot create a ranged breakpoint with multiple locations."));
9991
9992   const symtab_and_line &sal_end = lsal_end.sals[0];
9993
9994   end = find_breakpoint_range_end (sal_end);
9995   if (sal_start.pc > end)
9996     error (_("Invalid address range, end precedes start."));
9997
9998   length = end - sal_start.pc + 1;
9999   if (length < 0)
10000     /* Length overflowed.  */
10001     error (_("Address range too large."));
10002   else if (length == 1)
10003     {
10004       /* This range is simple enough to be handled by
10005          the `hbreak' command.  */
10006       hbreak_command (&addr_string_start[0], 1);
10007
10008       return;
10009     }
10010
10011   /* Now set up the breakpoint.  */
10012   b = set_raw_breakpoint (get_current_arch (), sal_start,
10013                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10014   set_breakpoint_count (breakpoint_count + 1);
10015   b->number = breakpoint_count;
10016   b->disposition = disp_donttouch;
10017   b->location = std::move (start_location);
10018   b->location_range_end = std::move (end_location);
10019   b->loc->length = length;
10020
10021   mention (b);
10022   observer_notify_breakpoint_created (b);
10023   update_global_location_list (UGLL_MAY_INSERT);
10024 }
10025
10026 /*  Return non-zero if EXP is verified as constant.  Returned zero
10027     means EXP is variable.  Also the constant detection may fail for
10028     some constant expressions and in such case still falsely return
10029     zero.  */
10030
10031 static int
10032 watchpoint_exp_is_const (const struct expression *exp)
10033 {
10034   int i = exp->nelts;
10035
10036   while (i > 0)
10037     {
10038       int oplenp, argsp;
10039
10040       /* We are only interested in the descriptor of each element.  */
10041       operator_length (exp, i, &oplenp, &argsp);
10042       i -= oplenp;
10043
10044       switch (exp->elts[i].opcode)
10045         {
10046         case BINOP_ADD:
10047         case BINOP_SUB:
10048         case BINOP_MUL:
10049         case BINOP_DIV:
10050         case BINOP_REM:
10051         case BINOP_MOD:
10052         case BINOP_LSH:
10053         case BINOP_RSH:
10054         case BINOP_LOGICAL_AND:
10055         case BINOP_LOGICAL_OR:
10056         case BINOP_BITWISE_AND:
10057         case BINOP_BITWISE_IOR:
10058         case BINOP_BITWISE_XOR:
10059         case BINOP_EQUAL:
10060         case BINOP_NOTEQUAL:
10061         case BINOP_LESS:
10062         case BINOP_GTR:
10063         case BINOP_LEQ:
10064         case BINOP_GEQ:
10065         case BINOP_REPEAT:
10066         case BINOP_COMMA:
10067         case BINOP_EXP:
10068         case BINOP_MIN:
10069         case BINOP_MAX:
10070         case BINOP_INTDIV:
10071         case BINOP_CONCAT:
10072         case TERNOP_COND:
10073         case TERNOP_SLICE:
10074
10075         case OP_LONG:
10076         case OP_FLOAT:
10077         case OP_LAST:
10078         case OP_COMPLEX:
10079         case OP_STRING:
10080         case OP_ARRAY:
10081         case OP_TYPE:
10082         case OP_TYPEOF:
10083         case OP_DECLTYPE:
10084         case OP_TYPEID:
10085         case OP_NAME:
10086         case OP_OBJC_NSSTRING:
10087
10088         case UNOP_NEG:
10089         case UNOP_LOGICAL_NOT:
10090         case UNOP_COMPLEMENT:
10091         case UNOP_ADDR:
10092         case UNOP_HIGH:
10093         case UNOP_CAST:
10094
10095         case UNOP_CAST_TYPE:
10096         case UNOP_REINTERPRET_CAST:
10097         case UNOP_DYNAMIC_CAST:
10098           /* Unary, binary and ternary operators: We have to check
10099              their operands.  If they are constant, then so is the
10100              result of that operation.  For instance, if A and B are
10101              determined to be constants, then so is "A + B".
10102
10103              UNOP_IND is one exception to the rule above, because the
10104              value of *ADDR is not necessarily a constant, even when
10105              ADDR is.  */
10106           break;
10107
10108         case OP_VAR_VALUE:
10109           /* Check whether the associated symbol is a constant.
10110
10111              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10112              possible that a buggy compiler could mark a variable as
10113              constant even when it is not, and TYPE_CONST would return
10114              true in this case, while SYMBOL_CLASS wouldn't.
10115
10116              We also have to check for function symbols because they
10117              are always constant.  */
10118           {
10119             struct symbol *s = exp->elts[i + 2].symbol;
10120
10121             if (SYMBOL_CLASS (s) != LOC_BLOCK
10122                 && SYMBOL_CLASS (s) != LOC_CONST
10123                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10124               return 0;
10125             break;
10126           }
10127
10128         /* The default action is to return 0 because we are using
10129            the optimistic approach here: If we don't know something,
10130            then it is not a constant.  */
10131         default:
10132           return 0;
10133         }
10134     }
10135
10136   return 1;
10137 }
10138
10139 /* Watchpoint destructor.  */
10140
10141 watchpoint::~watchpoint ()
10142 {
10143   xfree (this->exp_string);
10144   xfree (this->exp_string_reparse);
10145   value_free (this->val);
10146 }
10147
10148 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10149
10150 static void
10151 re_set_watchpoint (struct breakpoint *b)
10152 {
10153   struct watchpoint *w = (struct watchpoint *) b;
10154
10155   /* Watchpoint can be either on expression using entirely global
10156      variables, or it can be on local variables.
10157
10158      Watchpoints of the first kind are never auto-deleted, and even
10159      persist across program restarts.  Since they can use variables
10160      from shared libraries, we need to reparse expression as libraries
10161      are loaded and unloaded.
10162
10163      Watchpoints on local variables can also change meaning as result
10164      of solib event.  For example, if a watchpoint uses both a local
10165      and a global variables in expression, it's a local watchpoint,
10166      but unloading of a shared library will make the expression
10167      invalid.  This is not a very common use case, but we still
10168      re-evaluate expression, to avoid surprises to the user.
10169
10170      Note that for local watchpoints, we re-evaluate it only if
10171      watchpoints frame id is still valid.  If it's not, it means the
10172      watchpoint is out of scope and will be deleted soon.  In fact,
10173      I'm not sure we'll ever be called in this case.
10174
10175      If a local watchpoint's frame id is still valid, then
10176      w->exp_valid_block is likewise valid, and we can safely use it.
10177
10178      Don't do anything about disabled watchpoints, since they will be
10179      reevaluated again when enabled.  */
10180   update_watchpoint (w, 1 /* reparse */);
10181 }
10182
10183 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10184
10185 static int
10186 insert_watchpoint (struct bp_location *bl)
10187 {
10188   struct watchpoint *w = (struct watchpoint *) bl->owner;
10189   int length = w->exact ? 1 : bl->length;
10190
10191   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10192                                    w->cond_exp.get ());
10193 }
10194
10195 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10196
10197 static int
10198 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10199 {
10200   struct watchpoint *w = (struct watchpoint *) bl->owner;
10201   int length = w->exact ? 1 : bl->length;
10202
10203   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10204                                    w->cond_exp.get ());
10205 }
10206
10207 static int
10208 breakpoint_hit_watchpoint (const struct bp_location *bl,
10209                            const address_space *aspace, CORE_ADDR bp_addr,
10210                            const struct target_waitstatus *ws)
10211 {
10212   struct breakpoint *b = bl->owner;
10213   struct watchpoint *w = (struct watchpoint *) b;
10214
10215   /* Continuable hardware watchpoints are treated as non-existent if the
10216      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10217      some data address).  Otherwise gdb won't stop on a break instruction
10218      in the code (not from a breakpoint) when a hardware watchpoint has
10219      been defined.  Also skip watchpoints which we know did not trigger
10220      (did not match the data address).  */
10221   if (is_hardware_watchpoint (b)
10222       && w->watchpoint_triggered == watch_triggered_no)
10223     return 0;
10224
10225   return 1;
10226 }
10227
10228 static void
10229 check_status_watchpoint (bpstat bs)
10230 {
10231   gdb_assert (is_watchpoint (bs->breakpoint_at));
10232
10233   bpstat_check_watchpoint (bs);
10234 }
10235
10236 /* Implement the "resources_needed" breakpoint_ops method for
10237    hardware watchpoints.  */
10238
10239 static int
10240 resources_needed_watchpoint (const struct bp_location *bl)
10241 {
10242   struct watchpoint *w = (struct watchpoint *) bl->owner;
10243   int length = w->exact? 1 : bl->length;
10244
10245   return target_region_ok_for_hw_watchpoint (bl->address, length);
10246 }
10247
10248 /* Implement the "works_in_software_mode" breakpoint_ops method for
10249    hardware watchpoints.  */
10250
10251 static int
10252 works_in_software_mode_watchpoint (const struct breakpoint *b)
10253 {
10254   /* Read and access watchpoints only work with hardware support.  */
10255   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10256 }
10257
10258 static enum print_stop_action
10259 print_it_watchpoint (bpstat bs)
10260 {
10261   struct breakpoint *b;
10262   enum print_stop_action result;
10263   struct watchpoint *w;
10264   struct ui_out *uiout = current_uiout;
10265
10266   gdb_assert (bs->bp_location_at != NULL);
10267
10268   b = bs->breakpoint_at;
10269   w = (struct watchpoint *) b;
10270
10271   annotate_watchpoint (b->number);
10272   maybe_print_thread_hit_breakpoint (uiout);
10273
10274   string_file stb;
10275
10276   gdb::optional<ui_out_emit_tuple> tuple_emitter;
10277   switch (b->type)
10278     {
10279     case bp_watchpoint:
10280     case bp_hardware_watchpoint:
10281       if (uiout->is_mi_like_p ())
10282         uiout->field_string
10283           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10284       mention (b);
10285       tuple_emitter.emplace (uiout, "value");
10286       uiout->text ("\nOld value = ");
10287       watchpoint_value_print (bs->old_val, &stb);
10288       uiout->field_stream ("old", stb);
10289       uiout->text ("\nNew value = ");
10290       watchpoint_value_print (w->val, &stb);
10291       uiout->field_stream ("new", stb);
10292       uiout->text ("\n");
10293       /* More than one watchpoint may have been triggered.  */
10294       result = PRINT_UNKNOWN;
10295       break;
10296
10297     case bp_read_watchpoint:
10298       if (uiout->is_mi_like_p ())
10299         uiout->field_string
10300           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10301       mention (b);
10302       tuple_emitter.emplace (uiout, "value");
10303       uiout->text ("\nValue = ");
10304       watchpoint_value_print (w->val, &stb);
10305       uiout->field_stream ("value", stb);
10306       uiout->text ("\n");
10307       result = PRINT_UNKNOWN;
10308       break;
10309
10310     case bp_access_watchpoint:
10311       if (bs->old_val != NULL)
10312         {
10313           if (uiout->is_mi_like_p ())
10314             uiout->field_string
10315               ("reason",
10316                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10317           mention (b);
10318           tuple_emitter.emplace (uiout, "value");
10319           uiout->text ("\nOld value = ");
10320           watchpoint_value_print (bs->old_val, &stb);
10321           uiout->field_stream ("old", stb);
10322           uiout->text ("\nNew value = ");
10323         }
10324       else
10325         {
10326           mention (b);
10327           if (uiout->is_mi_like_p ())
10328             uiout->field_string
10329               ("reason",
10330                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10331           tuple_emitter.emplace (uiout, "value");
10332           uiout->text ("\nValue = ");
10333         }
10334       watchpoint_value_print (w->val, &stb);
10335       uiout->field_stream ("new", stb);
10336       uiout->text ("\n");
10337       result = PRINT_UNKNOWN;
10338       break;
10339     default:
10340       result = PRINT_UNKNOWN;
10341     }
10342
10343   return result;
10344 }
10345
10346 /* Implement the "print_mention" breakpoint_ops method for hardware
10347    watchpoints.  */
10348
10349 static void
10350 print_mention_watchpoint (struct breakpoint *b)
10351 {
10352   struct watchpoint *w = (struct watchpoint *) b;
10353   struct ui_out *uiout = current_uiout;
10354   const char *tuple_name;
10355
10356   switch (b->type)
10357     {
10358     case bp_watchpoint:
10359       uiout->text ("Watchpoint ");
10360       tuple_name = "wpt";
10361       break;
10362     case bp_hardware_watchpoint:
10363       uiout->text ("Hardware watchpoint ");
10364       tuple_name = "wpt";
10365       break;
10366     case bp_read_watchpoint:
10367       uiout->text ("Hardware read watchpoint ");
10368       tuple_name = "hw-rwpt";
10369       break;
10370     case bp_access_watchpoint:
10371       uiout->text ("Hardware access (read/write) watchpoint ");
10372       tuple_name = "hw-awpt";
10373       break;
10374     default:
10375       internal_error (__FILE__, __LINE__,
10376                       _("Invalid hardware watchpoint type."));
10377     }
10378
10379   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10380   uiout->field_int ("number", b->number);
10381   uiout->text (": ");
10382   uiout->field_string ("exp", w->exp_string);
10383 }
10384
10385 /* Implement the "print_recreate" breakpoint_ops method for
10386    watchpoints.  */
10387
10388 static void
10389 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10390 {
10391   struct watchpoint *w = (struct watchpoint *) b;
10392
10393   switch (b->type)
10394     {
10395     case bp_watchpoint:
10396     case bp_hardware_watchpoint:
10397       fprintf_unfiltered (fp, "watch");
10398       break;
10399     case bp_read_watchpoint:
10400       fprintf_unfiltered (fp, "rwatch");
10401       break;
10402     case bp_access_watchpoint:
10403       fprintf_unfiltered (fp, "awatch");
10404       break;
10405     default:
10406       internal_error (__FILE__, __LINE__,
10407                       _("Invalid watchpoint type."));
10408     }
10409
10410   fprintf_unfiltered (fp, " %s", w->exp_string);
10411   print_recreate_thread (b, fp);
10412 }
10413
10414 /* Implement the "explains_signal" breakpoint_ops method for
10415    watchpoints.  */
10416
10417 static int
10418 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10419 {
10420   /* A software watchpoint cannot cause a signal other than
10421      GDB_SIGNAL_TRAP.  */
10422   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10423     return 0;
10424
10425   return 1;
10426 }
10427
10428 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10429
10430 static struct breakpoint_ops watchpoint_breakpoint_ops;
10431
10432 /* Implement the "insert" breakpoint_ops method for
10433    masked hardware watchpoints.  */
10434
10435 static int
10436 insert_masked_watchpoint (struct bp_location *bl)
10437 {
10438   struct watchpoint *w = (struct watchpoint *) bl->owner;
10439
10440   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10441                                         bl->watchpoint_type);
10442 }
10443
10444 /* Implement the "remove" breakpoint_ops method for
10445    masked hardware watchpoints.  */
10446
10447 static int
10448 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10449 {
10450   struct watchpoint *w = (struct watchpoint *) bl->owner;
10451
10452   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10453                                         bl->watchpoint_type);
10454 }
10455
10456 /* Implement the "resources_needed" breakpoint_ops method for
10457    masked hardware watchpoints.  */
10458
10459 static int
10460 resources_needed_masked_watchpoint (const struct bp_location *bl)
10461 {
10462   struct watchpoint *w = (struct watchpoint *) bl->owner;
10463
10464   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10465 }
10466
10467 /* Implement the "works_in_software_mode" breakpoint_ops method for
10468    masked hardware watchpoints.  */
10469
10470 static int
10471 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10472 {
10473   return 0;
10474 }
10475
10476 /* Implement the "print_it" breakpoint_ops method for
10477    masked hardware watchpoints.  */
10478
10479 static enum print_stop_action
10480 print_it_masked_watchpoint (bpstat bs)
10481 {
10482   struct breakpoint *b = bs->breakpoint_at;
10483   struct ui_out *uiout = current_uiout;
10484
10485   /* Masked watchpoints have only one location.  */
10486   gdb_assert (b->loc && b->loc->next == NULL);
10487
10488   annotate_watchpoint (b->number);
10489   maybe_print_thread_hit_breakpoint (uiout);
10490
10491   switch (b->type)
10492     {
10493     case bp_hardware_watchpoint:
10494       if (uiout->is_mi_like_p ())
10495         uiout->field_string
10496           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10497       break;
10498
10499     case bp_read_watchpoint:
10500       if (uiout->is_mi_like_p ())
10501         uiout->field_string
10502           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10503       break;
10504
10505     case bp_access_watchpoint:
10506       if (uiout->is_mi_like_p ())
10507         uiout->field_string
10508           ("reason",
10509            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10510       break;
10511     default:
10512       internal_error (__FILE__, __LINE__,
10513                       _("Invalid hardware watchpoint type."));
10514     }
10515
10516   mention (b);
10517   uiout->text (_("\n\
10518 Check the underlying instruction at PC for the memory\n\
10519 address and value which triggered this watchpoint.\n"));
10520   uiout->text ("\n");
10521
10522   /* More than one watchpoint may have been triggered.  */
10523   return PRINT_UNKNOWN;
10524 }
10525
10526 /* Implement the "print_one_detail" breakpoint_ops method for
10527    masked hardware watchpoints.  */
10528
10529 static void
10530 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10531                                     struct ui_out *uiout)
10532 {
10533   struct watchpoint *w = (struct watchpoint *) b;
10534
10535   /* Masked watchpoints have only one location.  */
10536   gdb_assert (b->loc && b->loc->next == NULL);
10537
10538   uiout->text ("\tmask ");
10539   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10540   uiout->text ("\n");
10541 }
10542
10543 /* Implement the "print_mention" breakpoint_ops method for
10544    masked hardware watchpoints.  */
10545
10546 static void
10547 print_mention_masked_watchpoint (struct breakpoint *b)
10548 {
10549   struct watchpoint *w = (struct watchpoint *) b;
10550   struct ui_out *uiout = current_uiout;
10551   const char *tuple_name;
10552
10553   switch (b->type)
10554     {
10555     case bp_hardware_watchpoint:
10556       uiout->text ("Masked hardware watchpoint ");
10557       tuple_name = "wpt";
10558       break;
10559     case bp_read_watchpoint:
10560       uiout->text ("Masked hardware read watchpoint ");
10561       tuple_name = "hw-rwpt";
10562       break;
10563     case bp_access_watchpoint:
10564       uiout->text ("Masked hardware access (read/write) watchpoint ");
10565       tuple_name = "hw-awpt";
10566       break;
10567     default:
10568       internal_error (__FILE__, __LINE__,
10569                       _("Invalid hardware watchpoint type."));
10570     }
10571
10572   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10573   uiout->field_int ("number", b->number);
10574   uiout->text (": ");
10575   uiout->field_string ("exp", w->exp_string);
10576 }
10577
10578 /* Implement the "print_recreate" breakpoint_ops method for
10579    masked hardware watchpoints.  */
10580
10581 static void
10582 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10583 {
10584   struct watchpoint *w = (struct watchpoint *) b;
10585   char tmp[40];
10586
10587   switch (b->type)
10588     {
10589     case bp_hardware_watchpoint:
10590       fprintf_unfiltered (fp, "watch");
10591       break;
10592     case bp_read_watchpoint:
10593       fprintf_unfiltered (fp, "rwatch");
10594       break;
10595     case bp_access_watchpoint:
10596       fprintf_unfiltered (fp, "awatch");
10597       break;
10598     default:
10599       internal_error (__FILE__, __LINE__,
10600                       _("Invalid hardware watchpoint type."));
10601     }
10602
10603   sprintf_vma (tmp, w->hw_wp_mask);
10604   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10605   print_recreate_thread (b, fp);
10606 }
10607
10608 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10609
10610 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10611
10612 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10613
10614 static int
10615 is_masked_watchpoint (const struct breakpoint *b)
10616 {
10617   return b->ops == &masked_watchpoint_breakpoint_ops;
10618 }
10619
10620 /* accessflag:  hw_write:  watch write, 
10621                 hw_read:   watch read, 
10622                 hw_access: watch access (read or write) */
10623 static void
10624 watch_command_1 (const char *arg, int accessflag, int from_tty,
10625                  int just_location, int internal)
10626 {
10627   struct breakpoint *scope_breakpoint = NULL;
10628   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10629   struct value *val, *mark, *result;
10630   int saved_bitpos = 0, saved_bitsize = 0;
10631   const char *exp_start = NULL;
10632   const char *exp_end = NULL;
10633   const char *tok, *end_tok;
10634   int toklen = -1;
10635   const char *cond_start = NULL;
10636   const char *cond_end = NULL;
10637   enum bptype bp_type;
10638   int thread = -1;
10639   int pc = 0;
10640   /* Flag to indicate whether we are going to use masks for
10641      the hardware watchpoint.  */
10642   int use_mask = 0;
10643   CORE_ADDR mask = 0;
10644
10645   /* Make sure that we actually have parameters to parse.  */
10646   if (arg != NULL && arg[0] != '\0')
10647     {
10648       const char *value_start;
10649
10650       exp_end = arg + strlen (arg);
10651
10652       /* Look for "parameter value" pairs at the end
10653          of the arguments string.  */
10654       for (tok = exp_end - 1; tok > arg; tok--)
10655         {
10656           /* Skip whitespace at the end of the argument list.  */
10657           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10658             tok--;
10659
10660           /* Find the beginning of the last token.
10661              This is the value of the parameter.  */
10662           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10663             tok--;
10664           value_start = tok + 1;
10665
10666           /* Skip whitespace.  */
10667           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10668             tok--;
10669
10670           end_tok = tok;
10671
10672           /* Find the beginning of the second to last token.
10673              This is the parameter itself.  */
10674           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10675             tok--;
10676           tok++;
10677           toklen = end_tok - tok + 1;
10678
10679           if (toklen == 6 && startswith (tok, "thread"))
10680             {
10681               struct thread_info *thr;
10682               /* At this point we've found a "thread" token, which means
10683                  the user is trying to set a watchpoint that triggers
10684                  only in a specific thread.  */
10685               const char *endp;
10686
10687               if (thread != -1)
10688                 error(_("You can specify only one thread."));
10689
10690               /* Extract the thread ID from the next token.  */
10691               thr = parse_thread_id (value_start, &endp);
10692
10693               /* Check if the user provided a valid thread ID.  */
10694               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10695                 invalid_thread_id_error (value_start);
10696
10697               thread = thr->global_num;
10698             }
10699           else if (toklen == 4 && startswith (tok, "mask"))
10700             {
10701               /* We've found a "mask" token, which means the user wants to
10702                  create a hardware watchpoint that is going to have the mask
10703                  facility.  */
10704               struct value *mask_value, *mark;
10705
10706               if (use_mask)
10707                 error(_("You can specify only one mask."));
10708
10709               use_mask = just_location = 1;
10710
10711               mark = value_mark ();
10712               mask_value = parse_to_comma_and_eval (&value_start);
10713               mask = value_as_address (mask_value);
10714               value_free_to_mark (mark);
10715             }
10716           else
10717             /* We didn't recognize what we found.  We should stop here.  */
10718             break;
10719
10720           /* Truncate the string and get rid of the "parameter value" pair before
10721              the arguments string is parsed by the parse_exp_1 function.  */
10722           exp_end = tok;
10723         }
10724     }
10725   else
10726     exp_end = arg;
10727
10728   /* Parse the rest of the arguments.  From here on out, everything
10729      is in terms of a newly allocated string instead of the original
10730      ARG.  */
10731   innermost_block = NULL;
10732   std::string expression (arg, exp_end - arg);
10733   exp_start = arg = expression.c_str ();
10734   expression_up exp = parse_exp_1 (&arg, 0, 0, 0);
10735   exp_end = arg;
10736   /* Remove trailing whitespace from the expression before saving it.
10737      This makes the eventual display of the expression string a bit
10738      prettier.  */
10739   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10740     --exp_end;
10741
10742   /* Checking if the expression is not constant.  */
10743   if (watchpoint_exp_is_const (exp.get ()))
10744     {
10745       int len;
10746
10747       len = exp_end - exp_start;
10748       while (len > 0 && isspace (exp_start[len - 1]))
10749         len--;
10750       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10751     }
10752
10753   exp_valid_block = innermost_block;
10754   mark = value_mark ();
10755   fetch_subexp_value (exp.get (), &pc, &val, &result, NULL, just_location);
10756
10757   if (val != NULL && just_location)
10758     {
10759       saved_bitpos = value_bitpos (val);
10760       saved_bitsize = value_bitsize (val);
10761     }
10762
10763   if (just_location)
10764     {
10765       int ret;
10766
10767       exp_valid_block = NULL;
10768       val = value_addr (result);
10769       release_value (val);
10770       value_free_to_mark (mark);
10771
10772       if (use_mask)
10773         {
10774           ret = target_masked_watch_num_registers (value_as_address (val),
10775                                                    mask);
10776           if (ret == -1)
10777             error (_("This target does not support masked watchpoints."));
10778           else if (ret == -2)
10779             error (_("Invalid mask or memory region."));
10780         }
10781     }
10782   else if (val != NULL)
10783     release_value (val);
10784
10785   tok = skip_spaces (arg);
10786   end_tok = skip_to_space (tok);
10787
10788   toklen = end_tok - tok;
10789   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10790     {
10791       innermost_block = NULL;
10792       tok = cond_start = end_tok + 1;
10793       parse_exp_1 (&tok, 0, 0, 0);
10794
10795       /* The watchpoint expression may not be local, but the condition
10796          may still be.  E.g.: `watch global if local > 0'.  */
10797       cond_exp_valid_block = innermost_block;
10798
10799       cond_end = tok;
10800     }
10801   if (*tok)
10802     error (_("Junk at end of command."));
10803
10804   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
10805
10806   /* Save this because create_internal_breakpoint below invalidates
10807      'wp_frame'.  */
10808   frame_id watchpoint_frame = get_frame_id (wp_frame);
10809
10810   /* If the expression is "local", then set up a "watchpoint scope"
10811      breakpoint at the point where we've left the scope of the watchpoint
10812      expression.  Create the scope breakpoint before the watchpoint, so
10813      that we will encounter it first in bpstat_stop_status.  */
10814   if (exp_valid_block != NULL && wp_frame != NULL)
10815     {
10816       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10817
10818       if (frame_id_p (caller_frame_id))
10819         {
10820           gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10821           CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10822
10823           scope_breakpoint
10824             = create_internal_breakpoint (caller_arch, caller_pc,
10825                                           bp_watchpoint_scope,
10826                                           &momentary_breakpoint_ops);
10827
10828           /* create_internal_breakpoint could invalidate WP_FRAME.  */
10829           wp_frame = NULL;
10830
10831           scope_breakpoint->enable_state = bp_enabled;
10832
10833           /* Automatically delete the breakpoint when it hits.  */
10834           scope_breakpoint->disposition = disp_del;
10835
10836           /* Only break in the proper frame (help with recursion).  */
10837           scope_breakpoint->frame_id = caller_frame_id;
10838
10839           /* Set the address at which we will stop.  */
10840           scope_breakpoint->loc->gdbarch = caller_arch;
10841           scope_breakpoint->loc->requested_address = caller_pc;
10842           scope_breakpoint->loc->address
10843             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10844                                          scope_breakpoint->loc->requested_address,
10845                                          scope_breakpoint->type);
10846         }
10847     }
10848
10849   /* Now set up the breakpoint.  We create all watchpoints as hardware
10850      watchpoints here even if hardware watchpoints are turned off, a call
10851      to update_watchpoint later in this function will cause the type to
10852      drop back to bp_watchpoint (software watchpoint) if required.  */
10853
10854   if (accessflag == hw_read)
10855     bp_type = bp_read_watchpoint;
10856   else if (accessflag == hw_access)
10857     bp_type = bp_access_watchpoint;
10858   else
10859     bp_type = bp_hardware_watchpoint;
10860
10861   std::unique_ptr<watchpoint> w (new watchpoint ());
10862
10863   if (use_mask)
10864     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10865                                           &masked_watchpoint_breakpoint_ops);
10866   else
10867     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10868                                           &watchpoint_breakpoint_ops);
10869   w->thread = thread;
10870   w->disposition = disp_donttouch;
10871   w->pspace = current_program_space;
10872   w->exp = std::move (exp);
10873   w->exp_valid_block = exp_valid_block;
10874   w->cond_exp_valid_block = cond_exp_valid_block;
10875   if (just_location)
10876     {
10877       struct type *t = value_type (val);
10878       CORE_ADDR addr = value_as_address (val);
10879
10880       w->exp_string_reparse
10881         = current_language->la_watch_location_expression (t, addr).release ();
10882
10883       w->exp_string = xstrprintf ("-location %.*s",
10884                                   (int) (exp_end - exp_start), exp_start);
10885     }
10886   else
10887     w->exp_string = savestring (exp_start, exp_end - exp_start);
10888
10889   if (use_mask)
10890     {
10891       w->hw_wp_mask = mask;
10892     }
10893   else
10894     {
10895       w->val = val;
10896       w->val_bitpos = saved_bitpos;
10897       w->val_bitsize = saved_bitsize;
10898       w->val_valid = 1;
10899     }
10900
10901   if (cond_start)
10902     w->cond_string = savestring (cond_start, cond_end - cond_start);
10903   else
10904     w->cond_string = 0;
10905
10906   if (frame_id_p (watchpoint_frame))
10907     {
10908       w->watchpoint_frame = watchpoint_frame;
10909       w->watchpoint_thread = inferior_ptid;
10910     }
10911   else
10912     {
10913       w->watchpoint_frame = null_frame_id;
10914       w->watchpoint_thread = null_ptid;
10915     }
10916
10917   if (scope_breakpoint != NULL)
10918     {
10919       /* The scope breakpoint is related to the watchpoint.  We will
10920          need to act on them together.  */
10921       w->related_breakpoint = scope_breakpoint;
10922       scope_breakpoint->related_breakpoint = w.get ();
10923     }
10924
10925   if (!just_location)
10926     value_free_to_mark (mark);
10927
10928   /* Finally update the new watchpoint.  This creates the locations
10929      that should be inserted.  */
10930   update_watchpoint (w.get (), 1);
10931
10932   install_breakpoint (internal, std::move (w), 1);
10933 }
10934
10935 /* Return count of debug registers needed to watch the given expression.
10936    If the watchpoint cannot be handled in hardware return zero.  */
10937
10938 static int
10939 can_use_hardware_watchpoint (struct value *v)
10940 {
10941   int found_memory_cnt = 0;
10942   struct value *head = v;
10943
10944   /* Did the user specifically forbid us to use hardware watchpoints? */
10945   if (!can_use_hw_watchpoints)
10946     return 0;
10947
10948   /* Make sure that the value of the expression depends only upon
10949      memory contents, and values computed from them within GDB.  If we
10950      find any register references or function calls, we can't use a
10951      hardware watchpoint.
10952
10953      The idea here is that evaluating an expression generates a series
10954      of values, one holding the value of every subexpression.  (The
10955      expression a*b+c has five subexpressions: a, b, a*b, c, and
10956      a*b+c.)  GDB's values hold almost enough information to establish
10957      the criteria given above --- they identify memory lvalues,
10958      register lvalues, computed values, etcetera.  So we can evaluate
10959      the expression, and then scan the chain of values that leaves
10960      behind to decide whether we can detect any possible change to the
10961      expression's final value using only hardware watchpoints.
10962
10963      However, I don't think that the values returned by inferior
10964      function calls are special in any way.  So this function may not
10965      notice that an expression involving an inferior function call
10966      can't be watched with hardware watchpoints.  FIXME.  */
10967   for (; v; v = value_next (v))
10968     {
10969       if (VALUE_LVAL (v) == lval_memory)
10970         {
10971           if (v != head && value_lazy (v))
10972             /* A lazy memory lvalue in the chain is one that GDB never
10973                needed to fetch; we either just used its address (e.g.,
10974                `a' in `a.b') or we never needed it at all (e.g., `a'
10975                in `a,b').  This doesn't apply to HEAD; if that is
10976                lazy then it was not readable, but watch it anyway.  */
10977             ;
10978           else
10979             {
10980               /* Ahh, memory we actually used!  Check if we can cover
10981                  it with hardware watchpoints.  */
10982               struct type *vtype = check_typedef (value_type (v));
10983
10984               /* We only watch structs and arrays if user asked for it
10985                  explicitly, never if they just happen to appear in a
10986                  middle of some value chain.  */
10987               if (v == head
10988                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
10989                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
10990                 {
10991                   CORE_ADDR vaddr = value_address (v);
10992                   int len;
10993                   int num_regs;
10994
10995                   len = (target_exact_watchpoints
10996                          && is_scalar_type_recursive (vtype))?
10997                     1 : TYPE_LENGTH (value_type (v));
10998
10999                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11000                   if (!num_regs)
11001                     return 0;
11002                   else
11003                     found_memory_cnt += num_regs;
11004                 }
11005             }
11006         }
11007       else if (VALUE_LVAL (v) != not_lval
11008                && deprecated_value_modifiable (v) == 0)
11009         return 0;       /* These are values from the history (e.g., $1).  */
11010       else if (VALUE_LVAL (v) == lval_register)
11011         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11012     }
11013
11014   /* The expression itself looks suitable for using a hardware
11015      watchpoint, but give the target machine a chance to reject it.  */
11016   return found_memory_cnt;
11017 }
11018
11019 void
11020 watch_command_wrapper (const char *arg, int from_tty, int internal)
11021 {
11022   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11023 }
11024
11025 /* A helper function that looks for the "-location" argument and then
11026    calls watch_command_1.  */
11027
11028 static void
11029 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
11030 {
11031   int just_location = 0;
11032
11033   if (arg
11034       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11035           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11036     {
11037       arg = skip_spaces (arg);
11038       just_location = 1;
11039     }
11040
11041   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11042 }
11043
11044 static void
11045 watch_command (const char *arg, int from_tty)
11046 {
11047   watch_maybe_just_location (arg, hw_write, from_tty);
11048 }
11049
11050 void
11051 rwatch_command_wrapper (const char *arg, int from_tty, int internal)
11052 {
11053   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11054 }
11055
11056 static void
11057 rwatch_command (const char *arg, int from_tty)
11058 {
11059   watch_maybe_just_location (arg, hw_read, from_tty);
11060 }
11061
11062 void
11063 awatch_command_wrapper (const char *arg, int from_tty, int internal)
11064 {
11065   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11066 }
11067
11068 static void
11069 awatch_command (const char *arg, int from_tty)
11070 {
11071   watch_maybe_just_location (arg, hw_access, from_tty);
11072 }
11073 \f
11074
11075 /* Data for the FSM that manages the until(location)/advance commands
11076    in infcmd.c.  Here because it uses the mechanisms of
11077    breakpoints.  */
11078
11079 struct until_break_fsm
11080 {
11081   /* The base class.  */
11082   struct thread_fsm thread_fsm;
11083
11084   /* The thread that as current when the command was executed.  */
11085   int thread;
11086
11087   /* The breakpoint set at the destination location.  */
11088   struct breakpoint *location_breakpoint;
11089
11090   /* Breakpoint set at the return address in the caller frame.  May be
11091      NULL.  */
11092   struct breakpoint *caller_breakpoint;
11093 };
11094
11095 static void until_break_fsm_clean_up (struct thread_fsm *self,
11096                                       struct thread_info *thread);
11097 static int until_break_fsm_should_stop (struct thread_fsm *self,
11098                                         struct thread_info *thread);
11099 static enum async_reply_reason
11100   until_break_fsm_async_reply_reason (struct thread_fsm *self);
11101
11102 /* until_break_fsm's vtable.  */
11103
11104 static struct thread_fsm_ops until_break_fsm_ops =
11105 {
11106   NULL, /* dtor */
11107   until_break_fsm_clean_up,
11108   until_break_fsm_should_stop,
11109   NULL, /* return_value */
11110   until_break_fsm_async_reply_reason,
11111 };
11112
11113 /* Allocate a new until_break_command_fsm.  */
11114
11115 static struct until_break_fsm *
11116 new_until_break_fsm (struct interp *cmd_interp, int thread,
11117                      breakpoint_up &&location_breakpoint,
11118                      breakpoint_up &&caller_breakpoint)
11119 {
11120   struct until_break_fsm *sm;
11121
11122   sm = XCNEW (struct until_break_fsm);
11123   thread_fsm_ctor (&sm->thread_fsm, &until_break_fsm_ops, cmd_interp);
11124
11125   sm->thread = thread;
11126   sm->location_breakpoint = location_breakpoint.release ();
11127   sm->caller_breakpoint = caller_breakpoint.release ();
11128
11129   return sm;
11130 }
11131
11132 /* Implementation of the 'should_stop' FSM method for the
11133    until(location)/advance commands.  */
11134
11135 static int
11136 until_break_fsm_should_stop (struct thread_fsm *self,
11137                              struct thread_info *tp)
11138 {
11139   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11140
11141   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11142                               sm->location_breakpoint) != NULL
11143       || (sm->caller_breakpoint != NULL
11144           && bpstat_find_breakpoint (tp->control.stop_bpstat,
11145                                      sm->caller_breakpoint) != NULL))
11146     thread_fsm_set_finished (self);
11147
11148   return 1;
11149 }
11150
11151 /* Implementation of the 'clean_up' FSM method for the
11152    until(location)/advance commands.  */
11153
11154 static void
11155 until_break_fsm_clean_up (struct thread_fsm *self,
11156                           struct thread_info *thread)
11157 {
11158   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11159
11160   /* Clean up our temporary breakpoints.  */
11161   if (sm->location_breakpoint != NULL)
11162     {
11163       delete_breakpoint (sm->location_breakpoint);
11164       sm->location_breakpoint = NULL;
11165     }
11166   if (sm->caller_breakpoint != NULL)
11167     {
11168       delete_breakpoint (sm->caller_breakpoint);
11169       sm->caller_breakpoint = NULL;
11170     }
11171   delete_longjmp_breakpoint (sm->thread);
11172 }
11173
11174 /* Implementation of the 'async_reply_reason' FSM method for the
11175    until(location)/advance commands.  */
11176
11177 static enum async_reply_reason
11178 until_break_fsm_async_reply_reason (struct thread_fsm *self)
11179 {
11180   return EXEC_ASYNC_LOCATION_REACHED;
11181 }
11182
11183 void
11184 until_break_command (const char *arg, int from_tty, int anywhere)
11185 {
11186   struct frame_info *frame;
11187   struct gdbarch *frame_gdbarch;
11188   struct frame_id stack_frame_id;
11189   struct frame_id caller_frame_id;
11190   struct cleanup *old_chain;
11191   int thread;
11192   struct thread_info *tp;
11193   struct until_break_fsm *sm;
11194
11195   clear_proceed_status (0);
11196
11197   /* Set a breakpoint where the user wants it and at return from
11198      this function.  */
11199
11200   event_location_up location = string_to_event_location (&arg, current_language);
11201
11202   std::vector<symtab_and_line> sals
11203     = (last_displayed_sal_is_valid ()
11204        ? decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
11205                         get_last_displayed_symtab (),
11206                         get_last_displayed_line ())
11207        : decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
11208                         NULL, (struct symtab *) NULL, 0));
11209
11210   if (sals.size () != 1)
11211     error (_("Couldn't get information on specified line."));
11212
11213   symtab_and_line &sal = sals[0];
11214
11215   if (*arg)
11216     error (_("Junk at end of arguments."));
11217
11218   resolve_sal_pc (&sal);
11219
11220   tp = inferior_thread ();
11221   thread = tp->global_num;
11222
11223   old_chain = make_cleanup (null_cleanup, NULL);
11224
11225   /* Note linespec handling above invalidates the frame chain.
11226      Installing a breakpoint also invalidates the frame chain (as it
11227      may need to switch threads), so do any frame handling before
11228      that.  */
11229
11230   frame = get_selected_frame (NULL);
11231   frame_gdbarch = get_frame_arch (frame);
11232   stack_frame_id = get_stack_frame_id (frame);
11233   caller_frame_id = frame_unwind_caller_id (frame);
11234
11235   /* Keep within the current frame, or in frames called by the current
11236      one.  */
11237
11238   breakpoint_up caller_breakpoint;
11239   if (frame_id_p (caller_frame_id))
11240     {
11241       struct symtab_and_line sal2;
11242       struct gdbarch *caller_gdbarch;
11243
11244       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11245       sal2.pc = frame_unwind_caller_pc (frame);
11246       caller_gdbarch = frame_unwind_caller_arch (frame);
11247       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11248                                                     sal2,
11249                                                     caller_frame_id,
11250                                                     bp_until);
11251
11252       set_longjmp_breakpoint (tp, caller_frame_id);
11253       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11254     }
11255
11256   /* set_momentary_breakpoint could invalidate FRAME.  */
11257   frame = NULL;
11258
11259   breakpoint_up location_breakpoint;
11260   if (anywhere)
11261     /* If the user told us to continue until a specified location,
11262        we don't specify a frame at which we need to stop.  */
11263     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11264                                                     null_frame_id, bp_until);
11265   else
11266     /* Otherwise, specify the selected frame, because we want to stop
11267        only at the very same frame.  */
11268     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11269                                                     stack_frame_id, bp_until);
11270
11271   sm = new_until_break_fsm (command_interp (), tp->global_num,
11272                             std::move (location_breakpoint),
11273                             std::move (caller_breakpoint));
11274   tp->thread_fsm = &sm->thread_fsm;
11275
11276   discard_cleanups (old_chain);
11277
11278   proceed (-1, GDB_SIGNAL_DEFAULT);
11279 }
11280
11281 /* This function attempts to parse an optional "if <cond>" clause
11282    from the arg string.  If one is not found, it returns NULL.
11283
11284    Else, it returns a pointer to the condition string.  (It does not
11285    attempt to evaluate the string against a particular block.)  And,
11286    it updates arg to point to the first character following the parsed
11287    if clause in the arg string.  */
11288
11289 const char *
11290 ep_parse_optional_if_clause (const char **arg)
11291 {
11292   const char *cond_string;
11293
11294   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11295     return NULL;
11296
11297   /* Skip the "if" keyword.  */
11298   (*arg) += 2;
11299
11300   /* Skip any extra leading whitespace, and record the start of the
11301      condition string.  */
11302   *arg = skip_spaces (*arg);
11303   cond_string = *arg;
11304
11305   /* Assume that the condition occupies the remainder of the arg
11306      string.  */
11307   (*arg) += strlen (cond_string);
11308
11309   return cond_string;
11310 }
11311
11312 /* Commands to deal with catching events, such as signals, exceptions,
11313    process start/exit, etc.  */
11314
11315 typedef enum
11316 {
11317   catch_fork_temporary, catch_vfork_temporary,
11318   catch_fork_permanent, catch_vfork_permanent
11319 }
11320 catch_fork_kind;
11321
11322 static void
11323 catch_fork_command_1 (const char *arg, int from_tty,
11324                       struct cmd_list_element *command)
11325 {
11326   struct gdbarch *gdbarch = get_current_arch ();
11327   const char *cond_string = NULL;
11328   catch_fork_kind fork_kind;
11329   int tempflag;
11330
11331   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11332   tempflag = (fork_kind == catch_fork_temporary
11333               || fork_kind == catch_vfork_temporary);
11334
11335   if (!arg)
11336     arg = "";
11337   arg = skip_spaces (arg);
11338
11339   /* The allowed syntax is:
11340      catch [v]fork
11341      catch [v]fork if <cond>
11342
11343      First, check if there's an if clause.  */
11344   cond_string = ep_parse_optional_if_clause (&arg);
11345
11346   if ((*arg != '\0') && !isspace (*arg))
11347     error (_("Junk at end of arguments."));
11348
11349   /* If this target supports it, create a fork or vfork catchpoint
11350      and enable reporting of such events.  */
11351   switch (fork_kind)
11352     {
11353     case catch_fork_temporary:
11354     case catch_fork_permanent:
11355       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11356                                           &catch_fork_breakpoint_ops);
11357       break;
11358     case catch_vfork_temporary:
11359     case catch_vfork_permanent:
11360       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11361                                           &catch_vfork_breakpoint_ops);
11362       break;
11363     default:
11364       error (_("unsupported or unknown fork kind; cannot catch it"));
11365       break;
11366     }
11367 }
11368
11369 static void
11370 catch_exec_command_1 (const char *arg, int from_tty,
11371                       struct cmd_list_element *command)
11372 {
11373   struct gdbarch *gdbarch = get_current_arch ();
11374   int tempflag;
11375   const char *cond_string = NULL;
11376
11377   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11378
11379   if (!arg)
11380     arg = "";
11381   arg = skip_spaces (arg);
11382
11383   /* The allowed syntax is:
11384      catch exec
11385      catch exec if <cond>
11386
11387      First, check if there's an if clause.  */
11388   cond_string = ep_parse_optional_if_clause (&arg);
11389
11390   if ((*arg != '\0') && !isspace (*arg))
11391     error (_("Junk at end of arguments."));
11392
11393   std::unique_ptr<exec_catchpoint> c (new exec_catchpoint ());
11394   init_catchpoint (c.get (), gdbarch, tempflag, cond_string,
11395                    &catch_exec_breakpoint_ops);
11396   c->exec_pathname = NULL;
11397
11398   install_breakpoint (0, std::move (c), 1);
11399 }
11400
11401 void
11402 init_ada_exception_breakpoint (struct breakpoint *b,
11403                                struct gdbarch *gdbarch,
11404                                struct symtab_and_line sal,
11405                                const char *addr_string,
11406                                const struct breakpoint_ops *ops,
11407                                int tempflag,
11408                                int enabled,
11409                                int from_tty)
11410 {
11411   if (from_tty)
11412     {
11413       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11414       if (!loc_gdbarch)
11415         loc_gdbarch = gdbarch;
11416
11417       describe_other_breakpoints (loc_gdbarch,
11418                                   sal.pspace, sal.pc, sal.section, -1);
11419       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11420          version for exception catchpoints, because two catchpoints
11421          used for different exception names will use the same address.
11422          In this case, a "breakpoint ... also set at..." warning is
11423          unproductive.  Besides, the warning phrasing is also a bit
11424          inappropriate, we should use the word catchpoint, and tell
11425          the user what type of catchpoint it is.  The above is good
11426          enough for now, though.  */
11427     }
11428
11429   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11430
11431   b->enable_state = enabled ? bp_enabled : bp_disabled;
11432   b->disposition = tempflag ? disp_del : disp_donttouch;
11433   b->location = string_to_event_location (&addr_string,
11434                                           language_def (language_ada));
11435   b->language = language_ada;
11436 }
11437
11438 static void
11439 catch_command (const char *arg, int from_tty)
11440 {
11441   error (_("Catch requires an event name."));
11442 }
11443 \f
11444
11445 static void
11446 tcatch_command (const char *arg, int from_tty)
11447 {
11448   error (_("Catch requires an event name."));
11449 }
11450
11451 /* Compare two breakpoints and return a strcmp-like result.  */
11452
11453 static int
11454 compare_breakpoints (const breakpoint *a, const breakpoint *b)
11455 {
11456   uintptr_t ua = (uintptr_t) a;
11457   uintptr_t ub = (uintptr_t) b;
11458
11459   if (a->number < b->number)
11460     return -1;
11461   else if (a->number > b->number)
11462     return 1;
11463
11464   /* Now sort by address, in case we see, e..g, two breakpoints with
11465      the number 0.  */
11466   if (ua < ub)
11467     return -1;
11468   return ua > ub ? 1 : 0;
11469 }
11470
11471 /* Delete breakpoints by address or line.  */
11472
11473 static void
11474 clear_command (const char *arg, int from_tty)
11475 {
11476   struct breakpoint *b;
11477   int default_match;
11478
11479   std::vector<symtab_and_line> decoded_sals;
11480   symtab_and_line last_sal;
11481   gdb::array_view<symtab_and_line> sals;
11482   if (arg)
11483     {
11484       decoded_sals
11485         = decode_line_with_current_source (arg,
11486                                            (DECODE_LINE_FUNFIRSTLINE
11487                                             | DECODE_LINE_LIST_MODE));
11488       default_match = 0;
11489       sals = decoded_sals;
11490     }
11491   else
11492     {
11493       /* Set sal's line, symtab, pc, and pspace to the values
11494          corresponding to the last call to print_frame_info.  If the
11495          codepoint is not valid, this will set all the fields to 0.  */
11496       last_sal = get_last_displayed_sal ();
11497       if (last_sal.symtab == 0)
11498         error (_("No source file specified."));
11499
11500       default_match = 1;
11501       sals = last_sal;
11502     }
11503
11504   /* We don't call resolve_sal_pc here.  That's not as bad as it
11505      seems, because all existing breakpoints typically have both
11506      file/line and pc set.  So, if clear is given file/line, we can
11507      match this to existing breakpoint without obtaining pc at all.
11508
11509      We only support clearing given the address explicitly 
11510      present in breakpoint table.  Say, we've set breakpoint 
11511      at file:line.  There were several PC values for that file:line,
11512      due to optimization, all in one block.
11513
11514      We've picked one PC value.  If "clear" is issued with another
11515      PC corresponding to the same file:line, the breakpoint won't
11516      be cleared.  We probably can still clear the breakpoint, but 
11517      since the other PC value is never presented to user, user
11518      can only find it by guessing, and it does not seem important
11519      to support that.  */
11520
11521   /* For each line spec given, delete bps which correspond to it.  Do
11522      it in two passes, solely to preserve the current behavior that
11523      from_tty is forced true if we delete more than one
11524      breakpoint.  */
11525
11526   std::vector<struct breakpoint *> found;
11527   for (const auto &sal : sals)
11528     {
11529       const char *sal_fullname;
11530
11531       /* If exact pc given, clear bpts at that pc.
11532          If line given (pc == 0), clear all bpts on specified line.
11533          If defaulting, clear all bpts on default line
11534          or at default pc.
11535
11536          defaulting    sal.pc != 0    tests to do
11537
11538          0              1             pc
11539          1              1             pc _and_ line
11540          0              0             line
11541          1              0             <can't happen> */
11542
11543       sal_fullname = (sal.symtab == NULL
11544                       ? NULL : symtab_to_fullname (sal.symtab));
11545
11546       /* Find all matching breakpoints and add them to 'found'.  */
11547       ALL_BREAKPOINTS (b)
11548         {
11549           int match = 0;
11550           /* Are we going to delete b?  */
11551           if (b->type != bp_none && !is_watchpoint (b))
11552             {
11553               struct bp_location *loc = b->loc;
11554               for (; loc; loc = loc->next)
11555                 {
11556                   /* If the user specified file:line, don't allow a PC
11557                      match.  This matches historical gdb behavior.  */
11558                   int pc_match = (!sal.explicit_line
11559                                   && sal.pc
11560                                   && (loc->pspace == sal.pspace)
11561                                   && (loc->address == sal.pc)
11562                                   && (!section_is_overlay (loc->section)
11563                                       || loc->section == sal.section));
11564                   int line_match = 0;
11565
11566                   if ((default_match || sal.explicit_line)
11567                       && loc->symtab != NULL
11568                       && sal_fullname != NULL
11569                       && sal.pspace == loc->pspace
11570                       && loc->line_number == sal.line
11571                       && filename_cmp (symtab_to_fullname (loc->symtab),
11572                                        sal_fullname) == 0)
11573                     line_match = 1;
11574
11575                   if (pc_match || line_match)
11576                     {
11577                       match = 1;
11578                       break;
11579                     }
11580                 }
11581             }
11582
11583           if (match)
11584             found.push_back (b);
11585         }
11586     }
11587
11588   /* Now go thru the 'found' chain and delete them.  */
11589   if (found.empty ())
11590     {
11591       if (arg)
11592         error (_("No breakpoint at %s."), arg);
11593       else
11594         error (_("No breakpoint at this line."));
11595     }
11596
11597   /* Remove duplicates from the vec.  */
11598   std::sort (found.begin (), found.end (),
11599              [] (const breakpoint *a, const breakpoint *b)
11600              {
11601                return compare_breakpoints (a, b) < 0;
11602              });
11603   found.erase (std::unique (found.begin (), found.end (),
11604                             [] (const breakpoint *a, const breakpoint *b)
11605                             {
11606                               return compare_breakpoints (a, b) == 0;
11607                             }),
11608                found.end ());
11609
11610   if (found.size () > 1)
11611     from_tty = 1;       /* Always report if deleted more than one.  */
11612   if (from_tty)
11613     {
11614       if (found.size () == 1)
11615         printf_unfiltered (_("Deleted breakpoint "));
11616       else
11617         printf_unfiltered (_("Deleted breakpoints "));
11618     }
11619
11620   for (breakpoint *iter : found)
11621     {
11622       if (from_tty)
11623         printf_unfiltered ("%d ", iter->number);
11624       delete_breakpoint (iter);
11625     }
11626   if (from_tty)
11627     putchar_unfiltered ('\n');
11628 }
11629 \f
11630 /* Delete breakpoint in BS if they are `delete' breakpoints and
11631    all breakpoints that are marked for deletion, whether hit or not.
11632    This is called after any breakpoint is hit, or after errors.  */
11633
11634 void
11635 breakpoint_auto_delete (bpstat bs)
11636 {
11637   struct breakpoint *b, *b_tmp;
11638
11639   for (; bs; bs = bs->next)
11640     if (bs->breakpoint_at
11641         && bs->breakpoint_at->disposition == disp_del
11642         && bs->stop)
11643       delete_breakpoint (bs->breakpoint_at);
11644
11645   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11646   {
11647     if (b->disposition == disp_del_at_next_stop)
11648       delete_breakpoint (b);
11649   }
11650 }
11651
11652 /* A comparison function for bp_location AP and BP being interfaced to
11653    qsort.  Sort elements primarily by their ADDRESS (no matter what
11654    does breakpoint_address_is_meaningful say for its OWNER),
11655    secondarily by ordering first permanent elements and
11656    terciarily just ensuring the array is sorted stable way despite
11657    qsort being an unstable algorithm.  */
11658
11659 static int
11660 bp_locations_compare (const void *ap, const void *bp)
11661 {
11662   const struct bp_location *a = *(const struct bp_location **) ap;
11663   const struct bp_location *b = *(const struct bp_location **) bp;
11664
11665   if (a->address != b->address)
11666     return (a->address > b->address) - (a->address < b->address);
11667
11668   /* Sort locations at the same address by their pspace number, keeping
11669      locations of the same inferior (in a multi-inferior environment)
11670      grouped.  */
11671
11672   if (a->pspace->num != b->pspace->num)
11673     return ((a->pspace->num > b->pspace->num)
11674             - (a->pspace->num < b->pspace->num));
11675
11676   /* Sort permanent breakpoints first.  */
11677   if (a->permanent != b->permanent)
11678     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
11679
11680   /* Make the internal GDB representation stable across GDB runs
11681      where A and B memory inside GDB can differ.  Breakpoint locations of
11682      the same type at the same address can be sorted in arbitrary order.  */
11683
11684   if (a->owner->number != b->owner->number)
11685     return ((a->owner->number > b->owner->number)
11686             - (a->owner->number < b->owner->number));
11687
11688   return (a > b) - (a < b);
11689 }
11690
11691 /* Set bp_locations_placed_address_before_address_max and
11692    bp_locations_shadow_len_after_address_max according to the current
11693    content of the bp_locations array.  */
11694
11695 static void
11696 bp_locations_target_extensions_update (void)
11697 {
11698   struct bp_location *bl, **blp_tmp;
11699
11700   bp_locations_placed_address_before_address_max = 0;
11701   bp_locations_shadow_len_after_address_max = 0;
11702
11703   ALL_BP_LOCATIONS (bl, blp_tmp)
11704     {
11705       CORE_ADDR start, end, addr;
11706
11707       if (!bp_location_has_shadow (bl))
11708         continue;
11709
11710       start = bl->target_info.placed_address;
11711       end = start + bl->target_info.shadow_len;
11712
11713       gdb_assert (bl->address >= start);
11714       addr = bl->address - start;
11715       if (addr > bp_locations_placed_address_before_address_max)
11716         bp_locations_placed_address_before_address_max = addr;
11717
11718       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11719
11720       gdb_assert (bl->address < end);
11721       addr = end - bl->address;
11722       if (addr > bp_locations_shadow_len_after_address_max)
11723         bp_locations_shadow_len_after_address_max = addr;
11724     }
11725 }
11726
11727 /* Download tracepoint locations if they haven't been.  */
11728
11729 static void
11730 download_tracepoint_locations (void)
11731 {
11732   struct breakpoint *b;
11733   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11734
11735   scoped_restore_current_pspace_and_thread restore_pspace_thread;
11736
11737   ALL_TRACEPOINTS (b)
11738     {
11739       struct bp_location *bl;
11740       struct tracepoint *t;
11741       int bp_location_downloaded = 0;
11742
11743       if ((b->type == bp_fast_tracepoint
11744            ? !may_insert_fast_tracepoints
11745            : !may_insert_tracepoints))
11746         continue;
11747
11748       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11749         {
11750           if (target_can_download_tracepoint ())
11751             can_download_tracepoint = TRIBOOL_TRUE;
11752           else
11753             can_download_tracepoint = TRIBOOL_FALSE;
11754         }
11755
11756       if (can_download_tracepoint == TRIBOOL_FALSE)
11757         break;
11758
11759       for (bl = b->loc; bl; bl = bl->next)
11760         {
11761           /* In tracepoint, locations are _never_ duplicated, so
11762              should_be_inserted is equivalent to
11763              unduplicated_should_be_inserted.  */
11764           if (!should_be_inserted (bl) || bl->inserted)
11765             continue;
11766
11767           switch_to_program_space_and_thread (bl->pspace);
11768
11769           target_download_tracepoint (bl);
11770
11771           bl->inserted = 1;
11772           bp_location_downloaded = 1;
11773         }
11774       t = (struct tracepoint *) b;
11775       t->number_on_target = b->number;
11776       if (bp_location_downloaded)
11777         observer_notify_breakpoint_modified (b);
11778     }
11779 }
11780
11781 /* Swap the insertion/duplication state between two locations.  */
11782
11783 static void
11784 swap_insertion (struct bp_location *left, struct bp_location *right)
11785 {
11786   const int left_inserted = left->inserted;
11787   const int left_duplicate = left->duplicate;
11788   const int left_needs_update = left->needs_update;
11789   const struct bp_target_info left_target_info = left->target_info;
11790
11791   /* Locations of tracepoints can never be duplicated.  */
11792   if (is_tracepoint (left->owner))
11793     gdb_assert (!left->duplicate);
11794   if (is_tracepoint (right->owner))
11795     gdb_assert (!right->duplicate);
11796
11797   left->inserted = right->inserted;
11798   left->duplicate = right->duplicate;
11799   left->needs_update = right->needs_update;
11800   left->target_info = right->target_info;
11801   right->inserted = left_inserted;
11802   right->duplicate = left_duplicate;
11803   right->needs_update = left_needs_update;
11804   right->target_info = left_target_info;
11805 }
11806
11807 /* Force the re-insertion of the locations at ADDRESS.  This is called
11808    once a new/deleted/modified duplicate location is found and we are evaluating
11809    conditions on the target's side.  Such conditions need to be updated on
11810    the target.  */
11811
11812 static void
11813 force_breakpoint_reinsertion (struct bp_location *bl)
11814 {
11815   struct bp_location **locp = NULL, **loc2p;
11816   struct bp_location *loc;
11817   CORE_ADDR address = 0;
11818   int pspace_num;
11819
11820   address = bl->address;
11821   pspace_num = bl->pspace->num;
11822
11823   /* This is only meaningful if the target is
11824      evaluating conditions and if the user has
11825      opted for condition evaluation on the target's
11826      side.  */
11827   if (gdb_evaluates_breakpoint_condition_p ()
11828       || !target_supports_evaluation_of_breakpoint_conditions ())
11829     return;
11830
11831   /* Flag all breakpoint locations with this address and
11832      the same program space as the location
11833      as "its condition has changed".  We need to
11834      update the conditions on the target's side.  */
11835   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11836     {
11837       loc = *loc2p;
11838
11839       if (!is_breakpoint (loc->owner)
11840           || pspace_num != loc->pspace->num)
11841         continue;
11842
11843       /* Flag the location appropriately.  We use a different state to
11844          let everyone know that we already updated the set of locations
11845          with addr bl->address and program space bl->pspace.  This is so
11846          we don't have to keep calling these functions just to mark locations
11847          that have already been marked.  */
11848       loc->condition_changed = condition_updated;
11849
11850       /* Free the agent expression bytecode as well.  We will compute
11851          it later on.  */
11852       loc->cond_bytecode.reset ();
11853     }
11854 }
11855 /* Called whether new breakpoints are created, or existing breakpoints
11856    deleted, to update the global location list and recompute which
11857    locations are duplicate of which.
11858
11859    The INSERT_MODE flag determines whether locations may not, may, or
11860    shall be inserted now.  See 'enum ugll_insert_mode' for more
11861    info.  */
11862
11863 static void
11864 update_global_location_list (enum ugll_insert_mode insert_mode)
11865 {
11866   struct breakpoint *b;
11867   struct bp_location **locp, *loc;
11868   /* Last breakpoint location address that was marked for update.  */
11869   CORE_ADDR last_addr = 0;
11870   /* Last breakpoint location program space that was marked for update.  */
11871   int last_pspace_num = -1;
11872
11873   /* Used in the duplicates detection below.  When iterating over all
11874      bp_locations, points to the first bp_location of a given address.
11875      Breakpoints and watchpoints of different types are never
11876      duplicates of each other.  Keep one pointer for each type of
11877      breakpoint/watchpoint, so we only need to loop over all locations
11878      once.  */
11879   struct bp_location *bp_loc_first;  /* breakpoint */
11880   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11881   struct bp_location *awp_loc_first; /* access watchpoint */
11882   struct bp_location *rwp_loc_first; /* read watchpoint */
11883
11884   /* Saved former bp_locations array which we compare against the newly
11885      built bp_locations from the current state of ALL_BREAKPOINTS.  */
11886   struct bp_location **old_locp;
11887   unsigned old_locations_count;
11888   gdb::unique_xmalloc_ptr<struct bp_location *> old_locations (bp_locations);
11889
11890   old_locations_count = bp_locations_count;
11891   bp_locations = NULL;
11892   bp_locations_count = 0;
11893
11894   ALL_BREAKPOINTS (b)
11895     for (loc = b->loc; loc; loc = loc->next)
11896       bp_locations_count++;
11897
11898   bp_locations = XNEWVEC (struct bp_location *, bp_locations_count);
11899   locp = bp_locations;
11900   ALL_BREAKPOINTS (b)
11901     for (loc = b->loc; loc; loc = loc->next)
11902       *locp++ = loc;
11903   qsort (bp_locations, bp_locations_count, sizeof (*bp_locations),
11904          bp_locations_compare);
11905
11906   bp_locations_target_extensions_update ();
11907
11908   /* Identify bp_location instances that are no longer present in the
11909      new list, and therefore should be freed.  Note that it's not
11910      necessary that those locations should be removed from inferior --
11911      if there's another location at the same address (previously
11912      marked as duplicate), we don't need to remove/insert the
11913      location.
11914      
11915      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11916      and former bp_location array state respectively.  */
11917
11918   locp = bp_locations;
11919   for (old_locp = old_locations.get ();
11920        old_locp < old_locations.get () + old_locations_count;
11921        old_locp++)
11922     {
11923       struct bp_location *old_loc = *old_locp;
11924       struct bp_location **loc2p;
11925
11926       /* Tells if 'old_loc' is found among the new locations.  If
11927          not, we have to free it.  */
11928       int found_object = 0;
11929       /* Tells if the location should remain inserted in the target.  */
11930       int keep_in_target = 0;
11931       int removed = 0;
11932
11933       /* Skip LOCP entries which will definitely never be needed.
11934          Stop either at or being the one matching OLD_LOC.  */
11935       while (locp < bp_locations + bp_locations_count
11936              && (*locp)->address < old_loc->address)
11937         locp++;
11938
11939       for (loc2p = locp;
11940            (loc2p < bp_locations + bp_locations_count
11941             && (*loc2p)->address == old_loc->address);
11942            loc2p++)
11943         {
11944           /* Check if this is a new/duplicated location or a duplicated
11945              location that had its condition modified.  If so, we want to send
11946              its condition to the target if evaluation of conditions is taking
11947              place there.  */
11948           if ((*loc2p)->condition_changed == condition_modified
11949               && (last_addr != old_loc->address
11950                   || last_pspace_num != old_loc->pspace->num))
11951             {
11952               force_breakpoint_reinsertion (*loc2p);
11953               last_pspace_num = old_loc->pspace->num;
11954             }
11955
11956           if (*loc2p == old_loc)
11957             found_object = 1;
11958         }
11959
11960       /* We have already handled this address, update it so that we don't
11961          have to go through updates again.  */
11962       last_addr = old_loc->address;
11963
11964       /* Target-side condition evaluation: Handle deleted locations.  */
11965       if (!found_object)
11966         force_breakpoint_reinsertion (old_loc);
11967
11968       /* If this location is no longer present, and inserted, look if
11969          there's maybe a new location at the same address.  If so,
11970          mark that one inserted, and don't remove this one.  This is
11971          needed so that we don't have a time window where a breakpoint
11972          at certain location is not inserted.  */
11973
11974       if (old_loc->inserted)
11975         {
11976           /* If the location is inserted now, we might have to remove
11977              it.  */
11978
11979           if (found_object && should_be_inserted (old_loc))
11980             {
11981               /* The location is still present in the location list,
11982                  and still should be inserted.  Don't do anything.  */
11983               keep_in_target = 1;
11984             }
11985           else
11986             {
11987               /* This location still exists, but it won't be kept in the
11988                  target since it may have been disabled.  We proceed to
11989                  remove its target-side condition.  */
11990
11991               /* The location is either no longer present, or got
11992                  disabled.  See if there's another location at the
11993                  same address, in which case we don't need to remove
11994                  this one from the target.  */
11995
11996               /* OLD_LOC comes from existing struct breakpoint.  */
11997               if (breakpoint_address_is_meaningful (old_loc->owner))
11998                 {
11999                   for (loc2p = locp;
12000                        (loc2p < bp_locations + bp_locations_count
12001                         && (*loc2p)->address == old_loc->address);
12002                        loc2p++)
12003                     {
12004                       struct bp_location *loc2 = *loc2p;
12005
12006                       if (breakpoint_locations_match (loc2, old_loc))
12007                         {
12008                           /* Read watchpoint locations are switched to
12009                              access watchpoints, if the former are not
12010                              supported, but the latter are.  */
12011                           if (is_hardware_watchpoint (old_loc->owner))
12012                             {
12013                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12014                               loc2->watchpoint_type = old_loc->watchpoint_type;
12015                             }
12016
12017                           /* loc2 is a duplicated location. We need to check
12018                              if it should be inserted in case it will be
12019                              unduplicated.  */
12020                           if (loc2 != old_loc
12021                               && unduplicated_should_be_inserted (loc2))
12022                             {
12023                               swap_insertion (old_loc, loc2);
12024                               keep_in_target = 1;
12025                               break;
12026                             }
12027                         }
12028                     }
12029                 }
12030             }
12031
12032           if (!keep_in_target)
12033             {
12034               if (remove_breakpoint (old_loc))
12035                 {
12036                   /* This is just about all we can do.  We could keep
12037                      this location on the global list, and try to
12038                      remove it next time, but there's no particular
12039                      reason why we will succeed next time.
12040                      
12041                      Note that at this point, old_loc->owner is still
12042                      valid, as delete_breakpoint frees the breakpoint
12043                      only after calling us.  */
12044                   printf_filtered (_("warning: Error removing "
12045                                      "breakpoint %d\n"), 
12046                                    old_loc->owner->number);
12047                 }
12048               removed = 1;
12049             }
12050         }
12051
12052       if (!found_object)
12053         {
12054           if (removed && target_is_non_stop_p ()
12055               && need_moribund_for_location_type (old_loc))
12056             {
12057               /* This location was removed from the target.  In
12058                  non-stop mode, a race condition is possible where
12059                  we've removed a breakpoint, but stop events for that
12060                  breakpoint are already queued and will arrive later.
12061                  We apply an heuristic to be able to distinguish such
12062                  SIGTRAPs from other random SIGTRAPs: we keep this
12063                  breakpoint location for a bit, and will retire it
12064                  after we see some number of events.  The theory here
12065                  is that reporting of events should, "on the average",
12066                  be fair, so after a while we'll see events from all
12067                  threads that have anything of interest, and no longer
12068                  need to keep this breakpoint location around.  We
12069                  don't hold locations forever so to reduce chances of
12070                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12071                  SIGTRAP.
12072
12073                  The heuristic failing can be disastrous on
12074                  decr_pc_after_break targets.
12075
12076                  On decr_pc_after_break targets, like e.g., x86-linux,
12077                  if we fail to recognize a late breakpoint SIGTRAP,
12078                  because events_till_retirement has reached 0 too
12079                  soon, we'll fail to do the PC adjustment, and report
12080                  a random SIGTRAP to the user.  When the user resumes
12081                  the inferior, it will most likely immediately crash
12082                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12083                  corrupted, because of being resumed e.g., in the
12084                  middle of a multi-byte instruction, or skipped a
12085                  one-byte instruction.  This was actually seen happen
12086                  on native x86-linux, and should be less rare on
12087                  targets that do not support new thread events, like
12088                  remote, due to the heuristic depending on
12089                  thread_count.
12090
12091                  Mistaking a random SIGTRAP for a breakpoint trap
12092                  causes similar symptoms (PC adjustment applied when
12093                  it shouldn't), but then again, playing with SIGTRAPs
12094                  behind the debugger's back is asking for trouble.
12095
12096                  Since hardware watchpoint traps are always
12097                  distinguishable from other traps, so we don't need to
12098                  apply keep hardware watchpoint moribund locations
12099                  around.  We simply always ignore hardware watchpoint
12100                  traps we can no longer explain.  */
12101
12102               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12103               old_loc->owner = NULL;
12104
12105               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12106             }
12107           else
12108             {
12109               old_loc->owner = NULL;
12110               decref_bp_location (&old_loc);
12111             }
12112         }
12113     }
12114
12115   /* Rescan breakpoints at the same address and section, marking the
12116      first one as "first" and any others as "duplicates".  This is so
12117      that the bpt instruction is only inserted once.  If we have a
12118      permanent breakpoint at the same place as BPT, make that one the
12119      official one, and the rest as duplicates.  Permanent breakpoints
12120      are sorted first for the same address.
12121
12122      Do the same for hardware watchpoints, but also considering the
12123      watchpoint's type (regular/access/read) and length.  */
12124
12125   bp_loc_first = NULL;
12126   wp_loc_first = NULL;
12127   awp_loc_first = NULL;
12128   rwp_loc_first = NULL;
12129   ALL_BP_LOCATIONS (loc, locp)
12130     {
12131       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12132          non-NULL.  */
12133       struct bp_location **loc_first_p;
12134       b = loc->owner;
12135
12136       if (!unduplicated_should_be_inserted (loc)
12137           || !breakpoint_address_is_meaningful (b)
12138           /* Don't detect duplicate for tracepoint locations because they are
12139            never duplicated.  See the comments in field `duplicate' of
12140            `struct bp_location'.  */
12141           || is_tracepoint (b))
12142         {
12143           /* Clear the condition modification flag.  */
12144           loc->condition_changed = condition_unchanged;
12145           continue;
12146         }
12147
12148       if (b->type == bp_hardware_watchpoint)
12149         loc_first_p = &wp_loc_first;
12150       else if (b->type == bp_read_watchpoint)
12151         loc_first_p = &rwp_loc_first;
12152       else if (b->type == bp_access_watchpoint)
12153         loc_first_p = &awp_loc_first;
12154       else
12155         loc_first_p = &bp_loc_first;
12156
12157       if (*loc_first_p == NULL
12158           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12159           || !breakpoint_locations_match (loc, *loc_first_p))
12160         {
12161           *loc_first_p = loc;
12162           loc->duplicate = 0;
12163
12164           if (is_breakpoint (loc->owner) && loc->condition_changed)
12165             {
12166               loc->needs_update = 1;
12167               /* Clear the condition modification flag.  */
12168               loc->condition_changed = condition_unchanged;
12169             }
12170           continue;
12171         }
12172
12173
12174       /* This and the above ensure the invariant that the first location
12175          is not duplicated, and is the inserted one.
12176          All following are marked as duplicated, and are not inserted.  */
12177       if (loc->inserted)
12178         swap_insertion (loc, *loc_first_p);
12179       loc->duplicate = 1;
12180
12181       /* Clear the condition modification flag.  */
12182       loc->condition_changed = condition_unchanged;
12183     }
12184
12185   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12186     {
12187       if (insert_mode != UGLL_DONT_INSERT)
12188         insert_breakpoint_locations ();
12189       else
12190         {
12191           /* Even though the caller told us to not insert new
12192              locations, we may still need to update conditions on the
12193              target's side of breakpoints that were already inserted
12194              if the target is evaluating breakpoint conditions.  We
12195              only update conditions for locations that are marked
12196              "needs_update".  */
12197           update_inserted_breakpoint_locations ();
12198         }
12199     }
12200
12201   if (insert_mode != UGLL_DONT_INSERT)
12202     download_tracepoint_locations ();
12203 }
12204
12205 void
12206 breakpoint_retire_moribund (void)
12207 {
12208   struct bp_location *loc;
12209   int ix;
12210
12211   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12212     if (--(loc->events_till_retirement) == 0)
12213       {
12214         decref_bp_location (&loc);
12215         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12216         --ix;
12217       }
12218 }
12219
12220 static void
12221 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12222 {
12223
12224   TRY
12225     {
12226       update_global_location_list (insert_mode);
12227     }
12228   CATCH (e, RETURN_MASK_ERROR)
12229     {
12230     }
12231   END_CATCH
12232 }
12233
12234 /* Clear BKP from a BPS.  */
12235
12236 static void
12237 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12238 {
12239   bpstat bs;
12240
12241   for (bs = bps; bs; bs = bs->next)
12242     if (bs->breakpoint_at == bpt)
12243       {
12244         bs->breakpoint_at = NULL;
12245         bs->old_val = NULL;
12246         /* bs->commands will be freed later.  */
12247       }
12248 }
12249
12250 /* Callback for iterate_over_threads.  */
12251 static int
12252 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12253 {
12254   struct breakpoint *bpt = (struct breakpoint *) data;
12255
12256   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12257   return 0;
12258 }
12259
12260 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12261    callbacks.  */
12262
12263 static void
12264 say_where (struct breakpoint *b)
12265 {
12266   struct value_print_options opts;
12267
12268   get_user_print_options (&opts);
12269
12270   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12271      single string.  */
12272   if (b->loc == NULL)
12273     {
12274       /* For pending locations, the output differs slightly based
12275          on b->extra_string.  If this is non-NULL, it contains either
12276          a condition or dprintf arguments.  */
12277       if (b->extra_string == NULL)
12278         {
12279           printf_filtered (_(" (%s) pending."),
12280                            event_location_to_string (b->location.get ()));
12281         }
12282       else if (b->type == bp_dprintf)
12283         {
12284           printf_filtered (_(" (%s,%s) pending."),
12285                            event_location_to_string (b->location.get ()),
12286                            b->extra_string);
12287         }
12288       else
12289         {
12290           printf_filtered (_(" (%s %s) pending."),
12291                            event_location_to_string (b->location.get ()),
12292                            b->extra_string);
12293         }
12294     }
12295   else
12296     {
12297       if (opts.addressprint || b->loc->symtab == NULL)
12298         {
12299           printf_filtered (" at ");
12300           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12301                           gdb_stdout);
12302         }
12303       if (b->loc->symtab != NULL)
12304         {
12305           /* If there is a single location, we can print the location
12306              more nicely.  */
12307           if (b->loc->next == NULL)
12308             printf_filtered (": file %s, line %d.",
12309                              symtab_to_filename_for_display (b->loc->symtab),
12310                              b->loc->line_number);
12311           else
12312             /* This is not ideal, but each location may have a
12313                different file name, and this at least reflects the
12314                real situation somewhat.  */
12315             printf_filtered (": %s.",
12316                              event_location_to_string (b->location.get ()));
12317         }
12318
12319       if (b->loc->next)
12320         {
12321           struct bp_location *loc = b->loc;
12322           int n = 0;
12323           for (; loc; loc = loc->next)
12324             ++n;
12325           printf_filtered (" (%d locations)", n);
12326         }
12327     }
12328 }
12329
12330 /* Default bp_location_ops methods.  */
12331
12332 static void
12333 bp_location_dtor (struct bp_location *self)
12334 {
12335   xfree (self->function_name);
12336 }
12337
12338 static const struct bp_location_ops bp_location_ops =
12339 {
12340   bp_location_dtor
12341 };
12342
12343 /* Destructor for the breakpoint base class.  */
12344
12345 breakpoint::~breakpoint ()
12346 {
12347   xfree (this->cond_string);
12348   xfree (this->extra_string);
12349   xfree (this->filter);
12350 }
12351
12352 static struct bp_location *
12353 base_breakpoint_allocate_location (struct breakpoint *self)
12354 {
12355   return new bp_location (&bp_location_ops, self);
12356 }
12357
12358 static void
12359 base_breakpoint_re_set (struct breakpoint *b)
12360 {
12361   /* Nothing to re-set. */
12362 }
12363
12364 #define internal_error_pure_virtual_called() \
12365   gdb_assert_not_reached ("pure virtual function called")
12366
12367 static int
12368 base_breakpoint_insert_location (struct bp_location *bl)
12369 {
12370   internal_error_pure_virtual_called ();
12371 }
12372
12373 static int
12374 base_breakpoint_remove_location (struct bp_location *bl,
12375                                  enum remove_bp_reason reason)
12376 {
12377   internal_error_pure_virtual_called ();
12378 }
12379
12380 static int
12381 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12382                                 const address_space *aspace,
12383                                 CORE_ADDR bp_addr,
12384                                 const struct target_waitstatus *ws)
12385 {
12386   internal_error_pure_virtual_called ();
12387 }
12388
12389 static void
12390 base_breakpoint_check_status (bpstat bs)
12391 {
12392   /* Always stop.   */
12393 }
12394
12395 /* A "works_in_software_mode" breakpoint_ops method that just internal
12396    errors.  */
12397
12398 static int
12399 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12400 {
12401   internal_error_pure_virtual_called ();
12402 }
12403
12404 /* A "resources_needed" breakpoint_ops method that just internal
12405    errors.  */
12406
12407 static int
12408 base_breakpoint_resources_needed (const struct bp_location *bl)
12409 {
12410   internal_error_pure_virtual_called ();
12411 }
12412
12413 static enum print_stop_action
12414 base_breakpoint_print_it (bpstat bs)
12415 {
12416   internal_error_pure_virtual_called ();
12417 }
12418
12419 static void
12420 base_breakpoint_print_one_detail (const struct breakpoint *self,
12421                                   struct ui_out *uiout)
12422 {
12423   /* nothing */
12424 }
12425
12426 static void
12427 base_breakpoint_print_mention (struct breakpoint *b)
12428 {
12429   internal_error_pure_virtual_called ();
12430 }
12431
12432 static void
12433 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12434 {
12435   internal_error_pure_virtual_called ();
12436 }
12437
12438 static void
12439 base_breakpoint_create_sals_from_location
12440   (const struct event_location *location,
12441    struct linespec_result *canonical,
12442    enum bptype type_wanted)
12443 {
12444   internal_error_pure_virtual_called ();
12445 }
12446
12447 static void
12448 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12449                                         struct linespec_result *c,
12450                                         gdb::unique_xmalloc_ptr<char> cond_string,
12451                                         gdb::unique_xmalloc_ptr<char> extra_string,
12452                                         enum bptype type_wanted,
12453                                         enum bpdisp disposition,
12454                                         int thread,
12455                                         int task, int ignore_count,
12456                                         const struct breakpoint_ops *o,
12457                                         int from_tty, int enabled,
12458                                         int internal, unsigned flags)
12459 {
12460   internal_error_pure_virtual_called ();
12461 }
12462
12463 static std::vector<symtab_and_line>
12464 base_breakpoint_decode_location (struct breakpoint *b,
12465                                  const struct event_location *location,
12466                                  struct program_space *search_pspace)
12467 {
12468   internal_error_pure_virtual_called ();
12469 }
12470
12471 /* The default 'explains_signal' method.  */
12472
12473 static int
12474 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12475 {
12476   return 1;
12477 }
12478
12479 /* The default "after_condition_true" method.  */
12480
12481 static void
12482 base_breakpoint_after_condition_true (struct bpstats *bs)
12483 {
12484   /* Nothing to do.   */
12485 }
12486
12487 struct breakpoint_ops base_breakpoint_ops =
12488 {
12489   base_breakpoint_allocate_location,
12490   base_breakpoint_re_set,
12491   base_breakpoint_insert_location,
12492   base_breakpoint_remove_location,
12493   base_breakpoint_breakpoint_hit,
12494   base_breakpoint_check_status,
12495   base_breakpoint_resources_needed,
12496   base_breakpoint_works_in_software_mode,
12497   base_breakpoint_print_it,
12498   NULL,
12499   base_breakpoint_print_one_detail,
12500   base_breakpoint_print_mention,
12501   base_breakpoint_print_recreate,
12502   base_breakpoint_create_sals_from_location,
12503   base_breakpoint_create_breakpoints_sal,
12504   base_breakpoint_decode_location,
12505   base_breakpoint_explains_signal,
12506   base_breakpoint_after_condition_true,
12507 };
12508
12509 /* Default breakpoint_ops methods.  */
12510
12511 static void
12512 bkpt_re_set (struct breakpoint *b)
12513 {
12514   /* FIXME: is this still reachable?  */
12515   if (breakpoint_event_location_empty_p (b))
12516     {
12517       /* Anything without a location can't be re-set.  */
12518       delete_breakpoint (b);
12519       return;
12520     }
12521
12522   breakpoint_re_set_default (b);
12523 }
12524
12525 static int
12526 bkpt_insert_location (struct bp_location *bl)
12527 {
12528   CORE_ADDR addr = bl->target_info.reqstd_address;
12529
12530   bl->target_info.kind = breakpoint_kind (bl, &addr);
12531   bl->target_info.placed_address = addr;
12532
12533   if (bl->loc_type == bp_loc_hardware_breakpoint)
12534     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12535   else
12536     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12537 }
12538
12539 static int
12540 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
12541 {
12542   if (bl->loc_type == bp_loc_hardware_breakpoint)
12543     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12544   else
12545     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12546 }
12547
12548 static int
12549 bkpt_breakpoint_hit (const struct bp_location *bl,
12550                      const address_space *aspace, CORE_ADDR bp_addr,
12551                      const struct target_waitstatus *ws)
12552 {
12553   if (ws->kind != TARGET_WAITKIND_STOPPED
12554       || ws->value.sig != GDB_SIGNAL_TRAP)
12555     return 0;
12556
12557   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12558                                  aspace, bp_addr))
12559     return 0;
12560
12561   if (overlay_debugging         /* unmapped overlay section */
12562       && section_is_overlay (bl->section)
12563       && !section_is_mapped (bl->section))
12564     return 0;
12565
12566   return 1;
12567 }
12568
12569 static int
12570 dprintf_breakpoint_hit (const struct bp_location *bl,
12571                         const address_space *aspace, CORE_ADDR bp_addr,
12572                         const struct target_waitstatus *ws)
12573 {
12574   if (dprintf_style == dprintf_style_agent
12575       && target_can_run_breakpoint_commands ())
12576     {
12577       /* An agent-style dprintf never causes a stop.  If we see a trap
12578          for this address it must be for a breakpoint that happens to
12579          be set at the same address.  */
12580       return 0;
12581     }
12582
12583   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12584 }
12585
12586 static int
12587 bkpt_resources_needed (const struct bp_location *bl)
12588 {
12589   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12590
12591   return 1;
12592 }
12593
12594 static enum print_stop_action
12595 bkpt_print_it (bpstat bs)
12596 {
12597   struct breakpoint *b;
12598   const struct bp_location *bl;
12599   int bp_temp;
12600   struct ui_out *uiout = current_uiout;
12601
12602   gdb_assert (bs->bp_location_at != NULL);
12603
12604   bl = bs->bp_location_at;
12605   b = bs->breakpoint_at;
12606
12607   bp_temp = b->disposition == disp_del;
12608   if (bl->address != bl->requested_address)
12609     breakpoint_adjustment_warning (bl->requested_address,
12610                                    bl->address,
12611                                    b->number, 1);
12612   annotate_breakpoint (b->number);
12613   maybe_print_thread_hit_breakpoint (uiout);
12614
12615   if (bp_temp)
12616     uiout->text ("Temporary breakpoint ");
12617   else
12618     uiout->text ("Breakpoint ");
12619   if (uiout->is_mi_like_p ())
12620     {
12621       uiout->field_string ("reason",
12622                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12623       uiout->field_string ("disp", bpdisp_text (b->disposition));
12624     }
12625   uiout->field_int ("bkptno", b->number);
12626   uiout->text (", ");
12627
12628   return PRINT_SRC_AND_LOC;
12629 }
12630
12631 static void
12632 bkpt_print_mention (struct breakpoint *b)
12633 {
12634   if (current_uiout->is_mi_like_p ())
12635     return;
12636
12637   switch (b->type)
12638     {
12639     case bp_breakpoint:
12640     case bp_gnu_ifunc_resolver:
12641       if (b->disposition == disp_del)
12642         printf_filtered (_("Temporary breakpoint"));
12643       else
12644         printf_filtered (_("Breakpoint"));
12645       printf_filtered (_(" %d"), b->number);
12646       if (b->type == bp_gnu_ifunc_resolver)
12647         printf_filtered (_(" at gnu-indirect-function resolver"));
12648       break;
12649     case bp_hardware_breakpoint:
12650       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12651       break;
12652     case bp_dprintf:
12653       printf_filtered (_("Dprintf %d"), b->number);
12654       break;
12655     }
12656
12657   say_where (b);
12658 }
12659
12660 static void
12661 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12662 {
12663   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12664     fprintf_unfiltered (fp, "tbreak");
12665   else if (tp->type == bp_breakpoint)
12666     fprintf_unfiltered (fp, "break");
12667   else if (tp->type == bp_hardware_breakpoint
12668            && tp->disposition == disp_del)
12669     fprintf_unfiltered (fp, "thbreak");
12670   else if (tp->type == bp_hardware_breakpoint)
12671     fprintf_unfiltered (fp, "hbreak");
12672   else
12673     internal_error (__FILE__, __LINE__,
12674                     _("unhandled breakpoint type %d"), (int) tp->type);
12675
12676   fprintf_unfiltered (fp, " %s",
12677                       event_location_to_string (tp->location.get ()));
12678
12679   /* Print out extra_string if this breakpoint is pending.  It might
12680      contain, for example, conditions that were set by the user.  */
12681   if (tp->loc == NULL && tp->extra_string != NULL)
12682     fprintf_unfiltered (fp, " %s", tp->extra_string);
12683
12684   print_recreate_thread (tp, fp);
12685 }
12686
12687 static void
12688 bkpt_create_sals_from_location (const struct event_location *location,
12689                                 struct linespec_result *canonical,
12690                                 enum bptype type_wanted)
12691 {
12692   create_sals_from_location_default (location, canonical, type_wanted);
12693 }
12694
12695 static void
12696 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12697                              struct linespec_result *canonical,
12698                              gdb::unique_xmalloc_ptr<char> cond_string,
12699                              gdb::unique_xmalloc_ptr<char> extra_string,
12700                              enum bptype type_wanted,
12701                              enum bpdisp disposition,
12702                              int thread,
12703                              int task, int ignore_count,
12704                              const struct breakpoint_ops *ops,
12705                              int from_tty, int enabled,
12706                              int internal, unsigned flags)
12707 {
12708   create_breakpoints_sal_default (gdbarch, canonical,
12709                                   std::move (cond_string),
12710                                   std::move (extra_string),
12711                                   type_wanted,
12712                                   disposition, thread, task,
12713                                   ignore_count, ops, from_tty,
12714                                   enabled, internal, flags);
12715 }
12716
12717 static std::vector<symtab_and_line>
12718 bkpt_decode_location (struct breakpoint *b,
12719                       const struct event_location *location,
12720                       struct program_space *search_pspace)
12721 {
12722   return decode_location_default (b, location, search_pspace);
12723 }
12724
12725 /* Virtual table for internal breakpoints.  */
12726
12727 static void
12728 internal_bkpt_re_set (struct breakpoint *b)
12729 {
12730   switch (b->type)
12731     {
12732       /* Delete overlay event and longjmp master breakpoints; they
12733          will be reset later by breakpoint_re_set.  */
12734     case bp_overlay_event:
12735     case bp_longjmp_master:
12736     case bp_std_terminate_master:
12737     case bp_exception_master:
12738       delete_breakpoint (b);
12739       break;
12740
12741       /* This breakpoint is special, it's set up when the inferior
12742          starts and we really don't want to touch it.  */
12743     case bp_shlib_event:
12744
12745       /* Like bp_shlib_event, this breakpoint type is special.  Once
12746          it is set up, we do not want to touch it.  */
12747     case bp_thread_event:
12748       break;
12749     }
12750 }
12751
12752 static void
12753 internal_bkpt_check_status (bpstat bs)
12754 {
12755   if (bs->breakpoint_at->type == bp_shlib_event)
12756     {
12757       /* If requested, stop when the dynamic linker notifies GDB of
12758          events.  This allows the user to get control and place
12759          breakpoints in initializer routines for dynamically loaded
12760          objects (among other things).  */
12761       bs->stop = stop_on_solib_events;
12762       bs->print = stop_on_solib_events;
12763     }
12764   else
12765     bs->stop = 0;
12766 }
12767
12768 static enum print_stop_action
12769 internal_bkpt_print_it (bpstat bs)
12770 {
12771   struct breakpoint *b;
12772
12773   b = bs->breakpoint_at;
12774
12775   switch (b->type)
12776     {
12777     case bp_shlib_event:
12778       /* Did we stop because the user set the stop_on_solib_events
12779          variable?  (If so, we report this as a generic, "Stopped due
12780          to shlib event" message.) */
12781       print_solib_event (0);
12782       break;
12783
12784     case bp_thread_event:
12785       /* Not sure how we will get here.
12786          GDB should not stop for these breakpoints.  */
12787       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12788       break;
12789
12790     case bp_overlay_event:
12791       /* By analogy with the thread event, GDB should not stop for these.  */
12792       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12793       break;
12794
12795     case bp_longjmp_master:
12796       /* These should never be enabled.  */
12797       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12798       break;
12799
12800     case bp_std_terminate_master:
12801       /* These should never be enabled.  */
12802       printf_filtered (_("std::terminate Master Breakpoint: "
12803                          "gdb should not stop!\n"));
12804       break;
12805
12806     case bp_exception_master:
12807       /* These should never be enabled.  */
12808       printf_filtered (_("Exception Master Breakpoint: "
12809                          "gdb should not stop!\n"));
12810       break;
12811     }
12812
12813   return PRINT_NOTHING;
12814 }
12815
12816 static void
12817 internal_bkpt_print_mention (struct breakpoint *b)
12818 {
12819   /* Nothing to mention.  These breakpoints are internal.  */
12820 }
12821
12822 /* Virtual table for momentary breakpoints  */
12823
12824 static void
12825 momentary_bkpt_re_set (struct breakpoint *b)
12826 {
12827   /* Keep temporary breakpoints, which can be encountered when we step
12828      over a dlopen call and solib_add is resetting the breakpoints.
12829      Otherwise these should have been blown away via the cleanup chain
12830      or by breakpoint_init_inferior when we rerun the executable.  */
12831 }
12832
12833 static void
12834 momentary_bkpt_check_status (bpstat bs)
12835 {
12836   /* Nothing.  The point of these breakpoints is causing a stop.  */
12837 }
12838
12839 static enum print_stop_action
12840 momentary_bkpt_print_it (bpstat bs)
12841 {
12842   return PRINT_UNKNOWN;
12843 }
12844
12845 static void
12846 momentary_bkpt_print_mention (struct breakpoint *b)
12847 {
12848   /* Nothing to mention.  These breakpoints are internal.  */
12849 }
12850
12851 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12852
12853    It gets cleared already on the removal of the first one of such placed
12854    breakpoints.  This is OK as they get all removed altogether.  */
12855
12856 longjmp_breakpoint::~longjmp_breakpoint ()
12857 {
12858   thread_info *tp = find_thread_global_id (this->thread);
12859
12860   if (tp != NULL)
12861     tp->initiating_frame = null_frame_id;
12862 }
12863
12864 /* Specific methods for probe breakpoints.  */
12865
12866 static int
12867 bkpt_probe_insert_location (struct bp_location *bl)
12868 {
12869   int v = bkpt_insert_location (bl);
12870
12871   if (v == 0)
12872     {
12873       /* The insertion was successful, now let's set the probe's semaphore
12874          if needed.  */
12875       bl->probe.prob->set_semaphore (bl->probe.objfile, bl->gdbarch);
12876     }
12877
12878   return v;
12879 }
12880
12881 static int
12882 bkpt_probe_remove_location (struct bp_location *bl,
12883                             enum remove_bp_reason reason)
12884 {
12885   /* Let's clear the semaphore before removing the location.  */
12886   bl->probe.prob->clear_semaphore (bl->probe.objfile, bl->gdbarch);
12887
12888   return bkpt_remove_location (bl, reason);
12889 }
12890
12891 static void
12892 bkpt_probe_create_sals_from_location (const struct event_location *location,
12893                                       struct linespec_result *canonical,
12894                                       enum bptype type_wanted)
12895 {
12896   struct linespec_sals lsal;
12897
12898   lsal.sals = parse_probes (location, NULL, canonical);
12899   lsal.canonical
12900     = xstrdup (event_location_to_string (canonical->location.get ()));
12901   canonical->lsals.push_back (std::move (lsal));
12902 }
12903
12904 static std::vector<symtab_and_line>
12905 bkpt_probe_decode_location (struct breakpoint *b,
12906                             const struct event_location *location,
12907                             struct program_space *search_pspace)
12908 {
12909   std::vector<symtab_and_line> sals = parse_probes (location, search_pspace, NULL);
12910   if (sals.empty ())
12911     error (_("probe not found"));
12912   return sals;
12913 }
12914
12915 /* The breakpoint_ops structure to be used in tracepoints.  */
12916
12917 static void
12918 tracepoint_re_set (struct breakpoint *b)
12919 {
12920   breakpoint_re_set_default (b);
12921 }
12922
12923 static int
12924 tracepoint_breakpoint_hit (const struct bp_location *bl,
12925                            const address_space *aspace, CORE_ADDR bp_addr,
12926                            const struct target_waitstatus *ws)
12927 {
12928   /* By definition, the inferior does not report stops at
12929      tracepoints.  */
12930   return 0;
12931 }
12932
12933 static void
12934 tracepoint_print_one_detail (const struct breakpoint *self,
12935                              struct ui_out *uiout)
12936 {
12937   struct tracepoint *tp = (struct tracepoint *) self;
12938   if (tp->static_trace_marker_id)
12939     {
12940       gdb_assert (self->type == bp_static_tracepoint);
12941
12942       uiout->text ("\tmarker id is ");
12943       uiout->field_string ("static-tracepoint-marker-string-id",
12944                            tp->static_trace_marker_id);
12945       uiout->text ("\n");
12946     }
12947 }
12948
12949 static void
12950 tracepoint_print_mention (struct breakpoint *b)
12951 {
12952   if (current_uiout->is_mi_like_p ())
12953     return;
12954
12955   switch (b->type)
12956     {
12957     case bp_tracepoint:
12958       printf_filtered (_("Tracepoint"));
12959       printf_filtered (_(" %d"), b->number);
12960       break;
12961     case bp_fast_tracepoint:
12962       printf_filtered (_("Fast tracepoint"));
12963       printf_filtered (_(" %d"), b->number);
12964       break;
12965     case bp_static_tracepoint:
12966       printf_filtered (_("Static tracepoint"));
12967       printf_filtered (_(" %d"), b->number);
12968       break;
12969     default:
12970       internal_error (__FILE__, __LINE__,
12971                       _("unhandled tracepoint type %d"), (int) b->type);
12972     }
12973
12974   say_where (b);
12975 }
12976
12977 static void
12978 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
12979 {
12980   struct tracepoint *tp = (struct tracepoint *) self;
12981
12982   if (self->type == bp_fast_tracepoint)
12983     fprintf_unfiltered (fp, "ftrace");
12984   else if (self->type == bp_static_tracepoint)
12985     fprintf_unfiltered (fp, "strace");
12986   else if (self->type == bp_tracepoint)
12987     fprintf_unfiltered (fp, "trace");
12988   else
12989     internal_error (__FILE__, __LINE__,
12990                     _("unhandled tracepoint type %d"), (int) self->type);
12991
12992   fprintf_unfiltered (fp, " %s",
12993                       event_location_to_string (self->location.get ()));
12994   print_recreate_thread (self, fp);
12995
12996   if (tp->pass_count)
12997     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
12998 }
12999
13000 static void
13001 tracepoint_create_sals_from_location (const struct event_location *location,
13002                                       struct linespec_result *canonical,
13003                                       enum bptype type_wanted)
13004 {
13005   create_sals_from_location_default (location, canonical, type_wanted);
13006 }
13007
13008 static void
13009 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13010                                    struct linespec_result *canonical,
13011                                    gdb::unique_xmalloc_ptr<char> cond_string,
13012                                    gdb::unique_xmalloc_ptr<char> extra_string,
13013                                    enum bptype type_wanted,
13014                                    enum bpdisp disposition,
13015                                    int thread,
13016                                    int task, int ignore_count,
13017                                    const struct breakpoint_ops *ops,
13018                                    int from_tty, int enabled,
13019                                    int internal, unsigned flags)
13020 {
13021   create_breakpoints_sal_default (gdbarch, canonical,
13022                                   std::move (cond_string),
13023                                   std::move (extra_string),
13024                                   type_wanted,
13025                                   disposition, thread, task,
13026                                   ignore_count, ops, from_tty,
13027                                   enabled, internal, flags);
13028 }
13029
13030 static std::vector<symtab_and_line>
13031 tracepoint_decode_location (struct breakpoint *b,
13032                             const struct event_location *location,
13033                             struct program_space *search_pspace)
13034 {
13035   return decode_location_default (b, location, search_pspace);
13036 }
13037
13038 struct breakpoint_ops tracepoint_breakpoint_ops;
13039
13040 /* The breakpoint_ops structure to be use on tracepoints placed in a
13041    static probe.  */
13042
13043 static void
13044 tracepoint_probe_create_sals_from_location
13045   (const struct event_location *location,
13046    struct linespec_result *canonical,
13047    enum bptype type_wanted)
13048 {
13049   /* We use the same method for breakpoint on probes.  */
13050   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
13051 }
13052
13053 static std::vector<symtab_and_line>
13054 tracepoint_probe_decode_location (struct breakpoint *b,
13055                                   const struct event_location *location,
13056                                   struct program_space *search_pspace)
13057 {
13058   /* We use the same method for breakpoint on probes.  */
13059   return bkpt_probe_decode_location (b, location, search_pspace);
13060 }
13061
13062 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13063
13064 /* Dprintf breakpoint_ops methods.  */
13065
13066 static void
13067 dprintf_re_set (struct breakpoint *b)
13068 {
13069   breakpoint_re_set_default (b);
13070
13071   /* extra_string should never be non-NULL for dprintf.  */
13072   gdb_assert (b->extra_string != NULL);
13073
13074   /* 1 - connect to target 1, that can run breakpoint commands.
13075      2 - create a dprintf, which resolves fine.
13076      3 - disconnect from target 1
13077      4 - connect to target 2, that can NOT run breakpoint commands.
13078
13079      After steps #3/#4, you'll want the dprintf command list to
13080      be updated, because target 1 and 2 may well return different
13081      answers for target_can_run_breakpoint_commands().
13082      Given absence of finer grained resetting, we get to do
13083      it all the time.  */
13084   if (b->extra_string != NULL)
13085     update_dprintf_command_list (b);
13086 }
13087
13088 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13089
13090 static void
13091 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13092 {
13093   fprintf_unfiltered (fp, "dprintf %s,%s",
13094                       event_location_to_string (tp->location.get ()),
13095                       tp->extra_string);
13096   print_recreate_thread (tp, fp);
13097 }
13098
13099 /* Implement the "after_condition_true" breakpoint_ops method for
13100    dprintf.
13101
13102    dprintf's are implemented with regular commands in their command
13103    list, but we run the commands here instead of before presenting the
13104    stop to the user, as dprintf's don't actually cause a stop.  This
13105    also makes it so that the commands of multiple dprintfs at the same
13106    address are all handled.  */
13107
13108 static void
13109 dprintf_after_condition_true (struct bpstats *bs)
13110 {
13111   struct bpstats tmp_bs;
13112   struct bpstats *tmp_bs_p = &tmp_bs;
13113
13114   /* dprintf's never cause a stop.  This wasn't set in the
13115      check_status hook instead because that would make the dprintf's
13116      condition not be evaluated.  */
13117   bs->stop = 0;
13118
13119   /* Run the command list here.  Take ownership of it instead of
13120      copying.  We never want these commands to run later in
13121      bpstat_do_actions, if a breakpoint that causes a stop happens to
13122      be set at same address as this dprintf, or even if running the
13123      commands here throws.  */
13124   tmp_bs.commands = bs->commands;
13125   bs->commands = NULL;
13126
13127   bpstat_do_actions_1 (&tmp_bs_p);
13128
13129   /* 'tmp_bs.commands' will usually be NULL by now, but
13130      bpstat_do_actions_1 may return early without processing the whole
13131      list.  */
13132 }
13133
13134 /* The breakpoint_ops structure to be used on static tracepoints with
13135    markers (`-m').  */
13136
13137 static void
13138 strace_marker_create_sals_from_location (const struct event_location *location,
13139                                          struct linespec_result *canonical,
13140                                          enum bptype type_wanted)
13141 {
13142   struct linespec_sals lsal;
13143   const char *arg_start, *arg;
13144
13145   arg = arg_start = get_linespec_location (location)->spec_string;
13146   lsal.sals = decode_static_tracepoint_spec (&arg);
13147
13148   std::string str (arg_start, arg - arg_start);
13149   const char *ptr = str.c_str ();
13150   canonical->location
13151     = new_linespec_location (&ptr, symbol_name_match_type::FULL);
13152
13153   lsal.canonical
13154     = xstrdup (event_location_to_string (canonical->location.get ()));
13155   canonical->lsals.push_back (std::move (lsal));
13156 }
13157
13158 static void
13159 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13160                                       struct linespec_result *canonical,
13161                                       gdb::unique_xmalloc_ptr<char> cond_string,
13162                                       gdb::unique_xmalloc_ptr<char> extra_string,
13163                                       enum bptype type_wanted,
13164                                       enum bpdisp disposition,
13165                                       int thread,
13166                                       int task, int ignore_count,
13167                                       const struct breakpoint_ops *ops,
13168                                       int from_tty, int enabled,
13169                                       int internal, unsigned flags)
13170 {
13171   const linespec_sals &lsal = canonical->lsals[0];
13172
13173   /* If the user is creating a static tracepoint by marker id
13174      (strace -m MARKER_ID), then store the sals index, so that
13175      breakpoint_re_set can try to match up which of the newly
13176      found markers corresponds to this one, and, don't try to
13177      expand multiple locations for each sal, given than SALS
13178      already should contain all sals for MARKER_ID.  */
13179
13180   for (size_t i = 0; i < lsal.sals.size (); i++)
13181     {
13182       event_location_up location
13183         = copy_event_location (canonical->location.get ());
13184
13185       std::unique_ptr<tracepoint> tp (new tracepoint ());
13186       init_breakpoint_sal (tp.get (), gdbarch, lsal.sals[i],
13187                            std::move (location), NULL,
13188                            std::move (cond_string),
13189                            std::move (extra_string),
13190                            type_wanted, disposition,
13191                            thread, task, ignore_count, ops,
13192                            from_tty, enabled, internal, flags,
13193                            canonical->special_display);
13194       /* Given that its possible to have multiple markers with
13195          the same string id, if the user is creating a static
13196          tracepoint by marker id ("strace -m MARKER_ID"), then
13197          store the sals index, so that breakpoint_re_set can
13198          try to match up which of the newly found markers
13199          corresponds to this one  */
13200       tp->static_trace_marker_id_idx = i;
13201
13202       install_breakpoint (internal, std::move (tp), 0);
13203     }
13204 }
13205
13206 static std::vector<symtab_and_line>
13207 strace_marker_decode_location (struct breakpoint *b,
13208                                const struct event_location *location,
13209                                struct program_space *search_pspace)
13210 {
13211   struct tracepoint *tp = (struct tracepoint *) b;
13212   const char *s = get_linespec_location (location)->spec_string;
13213
13214   std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
13215   if (sals.size () > tp->static_trace_marker_id_idx)
13216     {
13217       sals[0] = sals[tp->static_trace_marker_id_idx];
13218       sals.resize (1);
13219       return sals;
13220     }
13221   else
13222     error (_("marker %s not found"), tp->static_trace_marker_id);
13223 }
13224
13225 static struct breakpoint_ops strace_marker_breakpoint_ops;
13226
13227 static int
13228 strace_marker_p (struct breakpoint *b)
13229 {
13230   return b->ops == &strace_marker_breakpoint_ops;
13231 }
13232
13233 /* Delete a breakpoint and clean up all traces of it in the data
13234    structures.  */
13235
13236 void
13237 delete_breakpoint (struct breakpoint *bpt)
13238 {
13239   struct breakpoint *b;
13240
13241   gdb_assert (bpt != NULL);
13242
13243   /* Has this bp already been deleted?  This can happen because
13244      multiple lists can hold pointers to bp's.  bpstat lists are
13245      especial culprits.
13246
13247      One example of this happening is a watchpoint's scope bp.  When
13248      the scope bp triggers, we notice that the watchpoint is out of
13249      scope, and delete it.  We also delete its scope bp.  But the
13250      scope bp is marked "auto-deleting", and is already on a bpstat.
13251      That bpstat is then checked for auto-deleting bp's, which are
13252      deleted.
13253
13254      A real solution to this problem might involve reference counts in
13255      bp's, and/or giving them pointers back to their referencing
13256      bpstat's, and teaching delete_breakpoint to only free a bp's
13257      storage when no more references were extent.  A cheaper bandaid
13258      was chosen.  */
13259   if (bpt->type == bp_none)
13260     return;
13261
13262   /* At least avoid this stale reference until the reference counting
13263      of breakpoints gets resolved.  */
13264   if (bpt->related_breakpoint != bpt)
13265     {
13266       struct breakpoint *related;
13267       struct watchpoint *w;
13268
13269       if (bpt->type == bp_watchpoint_scope)
13270         w = (struct watchpoint *) bpt->related_breakpoint;
13271       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13272         w = (struct watchpoint *) bpt;
13273       else
13274         w = NULL;
13275       if (w != NULL)
13276         watchpoint_del_at_next_stop (w);
13277
13278       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13279       for (related = bpt; related->related_breakpoint != bpt;
13280            related = related->related_breakpoint);
13281       related->related_breakpoint = bpt->related_breakpoint;
13282       bpt->related_breakpoint = bpt;
13283     }
13284
13285   /* watch_command_1 creates a watchpoint but only sets its number if
13286      update_watchpoint succeeds in creating its bp_locations.  If there's
13287      a problem in that process, we'll be asked to delete the half-created
13288      watchpoint.  In that case, don't announce the deletion.  */
13289   if (bpt->number)
13290     observer_notify_breakpoint_deleted (bpt);
13291
13292   if (breakpoint_chain == bpt)
13293     breakpoint_chain = bpt->next;
13294
13295   ALL_BREAKPOINTS (b)
13296     if (b->next == bpt)
13297     {
13298       b->next = bpt->next;
13299       break;
13300     }
13301
13302   /* Be sure no bpstat's are pointing at the breakpoint after it's
13303      been freed.  */
13304   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13305      in all threads for now.  Note that we cannot just remove bpstats
13306      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13307      commands are associated with the bpstat; if we remove it here,
13308      then the later call to bpstat_do_actions (&stop_bpstat); in
13309      event-top.c won't do anything, and temporary breakpoints with
13310      commands won't work.  */
13311
13312   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13313
13314   /* Now that breakpoint is removed from breakpoint list, update the
13315      global location list.  This will remove locations that used to
13316      belong to this breakpoint.  Do this before freeing the breakpoint
13317      itself, since remove_breakpoint looks at location's owner.  It
13318      might be better design to have location completely
13319      self-contained, but it's not the case now.  */
13320   update_global_location_list (UGLL_DONT_INSERT);
13321
13322   /* On the chance that someone will soon try again to delete this
13323      same bp, we mark it as deleted before freeing its storage.  */
13324   bpt->type = bp_none;
13325   delete bpt;
13326 }
13327
13328 /* Iterator function to call a user-provided callback function once
13329    for each of B and its related breakpoints.  */
13330
13331 static void
13332 iterate_over_related_breakpoints (struct breakpoint *b,
13333                                   gdb::function_view<void (breakpoint *)> function)
13334 {
13335   struct breakpoint *related;
13336
13337   related = b;
13338   do
13339     {
13340       struct breakpoint *next;
13341
13342       /* FUNCTION may delete RELATED.  */
13343       next = related->related_breakpoint;
13344
13345       if (next == related)
13346         {
13347           /* RELATED is the last ring entry.  */
13348           function (related);
13349
13350           /* FUNCTION may have deleted it, so we'd never reach back to
13351              B.  There's nothing left to do anyway, so just break
13352              out.  */
13353           break;
13354         }
13355       else
13356         function (related);
13357
13358       related = next;
13359     }
13360   while (related != b);
13361 }
13362
13363 static void
13364 delete_command (const char *arg, int from_tty)
13365 {
13366   struct breakpoint *b, *b_tmp;
13367
13368   dont_repeat ();
13369
13370   if (arg == 0)
13371     {
13372       int breaks_to_delete = 0;
13373
13374       /* Delete all breakpoints if no argument.  Do not delete
13375          internal breakpoints, these have to be deleted with an
13376          explicit breakpoint number argument.  */
13377       ALL_BREAKPOINTS (b)
13378         if (user_breakpoint_p (b))
13379           {
13380             breaks_to_delete = 1;
13381             break;
13382           }
13383
13384       /* Ask user only if there are some breakpoints to delete.  */
13385       if (!from_tty
13386           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13387         {
13388           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13389             if (user_breakpoint_p (b))
13390               delete_breakpoint (b);
13391         }
13392     }
13393   else
13394     map_breakpoint_numbers
13395       (arg, [&] (breakpoint *b)
13396        {
13397          iterate_over_related_breakpoints (b, delete_breakpoint);
13398        });
13399 }
13400
13401 /* Return true if all locations of B bound to PSPACE are pending.  If
13402    PSPACE is NULL, all locations of all program spaces are
13403    considered.  */
13404
13405 static int
13406 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13407 {
13408   struct bp_location *loc;
13409
13410   for (loc = b->loc; loc != NULL; loc = loc->next)
13411     if ((pspace == NULL
13412          || loc->pspace == pspace)
13413         && !loc->shlib_disabled
13414         && !loc->pspace->executing_startup)
13415       return 0;
13416   return 1;
13417 }
13418
13419 /* Subroutine of update_breakpoint_locations to simplify it.
13420    Return non-zero if multiple fns in list LOC have the same name.
13421    Null names are ignored.  */
13422
13423 static int
13424 ambiguous_names_p (struct bp_location *loc)
13425 {
13426   struct bp_location *l;
13427   htab_t htab = htab_create_alloc (13, htab_hash_string,
13428                                    (int (*) (const void *, 
13429                                              const void *)) streq,
13430                                    NULL, xcalloc, xfree);
13431
13432   for (l = loc; l != NULL; l = l->next)
13433     {
13434       const char **slot;
13435       const char *name = l->function_name;
13436
13437       /* Allow for some names to be NULL, ignore them.  */
13438       if (name == NULL)
13439         continue;
13440
13441       slot = (const char **) htab_find_slot (htab, (const void *) name,
13442                                              INSERT);
13443       /* NOTE: We can assume slot != NULL here because xcalloc never
13444          returns NULL.  */
13445       if (*slot != NULL)
13446         {
13447           htab_delete (htab);
13448           return 1;
13449         }
13450       *slot = name;
13451     }
13452
13453   htab_delete (htab);
13454   return 0;
13455 }
13456
13457 /* When symbols change, it probably means the sources changed as well,
13458    and it might mean the static tracepoint markers are no longer at
13459    the same address or line numbers they used to be at last we
13460    checked.  Losing your static tracepoints whenever you rebuild is
13461    undesirable.  This function tries to resync/rematch gdb static
13462    tracepoints with the markers on the target, for static tracepoints
13463    that have not been set by marker id.  Static tracepoint that have
13464    been set by marker id are reset by marker id in breakpoint_re_set.
13465    The heuristic is:
13466
13467    1) For a tracepoint set at a specific address, look for a marker at
13468    the old PC.  If one is found there, assume to be the same marker.
13469    If the name / string id of the marker found is different from the
13470    previous known name, assume that means the user renamed the marker
13471    in the sources, and output a warning.
13472
13473    2) For a tracepoint set at a given line number, look for a marker
13474    at the new address of the old line number.  If one is found there,
13475    assume to be the same marker.  If the name / string id of the
13476    marker found is different from the previous known name, assume that
13477    means the user renamed the marker in the sources, and output a
13478    warning.
13479
13480    3) If a marker is no longer found at the same address or line, it
13481    may mean the marker no longer exists.  But it may also just mean
13482    the code changed a bit.  Maybe the user added a few lines of code
13483    that made the marker move up or down (in line number terms).  Ask
13484    the target for info about the marker with the string id as we knew
13485    it.  If found, update line number and address in the matching
13486    static tracepoint.  This will get confused if there's more than one
13487    marker with the same ID (possible in UST, although unadvised
13488    precisely because it confuses tools).  */
13489
13490 static struct symtab_and_line
13491 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13492 {
13493   struct tracepoint *tp = (struct tracepoint *) b;
13494   struct static_tracepoint_marker marker;
13495   CORE_ADDR pc;
13496
13497   pc = sal.pc;
13498   if (sal.line)
13499     find_line_pc (sal.symtab, sal.line, &pc);
13500
13501   if (target_static_tracepoint_marker_at (pc, &marker))
13502     {
13503       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13504         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13505                  b->number,
13506                  tp->static_trace_marker_id, marker.str_id);
13507
13508       xfree (tp->static_trace_marker_id);
13509       tp->static_trace_marker_id = xstrdup (marker.str_id);
13510       release_static_tracepoint_marker (&marker);
13511
13512       return sal;
13513     }
13514
13515   /* Old marker wasn't found on target at lineno.  Try looking it up
13516      by string ID.  */
13517   if (!sal.explicit_pc
13518       && sal.line != 0
13519       && sal.symtab != NULL
13520       && tp->static_trace_marker_id != NULL)
13521     {
13522       VEC(static_tracepoint_marker_p) *markers;
13523
13524       markers
13525         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13526
13527       if (!VEC_empty(static_tracepoint_marker_p, markers))
13528         {
13529           struct symbol *sym;
13530           struct static_tracepoint_marker *tpmarker;
13531           struct ui_out *uiout = current_uiout;
13532           struct explicit_location explicit_loc;
13533
13534           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13535
13536           xfree (tp->static_trace_marker_id);
13537           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13538
13539           warning (_("marker for static tracepoint %d (%s) not "
13540                      "found at previous line number"),
13541                    b->number, tp->static_trace_marker_id);
13542
13543           symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
13544           sym = find_pc_sect_function (tpmarker->address, NULL);
13545           uiout->text ("Now in ");
13546           if (sym)
13547             {
13548               uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
13549               uiout->text (" at ");
13550             }
13551           uiout->field_string ("file",
13552                                symtab_to_filename_for_display (sal2.symtab));
13553           uiout->text (":");
13554
13555           if (uiout->is_mi_like_p ())
13556             {
13557               const char *fullname = symtab_to_fullname (sal2.symtab);
13558
13559               uiout->field_string ("fullname", fullname);
13560             }
13561
13562           uiout->field_int ("line", sal2.line);
13563           uiout->text ("\n");
13564
13565           b->loc->line_number = sal2.line;
13566           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13567
13568           b->location.reset (NULL);
13569           initialize_explicit_location (&explicit_loc);
13570           explicit_loc.source_filename
13571             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
13572           explicit_loc.line_offset.offset = b->loc->line_number;
13573           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
13574           b->location = new_explicit_location (&explicit_loc);
13575
13576           /* Might be nice to check if function changed, and warn if
13577              so.  */
13578
13579           release_static_tracepoint_marker (tpmarker);
13580         }
13581     }
13582   return sal;
13583 }
13584
13585 /* Returns 1 iff locations A and B are sufficiently same that
13586    we don't need to report breakpoint as changed.  */
13587
13588 static int
13589 locations_are_equal (struct bp_location *a, struct bp_location *b)
13590 {
13591   while (a && b)
13592     {
13593       if (a->address != b->address)
13594         return 0;
13595
13596       if (a->shlib_disabled != b->shlib_disabled)
13597         return 0;
13598
13599       if (a->enabled != b->enabled)
13600         return 0;
13601
13602       a = a->next;
13603       b = b->next;
13604     }
13605
13606   if ((a == NULL) != (b == NULL))
13607     return 0;
13608
13609   return 1;
13610 }
13611
13612 /* Split all locations of B that are bound to PSPACE out of B's
13613    location list to a separate list and return that list's head.  If
13614    PSPACE is NULL, hoist out all locations of B.  */
13615
13616 static struct bp_location *
13617 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
13618 {
13619   struct bp_location head;
13620   struct bp_location *i = b->loc;
13621   struct bp_location **i_link = &b->loc;
13622   struct bp_location *hoisted = &head;
13623
13624   if (pspace == NULL)
13625     {
13626       i = b->loc;
13627       b->loc = NULL;
13628       return i;
13629     }
13630
13631   head.next = NULL;
13632
13633   while (i != NULL)
13634     {
13635       if (i->pspace == pspace)
13636         {
13637           *i_link = i->next;
13638           i->next = NULL;
13639           hoisted->next = i;
13640           hoisted = i;
13641         }
13642       else
13643         i_link = &i->next;
13644       i = *i_link;
13645     }
13646
13647   return head.next;
13648 }
13649
13650 /* Create new breakpoint locations for B (a hardware or software
13651    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
13652    zero, then B is a ranged breakpoint.  Only recreates locations for
13653    FILTER_PSPACE.  Locations of other program spaces are left
13654    untouched.  */
13655
13656 void
13657 update_breakpoint_locations (struct breakpoint *b,
13658                              struct program_space *filter_pspace,
13659                              gdb::array_view<const symtab_and_line> sals,
13660                              gdb::array_view<const symtab_and_line> sals_end)
13661 {
13662   struct bp_location *existing_locations;
13663
13664   if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
13665     {
13666       /* Ranged breakpoints have only one start location and one end
13667          location.  */
13668       b->enable_state = bp_disabled;
13669       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13670                            "multiple locations found\n"),
13671                          b->number);
13672       return;
13673     }
13674
13675   /* If there's no new locations, and all existing locations are
13676      pending, don't do anything.  This optimizes the common case where
13677      all locations are in the same shared library, that was unloaded.
13678      We'd like to retain the location, so that when the library is
13679      loaded again, we don't loose the enabled/disabled status of the
13680      individual locations.  */
13681   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
13682     return;
13683
13684   existing_locations = hoist_existing_locations (b, filter_pspace);
13685
13686   for (const auto &sal : sals)
13687     {
13688       struct bp_location *new_loc;
13689
13690       switch_to_program_space_and_thread (sal.pspace);
13691
13692       new_loc = add_location_to_breakpoint (b, &sal);
13693
13694       /* Reparse conditions, they might contain references to the
13695          old symtab.  */
13696       if (b->cond_string != NULL)
13697         {
13698           const char *s;
13699
13700           s = b->cond_string;
13701           TRY
13702             {
13703               new_loc->cond = parse_exp_1 (&s, sal.pc,
13704                                            block_for_pc (sal.pc),
13705                                            0);
13706             }
13707           CATCH (e, RETURN_MASK_ERROR)
13708             {
13709               warning (_("failed to reevaluate condition "
13710                          "for breakpoint %d: %s"), 
13711                        b->number, e.message);
13712               new_loc->enabled = 0;
13713             }
13714           END_CATCH
13715         }
13716
13717       if (!sals_end.empty ())
13718         {
13719           CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13720
13721           new_loc->length = end - sals[0].pc + 1;
13722         }
13723     }
13724
13725   /* If possible, carry over 'disable' status from existing
13726      breakpoints.  */
13727   {
13728     struct bp_location *e = existing_locations;
13729     /* If there are multiple breakpoints with the same function name,
13730        e.g. for inline functions, comparing function names won't work.
13731        Instead compare pc addresses; this is just a heuristic as things
13732        may have moved, but in practice it gives the correct answer
13733        often enough until a better solution is found.  */
13734     int have_ambiguous_names = ambiguous_names_p (b->loc);
13735
13736     for (; e; e = e->next)
13737       {
13738         if (!e->enabled && e->function_name)
13739           {
13740             struct bp_location *l = b->loc;
13741             if (have_ambiguous_names)
13742               {
13743                 for (; l; l = l->next)
13744                   if (breakpoint_locations_match (e, l))
13745                     {
13746                       l->enabled = 0;
13747                       break;
13748                     }
13749               }
13750             else
13751               {
13752                 for (; l; l = l->next)
13753                   if (l->function_name
13754                       && strcmp (e->function_name, l->function_name) == 0)
13755                     {
13756                       l->enabled = 0;
13757                       break;
13758                     }
13759               }
13760           }
13761       }
13762   }
13763
13764   if (!locations_are_equal (existing_locations, b->loc))
13765     observer_notify_breakpoint_modified (b);
13766 }
13767
13768 /* Find the SaL locations corresponding to the given LOCATION.
13769    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13770
13771 static std::vector<symtab_and_line>
13772 location_to_sals (struct breakpoint *b, struct event_location *location,
13773                   struct program_space *search_pspace, int *found)
13774 {
13775   struct gdb_exception exception = exception_none;
13776
13777   gdb_assert (b->ops != NULL);
13778
13779   std::vector<symtab_and_line> sals;
13780
13781   TRY
13782     {
13783       sals = b->ops->decode_location (b, location, search_pspace);
13784     }
13785   CATCH (e, RETURN_MASK_ERROR)
13786     {
13787       int not_found_and_ok = 0;
13788
13789       exception = e;
13790
13791       /* For pending breakpoints, it's expected that parsing will
13792          fail until the right shared library is loaded.  User has
13793          already told to create pending breakpoints and don't need
13794          extra messages.  If breakpoint is in bp_shlib_disabled
13795          state, then user already saw the message about that
13796          breakpoint being disabled, and don't want to see more
13797          errors.  */
13798       if (e.error == NOT_FOUND_ERROR
13799           && (b->condition_not_parsed
13800               || (b->loc != NULL
13801                   && search_pspace != NULL
13802                   && b->loc->pspace != search_pspace)
13803               || (b->loc && b->loc->shlib_disabled)
13804               || (b->loc && b->loc->pspace->executing_startup)
13805               || b->enable_state == bp_disabled))
13806         not_found_and_ok = 1;
13807
13808       if (!not_found_and_ok)
13809         {
13810           /* We surely don't want to warn about the same breakpoint
13811              10 times.  One solution, implemented here, is disable
13812              the breakpoint on error.  Another solution would be to
13813              have separate 'warning emitted' flag.  Since this
13814              happens only when a binary has changed, I don't know
13815              which approach is better.  */
13816           b->enable_state = bp_disabled;
13817           throw_exception (e);
13818         }
13819     }
13820   END_CATCH
13821
13822   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13823     {
13824       for (auto &sal : sals)
13825         resolve_sal_pc (&sal);
13826       if (b->condition_not_parsed && b->extra_string != NULL)
13827         {
13828           char *cond_string, *extra_string;
13829           int thread, task;
13830
13831           find_condition_and_thread (b->extra_string, sals[0].pc,
13832                                      &cond_string, &thread, &task,
13833                                      &extra_string);
13834           gdb_assert (b->cond_string == NULL);
13835           if (cond_string)
13836             b->cond_string = cond_string;
13837           b->thread = thread;
13838           b->task = task;
13839           if (extra_string)
13840             {
13841               xfree (b->extra_string);
13842               b->extra_string = extra_string;
13843             }
13844           b->condition_not_parsed = 0;
13845         }
13846
13847       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13848         sals[0] = update_static_tracepoint (b, sals[0]);
13849
13850       *found = 1;
13851     }
13852   else
13853     *found = 0;
13854
13855   return sals;
13856 }
13857
13858 /* The default re_set method, for typical hardware or software
13859    breakpoints.  Reevaluate the breakpoint and recreate its
13860    locations.  */
13861
13862 static void
13863 breakpoint_re_set_default (struct breakpoint *b)
13864 {
13865   struct program_space *filter_pspace = current_program_space;
13866   std::vector<symtab_and_line> expanded, expanded_end;
13867
13868   int found;
13869   std::vector<symtab_and_line> sals = location_to_sals (b, b->location.get (),
13870                                                         filter_pspace, &found);
13871   if (found)
13872     expanded = std::move (sals);
13873
13874   if (b->location_range_end != NULL)
13875     {
13876       std::vector<symtab_and_line> sals_end
13877         = location_to_sals (b, b->location_range_end.get (),
13878                             filter_pspace, &found);
13879       if (found)
13880         expanded_end = std::move (sals_end);
13881     }
13882
13883   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
13884 }
13885
13886 /* Default method for creating SALs from an address string.  It basically
13887    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13888
13889 static void
13890 create_sals_from_location_default (const struct event_location *location,
13891                                    struct linespec_result *canonical,
13892                                    enum bptype type_wanted)
13893 {
13894   parse_breakpoint_sals (location, canonical);
13895 }
13896
13897 /* Call create_breakpoints_sal for the given arguments.  This is the default
13898    function for the `create_breakpoints_sal' method of
13899    breakpoint_ops.  */
13900
13901 static void
13902 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13903                                 struct linespec_result *canonical,
13904                                 gdb::unique_xmalloc_ptr<char> cond_string,
13905                                 gdb::unique_xmalloc_ptr<char> extra_string,
13906                                 enum bptype type_wanted,
13907                                 enum bpdisp disposition,
13908                                 int thread,
13909                                 int task, int ignore_count,
13910                                 const struct breakpoint_ops *ops,
13911                                 int from_tty, int enabled,
13912                                 int internal, unsigned flags)
13913 {
13914   create_breakpoints_sal (gdbarch, canonical,
13915                           std::move (cond_string),
13916                           std::move (extra_string),
13917                           type_wanted, disposition,
13918                           thread, task, ignore_count, ops, from_tty,
13919                           enabled, internal, flags);
13920 }
13921
13922 /* Decode the line represented by S by calling decode_line_full.  This is the
13923    default function for the `decode_location' method of breakpoint_ops.  */
13924
13925 static std::vector<symtab_and_line>
13926 decode_location_default (struct breakpoint *b,
13927                          const struct event_location *location,
13928                          struct program_space *search_pspace)
13929 {
13930   struct linespec_result canonical;
13931
13932   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
13933                     (struct symtab *) NULL, 0,
13934                     &canonical, multiple_symbols_all,
13935                     b->filter);
13936
13937   /* We should get 0 or 1 resulting SALs.  */
13938   gdb_assert (canonical.lsals.size () < 2);
13939
13940   if (!canonical.lsals.empty ())
13941     {
13942       const linespec_sals &lsal = canonical.lsals[0];
13943       return std::move (lsal.sals);
13944     }
13945   return {};
13946 }
13947
13948 /* Reset a breakpoint.  */
13949
13950 static void
13951 breakpoint_re_set_one (breakpoint *b)
13952 {
13953   input_radix = b->input_radix;
13954   set_language (b->language);
13955
13956   b->ops->re_set (b);
13957 }
13958
13959 /* Re-set breakpoint locations for the current program space.
13960    Locations bound to other program spaces are left untouched.  */
13961
13962 void
13963 breakpoint_re_set (void)
13964 {
13965   struct breakpoint *b, *b_tmp;
13966
13967   {
13968     scoped_restore_current_language save_language;
13969     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
13970     scoped_restore_current_pspace_and_thread restore_pspace_thread;
13971
13972     /* Note: we must not try to insert locations until after all
13973        breakpoints have been re-set.  Otherwise, e.g., when re-setting
13974        breakpoint 1, we'd insert the locations of breakpoint 2, which
13975        hadn't been re-set yet, and thus may have stale locations.  */
13976
13977     ALL_BREAKPOINTS_SAFE (b, b_tmp)
13978       {
13979         TRY
13980           {
13981             breakpoint_re_set_one (b);
13982           }
13983         CATCH (ex, RETURN_MASK_ALL)
13984           {
13985             exception_fprintf (gdb_stderr, ex,
13986                                "Error in re-setting breakpoint %d: ",
13987                                b->number);
13988           }
13989         END_CATCH
13990       }
13991
13992     jit_breakpoint_re_set ();
13993   }
13994
13995   create_overlay_event_breakpoint ();
13996   create_longjmp_master_breakpoint ();
13997   create_std_terminate_master_breakpoint ();
13998   create_exception_master_breakpoint ();
13999
14000   /* Now we can insert.  */
14001   update_global_location_list (UGLL_MAY_INSERT);
14002 }
14003 \f
14004 /* Reset the thread number of this breakpoint:
14005
14006    - If the breakpoint is for all threads, leave it as-is.
14007    - Else, reset it to the current thread for inferior_ptid.  */
14008 void
14009 breakpoint_re_set_thread (struct breakpoint *b)
14010 {
14011   if (b->thread != -1)
14012     {
14013       if (in_thread_list (inferior_ptid))
14014         b->thread = ptid_to_global_thread_id (inferior_ptid);
14015
14016       /* We're being called after following a fork.  The new fork is
14017          selected as current, and unless this was a vfork will have a
14018          different program space from the original thread.  Reset that
14019          as well.  */
14020       b->loc->pspace = current_program_space;
14021     }
14022 }
14023
14024 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14025    If from_tty is nonzero, it prints a message to that effect,
14026    which ends with a period (no newline).  */
14027
14028 void
14029 set_ignore_count (int bptnum, int count, int from_tty)
14030 {
14031   struct breakpoint *b;
14032
14033   if (count < 0)
14034     count = 0;
14035
14036   ALL_BREAKPOINTS (b)
14037     if (b->number == bptnum)
14038     {
14039       if (is_tracepoint (b))
14040         {
14041           if (from_tty && count != 0)
14042             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14043                              bptnum);
14044           return;
14045         }
14046       
14047       b->ignore_count = count;
14048       if (from_tty)
14049         {
14050           if (count == 0)
14051             printf_filtered (_("Will stop next time "
14052                                "breakpoint %d is reached."),
14053                              bptnum);
14054           else if (count == 1)
14055             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14056                              bptnum);
14057           else
14058             printf_filtered (_("Will ignore next %d "
14059                                "crossings of breakpoint %d."),
14060                              count, bptnum);
14061         }
14062       observer_notify_breakpoint_modified (b);
14063       return;
14064     }
14065
14066   error (_("No breakpoint number %d."), bptnum);
14067 }
14068
14069 /* Command to set ignore-count of breakpoint N to COUNT.  */
14070
14071 static void
14072 ignore_command (const char *args, int from_tty)
14073 {
14074   const char *p = args;
14075   int num;
14076
14077   if (p == 0)
14078     error_no_arg (_("a breakpoint number"));
14079
14080   num = get_number (&p);
14081   if (num == 0)
14082     error (_("bad breakpoint number: '%s'"), args);
14083   if (*p == 0)
14084     error (_("Second argument (specified ignore-count) is missing."));
14085
14086   set_ignore_count (num,
14087                     longest_to_int (value_as_long (parse_and_eval (p))),
14088                     from_tty);
14089   if (from_tty)
14090     printf_filtered ("\n");
14091 }
14092 \f
14093
14094 /* Call FUNCTION on each of the breakpoints with numbers in the range
14095    defined by BP_NUM_RANGE (an inclusive range).  */
14096
14097 static void
14098 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
14099                              gdb::function_view<void (breakpoint *)> function)
14100 {
14101   if (bp_num_range.first == 0)
14102     {
14103       warning (_("bad breakpoint number at or near '%d'"),
14104                bp_num_range.first);
14105     }
14106   else
14107     {
14108       struct breakpoint *b, *tmp;
14109
14110       for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
14111         {
14112           bool match = false;
14113
14114           ALL_BREAKPOINTS_SAFE (b, tmp)
14115             if (b->number == i)
14116               {
14117                 match = true;
14118                 function (b);
14119                 break;
14120               }
14121           if (!match)
14122             printf_unfiltered (_("No breakpoint number %d.\n"), i);
14123         }
14124     }
14125 }
14126
14127 /* Call FUNCTION on each of the breakpoints whose numbers are given in
14128    ARGS.  */
14129
14130 static void
14131 map_breakpoint_numbers (const char *args,
14132                         gdb::function_view<void (breakpoint *)> function)
14133 {
14134   if (args == NULL || *args == '\0')
14135     error_no_arg (_("one or more breakpoint numbers"));
14136
14137   number_or_range_parser parser (args);
14138
14139   while (!parser.finished ())
14140     {
14141       int num = parser.get_number ();
14142       map_breakpoint_number_range (std::make_pair (num, num), function);
14143     }
14144 }
14145
14146 /* Return the breakpoint location structure corresponding to the
14147    BP_NUM and LOC_NUM values.  */
14148
14149 static struct bp_location *
14150 find_location_by_number (int bp_num, int loc_num)
14151 {
14152   struct breakpoint *b;
14153
14154   ALL_BREAKPOINTS (b)
14155     if (b->number == bp_num)
14156       {
14157         break;
14158       }
14159
14160   if (!b || b->number != bp_num)
14161     error (_("Bad breakpoint number '%d'"), bp_num);
14162   
14163   if (loc_num == 0)
14164     error (_("Bad breakpoint location number '%d'"), loc_num);
14165
14166   int n = 0;
14167   for (bp_location *loc = b->loc; loc != NULL; loc = loc->next)
14168     if (++n == loc_num)
14169       return loc;
14170
14171   error (_("Bad breakpoint location number '%d'"), loc_num);
14172 }
14173
14174 /* Modes of operation for extract_bp_num.  */
14175 enum class extract_bp_kind
14176 {
14177   /* Extracting a breakpoint number.  */
14178   bp,
14179
14180   /* Extracting a location number.  */
14181   loc,
14182 };
14183
14184 /* Extract a breakpoint or location number (as determined by KIND)
14185    from the string starting at START.  TRAILER is a character which
14186    can be found after the number.  If you don't want a trailer, use
14187    '\0'.  If END_OUT is not NULL, it is set to point after the parsed
14188    string.  This always returns a positive integer.  */
14189
14190 static int
14191 extract_bp_num (extract_bp_kind kind, const char *start,
14192                 int trailer, const char **end_out = NULL)
14193 {
14194   const char *end = start;
14195   int num = get_number_trailer (&end, trailer);
14196   if (num < 0)
14197     error (kind == extract_bp_kind::bp
14198            ? _("Negative breakpoint number '%.*s'")
14199            : _("Negative breakpoint location number '%.*s'"),
14200            int (end - start), start);
14201   if (num == 0)
14202     error (kind == extract_bp_kind::bp
14203            ? _("Bad breakpoint number '%.*s'")
14204            : _("Bad breakpoint location number '%.*s'"),
14205            int (end - start), start);
14206
14207   if (end_out != NULL)
14208     *end_out = end;
14209   return num;
14210 }
14211
14212 /* Extract a breakpoint or location range (as determined by KIND) in
14213    the form NUM1-NUM2 stored at &ARG[arg_offset].  Returns a std::pair
14214    representing the (inclusive) range.  The returned pair's elements
14215    are always positive integers.  */
14216
14217 static std::pair<int, int>
14218 extract_bp_or_bp_range (extract_bp_kind kind,
14219                         const std::string &arg,
14220                         std::string::size_type arg_offset)
14221 {
14222   std::pair<int, int> range;
14223   const char *bp_loc = &arg[arg_offset];
14224   std::string::size_type dash = arg.find ('-', arg_offset);
14225   if (dash != std::string::npos)
14226     {
14227       /* bp_loc is a range (x-z).  */
14228       if (arg.length () == dash + 1)
14229         error (kind == extract_bp_kind::bp
14230                ? _("Bad breakpoint number at or near: '%s'")
14231                : _("Bad breakpoint location number at or near: '%s'"),
14232                bp_loc);
14233
14234       const char *end;
14235       const char *start_first = bp_loc;
14236       const char *start_second = &arg[dash + 1];
14237       range.first = extract_bp_num (kind, start_first, '-');
14238       range.second = extract_bp_num (kind, start_second, '\0', &end);
14239
14240       if (range.first > range.second)
14241         error (kind == extract_bp_kind::bp
14242                ? _("Inverted breakpoint range at '%.*s'")
14243                : _("Inverted breakpoint location range at '%.*s'"),
14244                int (end - start_first), start_first);
14245     }
14246   else
14247     {
14248       /* bp_loc is a single value.  */
14249       range.first = extract_bp_num (kind, bp_loc, '\0');
14250       range.second = range.first;
14251     }
14252   return range;
14253 }
14254
14255 /* Extract the breakpoint/location range specified by ARG.  Returns
14256    the breakpoint range in BP_NUM_RANGE, and the location range in
14257    BP_LOC_RANGE.
14258
14259    ARG may be in any of the following forms:
14260
14261    x     where 'x' is a breakpoint number.
14262    x-y   where 'x' and 'y' specify a breakpoint numbers range.
14263    x.y   where 'x' is a breakpoint number and 'y' a location number.
14264    x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
14265          location number range.
14266 */
14267
14268 static void
14269 extract_bp_number_and_location (const std::string &arg,
14270                                 std::pair<int, int> &bp_num_range,
14271                                 std::pair<int, int> &bp_loc_range)
14272 {
14273   std::string::size_type dot = arg.find ('.');
14274
14275   if (dot != std::string::npos)
14276     {
14277       /* Handle 'x.y' and 'x.y-z' cases.  */
14278
14279       if (arg.length () == dot + 1 || dot == 0)
14280         error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
14281
14282       bp_num_range.first
14283         = extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
14284       bp_num_range.second = bp_num_range.first;
14285
14286       bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
14287                                              arg, dot + 1);
14288     }
14289   else
14290     {
14291       /* Handle x and x-y cases.  */
14292
14293       bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
14294       bp_loc_range.first = 0;
14295       bp_loc_range.second = 0;
14296     }
14297 }
14298
14299 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM.  ENABLE
14300    specifies whether to enable or disable.  */
14301
14302 static void
14303 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
14304 {
14305   struct bp_location *loc = find_location_by_number (bp_num, loc_num);
14306   if (loc != NULL)
14307     {
14308       if (loc->enabled != enable)
14309         {
14310           loc->enabled = enable;
14311           mark_breakpoint_location_modified (loc);
14312         }
14313       if (target_supports_enable_disable_tracepoint ()
14314           && current_trace_status ()->running && loc->owner
14315           && is_tracepoint (loc->owner))
14316         target_disable_tracepoint (loc);
14317     }
14318   update_global_location_list (UGLL_DONT_INSERT);
14319 }
14320
14321 /* Enable or disable a range of breakpoint locations.  BP_NUM is the
14322    number of the breakpoint, and BP_LOC_RANGE specifies the
14323    (inclusive) range of location numbers of that breakpoint to
14324    enable/disable.  ENABLE specifies whether to enable or disable the
14325    location.  */
14326
14327 static void
14328 enable_disable_breakpoint_location_range (int bp_num,
14329                                           std::pair<int, int> &bp_loc_range,
14330                                           bool enable)
14331 {
14332   for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
14333     enable_disable_bp_num_loc (bp_num, i, enable);
14334 }
14335
14336 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14337    If from_tty is nonzero, it prints a message to that effect,
14338    which ends with a period (no newline).  */
14339
14340 void
14341 disable_breakpoint (struct breakpoint *bpt)
14342 {
14343   /* Never disable a watchpoint scope breakpoint; we want to
14344      hit them when we leave scope so we can delete both the
14345      watchpoint and its scope breakpoint at that time.  */
14346   if (bpt->type == bp_watchpoint_scope)
14347     return;
14348
14349   bpt->enable_state = bp_disabled;
14350
14351   /* Mark breakpoint locations modified.  */
14352   mark_breakpoint_modified (bpt);
14353
14354   if (target_supports_enable_disable_tracepoint ()
14355       && current_trace_status ()->running && is_tracepoint (bpt))
14356     {
14357       struct bp_location *location;
14358      
14359       for (location = bpt->loc; location; location = location->next)
14360         target_disable_tracepoint (location);
14361     }
14362
14363   update_global_location_list (UGLL_DONT_INSERT);
14364
14365   observer_notify_breakpoint_modified (bpt);
14366 }
14367
14368 /* Enable or disable the breakpoint(s) or breakpoint location(s)
14369    specified in ARGS.  ARGS may be in any of the formats handled by
14370    extract_bp_number_and_location.  ENABLE specifies whether to enable
14371    or disable the breakpoints/locations.  */
14372
14373 static void
14374 enable_disable_command (const char *args, int from_tty, bool enable)
14375 {
14376   if (args == 0)
14377     {
14378       struct breakpoint *bpt;
14379
14380       ALL_BREAKPOINTS (bpt)
14381         if (user_breakpoint_p (bpt))
14382           {
14383             if (enable)
14384               enable_breakpoint (bpt);
14385             else
14386               disable_breakpoint (bpt);
14387           }
14388     }
14389   else
14390     {
14391       std::string num = extract_arg (&args);
14392
14393       while (!num.empty ())
14394         {
14395           std::pair<int, int> bp_num_range, bp_loc_range;
14396
14397           extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
14398
14399           if (bp_loc_range.first == bp_loc_range.second
14400               && bp_loc_range.first == 0)
14401             {
14402               /* Handle breakpoint ids with formats 'x' or 'x-z'.  */
14403               map_breakpoint_number_range (bp_num_range,
14404                                            enable
14405                                            ? enable_breakpoint
14406                                            : disable_breakpoint);
14407             }
14408           else
14409             {
14410               /* Handle breakpoint ids with formats 'x.y' or
14411                  'x.y-z'.  */
14412               enable_disable_breakpoint_location_range
14413                 (bp_num_range.first, bp_loc_range, enable);
14414             }
14415           num = extract_arg (&args);
14416         }
14417     }
14418 }
14419
14420 /* The disable command disables the specified breakpoints/locations
14421    (or all defined breakpoints) so they're no longer effective in
14422    stopping the inferior.  ARGS may be in any of the forms defined in
14423    extract_bp_number_and_location.  */
14424
14425 static void
14426 disable_command (const char *args, int from_tty)
14427 {
14428   enable_disable_command (args, from_tty, false);
14429 }
14430
14431 static void
14432 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14433                         int count)
14434 {
14435   int target_resources_ok;
14436
14437   if (bpt->type == bp_hardware_breakpoint)
14438     {
14439       int i;
14440       i = hw_breakpoint_used_count ();
14441       target_resources_ok = 
14442         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14443                                             i + 1, 0);
14444       if (target_resources_ok == 0)
14445         error (_("No hardware breakpoint support in the target."));
14446       else if (target_resources_ok < 0)
14447         error (_("Hardware breakpoints used exceeds limit."));
14448     }
14449
14450   if (is_watchpoint (bpt))
14451     {
14452       /* Initialize it just to avoid a GCC false warning.  */
14453       enum enable_state orig_enable_state = bp_disabled;
14454
14455       TRY
14456         {
14457           struct watchpoint *w = (struct watchpoint *) bpt;
14458
14459           orig_enable_state = bpt->enable_state;
14460           bpt->enable_state = bp_enabled;
14461           update_watchpoint (w, 1 /* reparse */);
14462         }
14463       CATCH (e, RETURN_MASK_ALL)
14464         {
14465           bpt->enable_state = orig_enable_state;
14466           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14467                              bpt->number);
14468           return;
14469         }
14470       END_CATCH
14471     }
14472
14473   bpt->enable_state = bp_enabled;
14474
14475   /* Mark breakpoint locations modified.  */
14476   mark_breakpoint_modified (bpt);
14477
14478   if (target_supports_enable_disable_tracepoint ()
14479       && current_trace_status ()->running && is_tracepoint (bpt))
14480     {
14481       struct bp_location *location;
14482
14483       for (location = bpt->loc; location; location = location->next)
14484         target_enable_tracepoint (location);
14485     }
14486
14487   bpt->disposition = disposition;
14488   bpt->enable_count = count;
14489   update_global_location_list (UGLL_MAY_INSERT);
14490
14491   observer_notify_breakpoint_modified (bpt);
14492 }
14493
14494
14495 void
14496 enable_breakpoint (struct breakpoint *bpt)
14497 {
14498   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14499 }
14500
14501 /* The enable command enables the specified breakpoints/locations (or
14502    all defined breakpoints) so they once again become (or continue to
14503    be) effective in stopping the inferior.  ARGS may be in any of the
14504    forms defined in extract_bp_number_and_location.  */
14505
14506 static void
14507 enable_command (const char *args, int from_tty)
14508 {
14509   enable_disable_command (args, from_tty, true);
14510 }
14511
14512 static void
14513 enable_once_command (const char *args, int from_tty)
14514 {
14515   map_breakpoint_numbers
14516     (args, [&] (breakpoint *b)
14517      {
14518        iterate_over_related_breakpoints
14519          (b, [&] (breakpoint *bpt)
14520           {
14521             enable_breakpoint_disp (bpt, disp_disable, 1);
14522           });
14523      });
14524 }
14525
14526 static void
14527 enable_count_command (const char *args, int from_tty)
14528 {
14529   int count;
14530
14531   if (args == NULL)
14532     error_no_arg (_("hit count"));
14533
14534   count = get_number (&args);
14535
14536   map_breakpoint_numbers
14537     (args, [&] (breakpoint *b)
14538      {
14539        iterate_over_related_breakpoints
14540          (b, [&] (breakpoint *bpt)
14541           {
14542             enable_breakpoint_disp (bpt, disp_disable, count);
14543           });
14544      });
14545 }
14546
14547 static void
14548 enable_delete_command (const char *args, int from_tty)
14549 {
14550   map_breakpoint_numbers
14551     (args, [&] (breakpoint *b)
14552      {
14553        iterate_over_related_breakpoints
14554          (b, [&] (breakpoint *bpt)
14555           {
14556             enable_breakpoint_disp (bpt, disp_del, 1);
14557           });
14558      });
14559 }
14560 \f
14561 static void
14562 set_breakpoint_cmd (const char *args, int from_tty)
14563 {
14564 }
14565
14566 static void
14567 show_breakpoint_cmd (const char *args, int from_tty)
14568 {
14569 }
14570
14571 /* Invalidate last known value of any hardware watchpoint if
14572    the memory which that value represents has been written to by
14573    GDB itself.  */
14574
14575 static void
14576 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14577                                       CORE_ADDR addr, ssize_t len,
14578                                       const bfd_byte *data)
14579 {
14580   struct breakpoint *bp;
14581
14582   ALL_BREAKPOINTS (bp)
14583     if (bp->enable_state == bp_enabled
14584         && bp->type == bp_hardware_watchpoint)
14585       {
14586         struct watchpoint *wp = (struct watchpoint *) bp;
14587
14588         if (wp->val_valid && wp->val)
14589           {
14590             struct bp_location *loc;
14591
14592             for (loc = bp->loc; loc != NULL; loc = loc->next)
14593               if (loc->loc_type == bp_loc_hardware_watchpoint
14594                   && loc->address + loc->length > addr
14595                   && addr + len > loc->address)
14596                 {
14597                   value_free (wp->val);
14598                   wp->val = NULL;
14599                   wp->val_valid = 0;
14600                 }
14601           }
14602       }
14603 }
14604
14605 /* Create and insert a breakpoint for software single step.  */
14606
14607 void
14608 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14609                                const address_space *aspace,
14610                                CORE_ADDR next_pc)
14611 {
14612   struct thread_info *tp = inferior_thread ();
14613   struct symtab_and_line sal;
14614   CORE_ADDR pc = next_pc;
14615
14616   if (tp->control.single_step_breakpoints == NULL)
14617     {
14618       tp->control.single_step_breakpoints
14619         = new_single_step_breakpoint (tp->global_num, gdbarch);
14620     }
14621
14622   sal = find_pc_line (pc, 0);
14623   sal.pc = pc;
14624   sal.section = find_pc_overlay (pc);
14625   sal.explicit_pc = 1;
14626   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14627
14628   update_global_location_list (UGLL_INSERT);
14629 }
14630
14631 /* Insert single step breakpoints according to the current state.  */
14632
14633 int
14634 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14635 {
14636   struct regcache *regcache = get_current_regcache ();
14637   std::vector<CORE_ADDR> next_pcs;
14638
14639   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14640
14641   if (!next_pcs.empty ())
14642     {
14643       struct frame_info *frame = get_current_frame ();
14644       const address_space *aspace = get_frame_address_space (frame);
14645
14646       for (CORE_ADDR pc : next_pcs)
14647         insert_single_step_breakpoint (gdbarch, aspace, pc);
14648
14649       return 1;
14650     }
14651   else
14652     return 0;
14653 }
14654
14655 /* See breakpoint.h.  */
14656
14657 int
14658 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14659                                        const address_space *aspace,
14660                                        CORE_ADDR pc)
14661 {
14662   struct bp_location *loc;
14663
14664   for (loc = bp->loc; loc != NULL; loc = loc->next)
14665     if (loc->inserted
14666         && breakpoint_location_address_match (loc, aspace, pc))
14667       return 1;
14668
14669   return 0;
14670 }
14671
14672 /* Check whether a software single-step breakpoint is inserted at
14673    PC.  */
14674
14675 int
14676 single_step_breakpoint_inserted_here_p (const address_space *aspace,
14677                                         CORE_ADDR pc)
14678 {
14679   struct breakpoint *bpt;
14680
14681   ALL_BREAKPOINTS (bpt)
14682     {
14683       if (bpt->type == bp_single_step
14684           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
14685         return 1;
14686     }
14687   return 0;
14688 }
14689
14690 /* Tracepoint-specific operations.  */
14691
14692 /* Set tracepoint count to NUM.  */
14693 static void
14694 set_tracepoint_count (int num)
14695 {
14696   tracepoint_count = num;
14697   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14698 }
14699
14700 static void
14701 trace_command (const char *arg, int from_tty)
14702 {
14703   struct breakpoint_ops *ops;
14704
14705   event_location_up location = string_to_event_location (&arg,
14706                                                          current_language);
14707   if (location != NULL
14708       && event_location_type (location.get ()) == PROBE_LOCATION)
14709     ops = &tracepoint_probe_breakpoint_ops;
14710   else
14711     ops = &tracepoint_breakpoint_ops;
14712
14713   create_breakpoint (get_current_arch (),
14714                      location.get (),
14715                      NULL, 0, arg, 1 /* parse arg */,
14716                      0 /* tempflag */,
14717                      bp_tracepoint /* type_wanted */,
14718                      0 /* Ignore count */,
14719                      pending_break_support,
14720                      ops,
14721                      from_tty,
14722                      1 /* enabled */,
14723                      0 /* internal */, 0);
14724 }
14725
14726 static void
14727 ftrace_command (const char *arg, int from_tty)
14728 {
14729   event_location_up location = string_to_event_location (&arg,
14730                                                          current_language);
14731   create_breakpoint (get_current_arch (),
14732                      location.get (),
14733                      NULL, 0, arg, 1 /* parse arg */,
14734                      0 /* tempflag */,
14735                      bp_fast_tracepoint /* type_wanted */,
14736                      0 /* Ignore count */,
14737                      pending_break_support,
14738                      &tracepoint_breakpoint_ops,
14739                      from_tty,
14740                      1 /* enabled */,
14741                      0 /* internal */, 0);
14742 }
14743
14744 /* strace command implementation.  Creates a static tracepoint.  */
14745
14746 static void
14747 strace_command (const char *arg, int from_tty)
14748 {
14749   struct breakpoint_ops *ops;
14750   event_location_up location;
14751
14752   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14753      or with a normal static tracepoint.  */
14754   if (arg && startswith (arg, "-m") && isspace (arg[2]))
14755     {
14756       ops = &strace_marker_breakpoint_ops;
14757       location = new_linespec_location (&arg, symbol_name_match_type::FULL);
14758     }
14759   else
14760     {
14761       ops = &tracepoint_breakpoint_ops;
14762       location = string_to_event_location (&arg, current_language);
14763     }
14764
14765   create_breakpoint (get_current_arch (),
14766                      location.get (),
14767                      NULL, 0, arg, 1 /* parse arg */,
14768                      0 /* tempflag */,
14769                      bp_static_tracepoint /* type_wanted */,
14770                      0 /* Ignore count */,
14771                      pending_break_support,
14772                      ops,
14773                      from_tty,
14774                      1 /* enabled */,
14775                      0 /* internal */, 0);
14776 }
14777
14778 /* Set up a fake reader function that gets command lines from a linked
14779    list that was acquired during tracepoint uploading.  */
14780
14781 static struct uploaded_tp *this_utp;
14782 static int next_cmd;
14783
14784 static char *
14785 read_uploaded_action (void)
14786 {
14787   char *rslt;
14788
14789   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
14790
14791   next_cmd++;
14792
14793   return rslt;
14794 }
14795
14796 /* Given information about a tracepoint as recorded on a target (which
14797    can be either a live system or a trace file), attempt to create an
14798    equivalent GDB tracepoint.  This is not a reliable process, since
14799    the target does not necessarily have all the information used when
14800    the tracepoint was originally defined.  */
14801   
14802 struct tracepoint *
14803 create_tracepoint_from_upload (struct uploaded_tp *utp)
14804 {
14805   const char *addr_str;
14806   char small_buf[100];
14807   struct tracepoint *tp;
14808
14809   if (utp->at_string)
14810     addr_str = utp->at_string;
14811   else
14812     {
14813       /* In the absence of a source location, fall back to raw
14814          address.  Since there is no way to confirm that the address
14815          means the same thing as when the trace was started, warn the
14816          user.  */
14817       warning (_("Uploaded tracepoint %d has no "
14818                  "source location, using raw address"),
14819                utp->number);
14820       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14821       addr_str = small_buf;
14822     }
14823
14824   /* There's not much we can do with a sequence of bytecodes.  */
14825   if (utp->cond && !utp->cond_string)
14826     warning (_("Uploaded tracepoint %d condition "
14827                "has no source form, ignoring it"),
14828              utp->number);
14829
14830   event_location_up location = string_to_event_location (&addr_str,
14831                                                          current_language);
14832   if (!create_breakpoint (get_current_arch (),
14833                           location.get (),
14834                           utp->cond_string, -1, addr_str,
14835                           0 /* parse cond/thread */,
14836                           0 /* tempflag */,
14837                           utp->type /* type_wanted */,
14838                           0 /* Ignore count */,
14839                           pending_break_support,
14840                           &tracepoint_breakpoint_ops,
14841                           0 /* from_tty */,
14842                           utp->enabled /* enabled */,
14843                           0 /* internal */,
14844                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14845     return NULL;
14846
14847   /* Get the tracepoint we just created.  */
14848   tp = get_tracepoint (tracepoint_count);
14849   gdb_assert (tp != NULL);
14850
14851   if (utp->pass > 0)
14852     {
14853       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14854                  tp->number);
14855
14856       trace_pass_command (small_buf, 0);
14857     }
14858
14859   /* If we have uploaded versions of the original commands, set up a
14860      special-purpose "reader" function and call the usual command line
14861      reader, then pass the result to the breakpoint command-setting
14862      function.  */
14863   if (!VEC_empty (char_ptr, utp->cmd_strings))
14864     {
14865       command_line_up cmd_list;
14866
14867       this_utp = utp;
14868       next_cmd = 0;
14869
14870       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
14871
14872       breakpoint_set_commands (tp, std::move (cmd_list));
14873     }
14874   else if (!VEC_empty (char_ptr, utp->actions)
14875            || !VEC_empty (char_ptr, utp->step_actions))
14876     warning (_("Uploaded tracepoint %d actions "
14877                "have no source form, ignoring them"),
14878              utp->number);
14879
14880   /* Copy any status information that might be available.  */
14881   tp->hit_count = utp->hit_count;
14882   tp->traceframe_usage = utp->traceframe_usage;
14883
14884   return tp;
14885 }
14886   
14887 /* Print information on tracepoint number TPNUM_EXP, or all if
14888    omitted.  */
14889
14890 static void
14891 info_tracepoints_command (const char *args, int from_tty)
14892 {
14893   struct ui_out *uiout = current_uiout;
14894   int num_printed;
14895
14896   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14897
14898   if (num_printed == 0)
14899     {
14900       if (args == NULL || *args == '\0')
14901         uiout->message ("No tracepoints.\n");
14902       else
14903         uiout->message ("No tracepoint matching '%s'.\n", args);
14904     }
14905
14906   default_collect_info ();
14907 }
14908
14909 /* The 'enable trace' command enables tracepoints.
14910    Not supported by all targets.  */
14911 static void
14912 enable_trace_command (const char *args, int from_tty)
14913 {
14914   enable_command (args, from_tty);
14915 }
14916
14917 /* The 'disable trace' command disables tracepoints.
14918    Not supported by all targets.  */
14919 static void
14920 disable_trace_command (const char *args, int from_tty)
14921 {
14922   disable_command (args, from_tty);
14923 }
14924
14925 /* Remove a tracepoint (or all if no argument).  */
14926 static void
14927 delete_trace_command (const char *arg, int from_tty)
14928 {
14929   struct breakpoint *b, *b_tmp;
14930
14931   dont_repeat ();
14932
14933   if (arg == 0)
14934     {
14935       int breaks_to_delete = 0;
14936
14937       /* Delete all breakpoints if no argument.
14938          Do not delete internal or call-dummy breakpoints, these
14939          have to be deleted with an explicit breakpoint number 
14940          argument.  */
14941       ALL_TRACEPOINTS (b)
14942         if (is_tracepoint (b) && user_breakpoint_p (b))
14943           {
14944             breaks_to_delete = 1;
14945             break;
14946           }
14947
14948       /* Ask user only if there are some breakpoints to delete.  */
14949       if (!from_tty
14950           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14951         {
14952           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14953             if (is_tracepoint (b) && user_breakpoint_p (b))
14954               delete_breakpoint (b);
14955         }
14956     }
14957   else
14958     map_breakpoint_numbers
14959       (arg, [&] (breakpoint *b)
14960        {
14961          iterate_over_related_breakpoints (b, delete_breakpoint);
14962        });
14963 }
14964
14965 /* Helper function for trace_pass_command.  */
14966
14967 static void
14968 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14969 {
14970   tp->pass_count = count;
14971   observer_notify_breakpoint_modified (tp);
14972   if (from_tty)
14973     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
14974                      tp->number, count);
14975 }
14976
14977 /* Set passcount for tracepoint.
14978
14979    First command argument is passcount, second is tracepoint number.
14980    If tracepoint number omitted, apply to most recently defined.
14981    Also accepts special argument "all".  */
14982
14983 static void
14984 trace_pass_command (const char *args, int from_tty)
14985 {
14986   struct tracepoint *t1;
14987   ULONGEST count;
14988
14989   if (args == 0 || *args == 0)
14990     error (_("passcount command requires an "
14991              "argument (count + optional TP num)"));
14992
14993   count = strtoulst (args, &args, 10);  /* Count comes first, then TP num.  */
14994
14995   args = skip_spaces (args);
14996   if (*args && strncasecmp (args, "all", 3) == 0)
14997     {
14998       struct breakpoint *b;
14999
15000       args += 3;                        /* Skip special argument "all".  */
15001       if (*args)
15002         error (_("Junk at end of arguments."));
15003
15004       ALL_TRACEPOINTS (b)
15005       {
15006         t1 = (struct tracepoint *) b;
15007         trace_pass_set_count (t1, count, from_tty);
15008       }
15009     }
15010   else if (*args == '\0')
15011     {
15012       t1 = get_tracepoint_by_number (&args, NULL);
15013       if (t1)
15014         trace_pass_set_count (t1, count, from_tty);
15015     }
15016   else
15017     {
15018       number_or_range_parser parser (args);
15019       while (!parser.finished ())
15020         {
15021           t1 = get_tracepoint_by_number (&args, &parser);
15022           if (t1)
15023             trace_pass_set_count (t1, count, from_tty);
15024         }
15025     }
15026 }
15027
15028 struct tracepoint *
15029 get_tracepoint (int num)
15030 {
15031   struct breakpoint *t;
15032
15033   ALL_TRACEPOINTS (t)
15034     if (t->number == num)
15035       return (struct tracepoint *) t;
15036
15037   return NULL;
15038 }
15039
15040 /* Find the tracepoint with the given target-side number (which may be
15041    different from the tracepoint number after disconnecting and
15042    reconnecting).  */
15043
15044 struct tracepoint *
15045 get_tracepoint_by_number_on_target (int num)
15046 {
15047   struct breakpoint *b;
15048
15049   ALL_TRACEPOINTS (b)
15050     {
15051       struct tracepoint *t = (struct tracepoint *) b;
15052
15053       if (t->number_on_target == num)
15054         return t;
15055     }
15056
15057   return NULL;
15058 }
15059
15060 /* Utility: parse a tracepoint number and look it up in the list.
15061    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15062    If the argument is missing, the most recent tracepoint
15063    (tracepoint_count) is returned.  */
15064
15065 struct tracepoint *
15066 get_tracepoint_by_number (const char **arg,
15067                           number_or_range_parser *parser)
15068 {
15069   struct breakpoint *t;
15070   int tpnum;
15071   const char *instring = arg == NULL ? NULL : *arg;
15072
15073   if (parser != NULL)
15074     {
15075       gdb_assert (!parser->finished ());
15076       tpnum = parser->get_number ();
15077     }
15078   else if (arg == NULL || *arg == NULL || ! **arg)
15079     tpnum = tracepoint_count;
15080   else
15081     tpnum = get_number (arg);
15082
15083   if (tpnum <= 0)
15084     {
15085       if (instring && *instring)
15086         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15087                          instring);
15088       else
15089         printf_filtered (_("No previous tracepoint\n"));
15090       return NULL;
15091     }
15092
15093   ALL_TRACEPOINTS (t)
15094     if (t->number == tpnum)
15095     {
15096       return (struct tracepoint *) t;
15097     }
15098
15099   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15100   return NULL;
15101 }
15102
15103 void
15104 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15105 {
15106   if (b->thread != -1)
15107     fprintf_unfiltered (fp, " thread %d", b->thread);
15108
15109   if (b->task != 0)
15110     fprintf_unfiltered (fp, " task %d", b->task);
15111
15112   fprintf_unfiltered (fp, "\n");
15113 }
15114
15115 /* Save information on user settable breakpoints (watchpoints, etc) to
15116    a new script file named FILENAME.  If FILTER is non-NULL, call it
15117    on each breakpoint and only include the ones for which it returns
15118    non-zero.  */
15119
15120 static void
15121 save_breakpoints (const char *filename, int from_tty,
15122                   int (*filter) (const struct breakpoint *))
15123 {
15124   struct breakpoint *tp;
15125   int any = 0;
15126   int extra_trace_bits = 0;
15127
15128   if (filename == 0 || *filename == 0)
15129     error (_("Argument required (file name in which to save)"));
15130
15131   /* See if we have anything to save.  */
15132   ALL_BREAKPOINTS (tp)
15133   {
15134     /* Skip internal and momentary breakpoints.  */
15135     if (!user_breakpoint_p (tp))
15136       continue;
15137
15138     /* If we have a filter, only save the breakpoints it accepts.  */
15139     if (filter && !filter (tp))
15140       continue;
15141
15142     any = 1;
15143
15144     if (is_tracepoint (tp))
15145       {
15146         extra_trace_bits = 1;
15147
15148         /* We can stop searching.  */
15149         break;
15150       }
15151   }
15152
15153   if (!any)
15154     {
15155       warning (_("Nothing to save."));
15156       return;
15157     }
15158
15159   gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
15160
15161   stdio_file fp;
15162
15163   if (!fp.open (expanded_filename.get (), "w"))
15164     error (_("Unable to open file '%s' for saving (%s)"),
15165            expanded_filename.get (), safe_strerror (errno));
15166
15167   if (extra_trace_bits)
15168     save_trace_state_variables (&fp);
15169
15170   ALL_BREAKPOINTS (tp)
15171   {
15172     /* Skip internal and momentary breakpoints.  */
15173     if (!user_breakpoint_p (tp))
15174       continue;
15175
15176     /* If we have a filter, only save the breakpoints it accepts.  */
15177     if (filter && !filter (tp))
15178       continue;
15179
15180     tp->ops->print_recreate (tp, &fp);
15181
15182     /* Note, we can't rely on tp->number for anything, as we can't
15183        assume the recreated breakpoint numbers will match.  Use $bpnum
15184        instead.  */
15185
15186     if (tp->cond_string)
15187       fp.printf ("  condition $bpnum %s\n", tp->cond_string);
15188
15189     if (tp->ignore_count)
15190       fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15191
15192     if (tp->type != bp_dprintf && tp->commands)
15193       {
15194         fp.puts ("  commands\n");
15195         
15196         current_uiout->redirect (&fp);
15197         TRY
15198           {
15199             print_command_lines (current_uiout, tp->commands.get (), 2);
15200           }
15201         CATCH (ex, RETURN_MASK_ALL)
15202           {
15203           current_uiout->redirect (NULL);
15204             throw_exception (ex);
15205           }
15206         END_CATCH
15207
15208         current_uiout->redirect (NULL);
15209         fp.puts ("  end\n");
15210       }
15211
15212     if (tp->enable_state == bp_disabled)
15213       fp.puts ("disable $bpnum\n");
15214
15215     /* If this is a multi-location breakpoint, check if the locations
15216        should be individually disabled.  Watchpoint locations are
15217        special, and not user visible.  */
15218     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15219       {
15220         struct bp_location *loc;
15221         int n = 1;
15222
15223         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15224           if (!loc->enabled)
15225             fp.printf ("disable $bpnum.%d\n", n);
15226       }
15227   }
15228
15229   if (extra_trace_bits && *default_collect)
15230     fp.printf ("set default-collect %s\n", default_collect);
15231
15232   if (from_tty)
15233     printf_filtered (_("Saved to file '%s'.\n"), expanded_filename.get ());
15234 }
15235
15236 /* The `save breakpoints' command.  */
15237
15238 static void
15239 save_breakpoints_command (const char *args, int from_tty)
15240 {
15241   save_breakpoints (args, from_tty, NULL);
15242 }
15243
15244 /* The `save tracepoints' command.  */
15245
15246 static void
15247 save_tracepoints_command (const char *args, int from_tty)
15248 {
15249   save_breakpoints (args, from_tty, is_tracepoint);
15250 }
15251
15252 /* Create a vector of all tracepoints.  */
15253
15254 VEC(breakpoint_p) *
15255 all_tracepoints (void)
15256 {
15257   VEC(breakpoint_p) *tp_vec = 0;
15258   struct breakpoint *tp;
15259
15260   ALL_TRACEPOINTS (tp)
15261   {
15262     VEC_safe_push (breakpoint_p, tp_vec, tp);
15263   }
15264
15265   return tp_vec;
15266 }
15267
15268 \f
15269 /* This help string is used to consolidate all the help string for specifying
15270    locations used by several commands.  */
15271
15272 #define LOCATION_HELP_STRING \
15273 "Linespecs are colon-separated lists of location parameters, such as\n\
15274 source filename, function name, label name, and line number.\n\
15275 Example: To specify the start of a label named \"the_top\" in the\n\
15276 function \"fact\" in the file \"factorial.c\", use\n\
15277 \"factorial.c:fact:the_top\".\n\
15278 \n\
15279 Address locations begin with \"*\" and specify an exact address in the\n\
15280 program.  Example: To specify the fourth byte past the start function\n\
15281 \"main\", use \"*main + 4\".\n\
15282 \n\
15283 Explicit locations are similar to linespecs but use an option/argument\n\
15284 syntax to specify location parameters.\n\
15285 Example: To specify the start of the label named \"the_top\" in the\n\
15286 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15287 -function fact -label the_top\".\n\
15288 \n\
15289 By default, a specified function is matched against the program's\n\
15290 functions in all scopes.  For C++, this means in all namespaces and\n\
15291 classes.  For Ada, this means in all packages.  E.g., in C++,\n\
15292 \"func()\" matches \"A::func()\", \"A::B::func()\", etc.  The\n\
15293 \"-qualified\" flag overrides this behavior, making GDB interpret the\n\
15294 specified name as a complete fully-qualified name instead.\n"
15295
15296 /* This help string is used for the break, hbreak, tbreak and thbreak
15297    commands.  It is defined as a macro to prevent duplication.
15298    COMMAND should be a string constant containing the name of the
15299    command.  */
15300
15301 #define BREAK_ARGS_HELP(command) \
15302 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15303 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15304 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15305 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15306 `-probe-dtrace' (for a DTrace probe).\n\
15307 LOCATION may be a linespec, address, or explicit location as described\n\
15308 below.\n\
15309 \n\
15310 With no LOCATION, uses current execution address of the selected\n\
15311 stack frame.  This is useful for breaking on return to a stack frame.\n\
15312 \n\
15313 THREADNUM is the number from \"info threads\".\n\
15314 CONDITION is a boolean expression.\n\
15315 \n" LOCATION_HELP_STRING "\n\
15316 Multiple breakpoints at one place are permitted, and useful if their\n\
15317 conditions are different.\n\
15318 \n\
15319 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15320
15321 /* List of subcommands for "catch".  */
15322 static struct cmd_list_element *catch_cmdlist;
15323
15324 /* List of subcommands for "tcatch".  */
15325 static struct cmd_list_element *tcatch_cmdlist;
15326
15327 void
15328 add_catch_command (const char *name, const char *docstring,
15329                    cmd_const_sfunc_ftype *sfunc,
15330                    completer_ftype *completer,
15331                    void *user_data_catch,
15332                    void *user_data_tcatch)
15333 {
15334   struct cmd_list_element *command;
15335
15336   command = add_cmd (name, class_breakpoint, docstring,
15337                      &catch_cmdlist);
15338   set_cmd_sfunc (command, sfunc);
15339   set_cmd_context (command, user_data_catch);
15340   set_cmd_completer (command, completer);
15341
15342   command = add_cmd (name, class_breakpoint, docstring,
15343                      &tcatch_cmdlist);
15344   set_cmd_sfunc (command, sfunc);
15345   set_cmd_context (command, user_data_tcatch);
15346   set_cmd_completer (command, completer);
15347 }
15348
15349 static void
15350 save_command (const char *arg, int from_tty)
15351 {
15352   printf_unfiltered (_("\"save\" must be followed by "
15353                        "the name of a save subcommand.\n"));
15354   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15355 }
15356
15357 struct breakpoint *
15358 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15359                           void *data)
15360 {
15361   struct breakpoint *b, *b_tmp;
15362
15363   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15364     {
15365       if ((*callback) (b, data))
15366         return b;
15367     }
15368
15369   return NULL;
15370 }
15371
15372 /* Zero if any of the breakpoint's locations could be a location where
15373    functions have been inlined, nonzero otherwise.  */
15374
15375 static int
15376 is_non_inline_function (struct breakpoint *b)
15377 {
15378   /* The shared library event breakpoint is set on the address of a
15379      non-inline function.  */
15380   if (b->type == bp_shlib_event)
15381     return 1;
15382
15383   return 0;
15384 }
15385
15386 /* Nonzero if the specified PC cannot be a location where functions
15387    have been inlined.  */
15388
15389 int
15390 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
15391                            const struct target_waitstatus *ws)
15392 {
15393   struct breakpoint *b;
15394   struct bp_location *bl;
15395
15396   ALL_BREAKPOINTS (b)
15397     {
15398       if (!is_non_inline_function (b))
15399         continue;
15400
15401       for (bl = b->loc; bl != NULL; bl = bl->next)
15402         {
15403           if (!bl->shlib_disabled
15404               && bpstat_check_location (bl, aspace, pc, ws))
15405             return 1;
15406         }
15407     }
15408
15409   return 0;
15410 }
15411
15412 /* Remove any references to OBJFILE which is going to be freed.  */
15413
15414 void
15415 breakpoint_free_objfile (struct objfile *objfile)
15416 {
15417   struct bp_location **locp, *loc;
15418
15419   ALL_BP_LOCATIONS (loc, locp)
15420     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15421       loc->symtab = NULL;
15422 }
15423
15424 void
15425 initialize_breakpoint_ops (void)
15426 {
15427   static int initialized = 0;
15428
15429   struct breakpoint_ops *ops;
15430
15431   if (initialized)
15432     return;
15433   initialized = 1;
15434
15435   /* The breakpoint_ops structure to be inherit by all kinds of
15436      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15437      internal and momentary breakpoints, etc.).  */
15438   ops = &bkpt_base_breakpoint_ops;
15439   *ops = base_breakpoint_ops;
15440   ops->re_set = bkpt_re_set;
15441   ops->insert_location = bkpt_insert_location;
15442   ops->remove_location = bkpt_remove_location;
15443   ops->breakpoint_hit = bkpt_breakpoint_hit;
15444   ops->create_sals_from_location = bkpt_create_sals_from_location;
15445   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15446   ops->decode_location = bkpt_decode_location;
15447
15448   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15449   ops = &bkpt_breakpoint_ops;
15450   *ops = bkpt_base_breakpoint_ops;
15451   ops->re_set = bkpt_re_set;
15452   ops->resources_needed = bkpt_resources_needed;
15453   ops->print_it = bkpt_print_it;
15454   ops->print_mention = bkpt_print_mention;
15455   ops->print_recreate = bkpt_print_recreate;
15456
15457   /* Ranged breakpoints.  */
15458   ops = &ranged_breakpoint_ops;
15459   *ops = bkpt_breakpoint_ops;
15460   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15461   ops->resources_needed = resources_needed_ranged_breakpoint;
15462   ops->print_it = print_it_ranged_breakpoint;
15463   ops->print_one = print_one_ranged_breakpoint;
15464   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15465   ops->print_mention = print_mention_ranged_breakpoint;
15466   ops->print_recreate = print_recreate_ranged_breakpoint;
15467
15468   /* Internal breakpoints.  */
15469   ops = &internal_breakpoint_ops;
15470   *ops = bkpt_base_breakpoint_ops;
15471   ops->re_set = internal_bkpt_re_set;
15472   ops->check_status = internal_bkpt_check_status;
15473   ops->print_it = internal_bkpt_print_it;
15474   ops->print_mention = internal_bkpt_print_mention;
15475
15476   /* Momentary breakpoints.  */
15477   ops = &momentary_breakpoint_ops;
15478   *ops = bkpt_base_breakpoint_ops;
15479   ops->re_set = momentary_bkpt_re_set;
15480   ops->check_status = momentary_bkpt_check_status;
15481   ops->print_it = momentary_bkpt_print_it;
15482   ops->print_mention = momentary_bkpt_print_mention;
15483
15484   /* Probe breakpoints.  */
15485   ops = &bkpt_probe_breakpoint_ops;
15486   *ops = bkpt_breakpoint_ops;
15487   ops->insert_location = bkpt_probe_insert_location;
15488   ops->remove_location = bkpt_probe_remove_location;
15489   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15490   ops->decode_location = bkpt_probe_decode_location;
15491
15492   /* Watchpoints.  */
15493   ops = &watchpoint_breakpoint_ops;
15494   *ops = base_breakpoint_ops;
15495   ops->re_set = re_set_watchpoint;
15496   ops->insert_location = insert_watchpoint;
15497   ops->remove_location = remove_watchpoint;
15498   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15499   ops->check_status = check_status_watchpoint;
15500   ops->resources_needed = resources_needed_watchpoint;
15501   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15502   ops->print_it = print_it_watchpoint;
15503   ops->print_mention = print_mention_watchpoint;
15504   ops->print_recreate = print_recreate_watchpoint;
15505   ops->explains_signal = explains_signal_watchpoint;
15506
15507   /* Masked watchpoints.  */
15508   ops = &masked_watchpoint_breakpoint_ops;
15509   *ops = watchpoint_breakpoint_ops;
15510   ops->insert_location = insert_masked_watchpoint;
15511   ops->remove_location = remove_masked_watchpoint;
15512   ops->resources_needed = resources_needed_masked_watchpoint;
15513   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15514   ops->print_it = print_it_masked_watchpoint;
15515   ops->print_one_detail = print_one_detail_masked_watchpoint;
15516   ops->print_mention = print_mention_masked_watchpoint;
15517   ops->print_recreate = print_recreate_masked_watchpoint;
15518
15519   /* Tracepoints.  */
15520   ops = &tracepoint_breakpoint_ops;
15521   *ops = base_breakpoint_ops;
15522   ops->re_set = tracepoint_re_set;
15523   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15524   ops->print_one_detail = tracepoint_print_one_detail;
15525   ops->print_mention = tracepoint_print_mention;
15526   ops->print_recreate = tracepoint_print_recreate;
15527   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15528   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15529   ops->decode_location = tracepoint_decode_location;
15530
15531   /* Probe tracepoints.  */
15532   ops = &tracepoint_probe_breakpoint_ops;
15533   *ops = tracepoint_breakpoint_ops;
15534   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15535   ops->decode_location = tracepoint_probe_decode_location;
15536
15537   /* Static tracepoints with marker (`-m').  */
15538   ops = &strace_marker_breakpoint_ops;
15539   *ops = tracepoint_breakpoint_ops;
15540   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15541   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15542   ops->decode_location = strace_marker_decode_location;
15543
15544   /* Fork catchpoints.  */
15545   ops = &catch_fork_breakpoint_ops;
15546   *ops = base_breakpoint_ops;
15547   ops->insert_location = insert_catch_fork;
15548   ops->remove_location = remove_catch_fork;
15549   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15550   ops->print_it = print_it_catch_fork;
15551   ops->print_one = print_one_catch_fork;
15552   ops->print_mention = print_mention_catch_fork;
15553   ops->print_recreate = print_recreate_catch_fork;
15554
15555   /* Vfork catchpoints.  */
15556   ops = &catch_vfork_breakpoint_ops;
15557   *ops = base_breakpoint_ops;
15558   ops->insert_location = insert_catch_vfork;
15559   ops->remove_location = remove_catch_vfork;
15560   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15561   ops->print_it = print_it_catch_vfork;
15562   ops->print_one = print_one_catch_vfork;
15563   ops->print_mention = print_mention_catch_vfork;
15564   ops->print_recreate = print_recreate_catch_vfork;
15565
15566   /* Exec catchpoints.  */
15567   ops = &catch_exec_breakpoint_ops;
15568   *ops = base_breakpoint_ops;
15569   ops->insert_location = insert_catch_exec;
15570   ops->remove_location = remove_catch_exec;
15571   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15572   ops->print_it = print_it_catch_exec;
15573   ops->print_one = print_one_catch_exec;
15574   ops->print_mention = print_mention_catch_exec;
15575   ops->print_recreate = print_recreate_catch_exec;
15576
15577   /* Solib-related catchpoints.  */
15578   ops = &catch_solib_breakpoint_ops;
15579   *ops = base_breakpoint_ops;
15580   ops->insert_location = insert_catch_solib;
15581   ops->remove_location = remove_catch_solib;
15582   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15583   ops->check_status = check_status_catch_solib;
15584   ops->print_it = print_it_catch_solib;
15585   ops->print_one = print_one_catch_solib;
15586   ops->print_mention = print_mention_catch_solib;
15587   ops->print_recreate = print_recreate_catch_solib;
15588
15589   ops = &dprintf_breakpoint_ops;
15590   *ops = bkpt_base_breakpoint_ops;
15591   ops->re_set = dprintf_re_set;
15592   ops->resources_needed = bkpt_resources_needed;
15593   ops->print_it = bkpt_print_it;
15594   ops->print_mention = bkpt_print_mention;
15595   ops->print_recreate = dprintf_print_recreate;
15596   ops->after_condition_true = dprintf_after_condition_true;
15597   ops->breakpoint_hit = dprintf_breakpoint_hit;
15598 }
15599
15600 /* Chain containing all defined "enable breakpoint" subcommands.  */
15601
15602 static struct cmd_list_element *enablebreaklist = NULL;
15603
15604 void
15605 _initialize_breakpoint (void)
15606 {
15607   struct cmd_list_element *c;
15608
15609   initialize_breakpoint_ops ();
15610
15611   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15612   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
15613   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
15614
15615   breakpoint_objfile_key
15616     = register_objfile_data_with_cleanup (NULL, free_breakpoint_objfile_data);
15617
15618   breakpoint_chain = 0;
15619   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15620      before a breakpoint is set.  */
15621   breakpoint_count = 0;
15622
15623   tracepoint_count = 0;
15624
15625   add_com ("ignore", class_breakpoint, ignore_command, _("\
15626 Set ignore-count of breakpoint number N to COUNT.\n\
15627 Usage is `ignore N COUNT'."));
15628
15629   add_com ("commands", class_breakpoint, commands_command, _("\
15630 Set commands to be executed when the given breakpoints are hit.\n\
15631 Give a space-separated breakpoint list as argument after \"commands\".\n\
15632 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
15633 (e.g. `5-7').\n\
15634 With no argument, the targeted breakpoint is the last one set.\n\
15635 The commands themselves follow starting on the next line.\n\
15636 Type a line containing \"end\" to indicate the end of them.\n\
15637 Give \"silent\" as the first line to make the breakpoint silent;\n\
15638 then no output is printed when it is hit, except what the commands print."));
15639
15640   c = add_com ("condition", class_breakpoint, condition_command, _("\
15641 Specify breakpoint number N to break only if COND is true.\n\
15642 Usage is `condition N COND', where N is an integer and COND is an\n\
15643 expression to be evaluated whenever breakpoint N is reached."));
15644   set_cmd_completer (c, condition_completer);
15645
15646   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15647 Set a temporary breakpoint.\n\
15648 Like \"break\" except the breakpoint is only temporary,\n\
15649 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15650 by using \"enable delete\" on the breakpoint number.\n\
15651 \n"
15652 BREAK_ARGS_HELP ("tbreak")));
15653   set_cmd_completer (c, location_completer);
15654
15655   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15656 Set a hardware assisted breakpoint.\n\
15657 Like \"break\" except the breakpoint requires hardware support,\n\
15658 some target hardware may not have this support.\n\
15659 \n"
15660 BREAK_ARGS_HELP ("hbreak")));
15661   set_cmd_completer (c, location_completer);
15662
15663   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15664 Set a temporary hardware assisted breakpoint.\n\
15665 Like \"hbreak\" except the breakpoint is only temporary,\n\
15666 so it will be deleted when hit.\n\
15667 \n"
15668 BREAK_ARGS_HELP ("thbreak")));
15669   set_cmd_completer (c, location_completer);
15670
15671   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15672 Enable some breakpoints.\n\
15673 Give breakpoint numbers (separated by spaces) as arguments.\n\
15674 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15675 This is used to cancel the effect of the \"disable\" command.\n\
15676 With a subcommand you can enable temporarily."),
15677                   &enablelist, "enable ", 1, &cmdlist);
15678
15679   add_com_alias ("en", "enable", class_breakpoint, 1);
15680
15681   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15682 Enable some breakpoints.\n\
15683 Give breakpoint numbers (separated by spaces) as arguments.\n\
15684 This is used to cancel the effect of the \"disable\" command.\n\
15685 May be abbreviated to simply \"enable\".\n"),
15686                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15687
15688   add_cmd ("once", no_class, enable_once_command, _("\
15689 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15690 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15691            &enablebreaklist);
15692
15693   add_cmd ("delete", no_class, enable_delete_command, _("\
15694 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15695 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15696            &enablebreaklist);
15697
15698   add_cmd ("count", no_class, enable_count_command, _("\
15699 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15700 If a breakpoint is hit while enabled in this fashion,\n\
15701 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15702            &enablebreaklist);
15703
15704   add_cmd ("delete", no_class, enable_delete_command, _("\
15705 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15706 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15707            &enablelist);
15708
15709   add_cmd ("once", no_class, enable_once_command, _("\
15710 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15711 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15712            &enablelist);
15713
15714   add_cmd ("count", no_class, enable_count_command, _("\
15715 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15716 If a breakpoint is hit while enabled in this fashion,\n\
15717 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15718            &enablelist);
15719
15720   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15721 Disable some breakpoints.\n\
15722 Arguments are breakpoint numbers with spaces in between.\n\
15723 To disable all breakpoints, give no argument.\n\
15724 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15725                   &disablelist, "disable ", 1, &cmdlist);
15726   add_com_alias ("dis", "disable", class_breakpoint, 1);
15727   add_com_alias ("disa", "disable", class_breakpoint, 1);
15728
15729   add_cmd ("breakpoints", class_alias, disable_command, _("\
15730 Disable some breakpoints.\n\
15731 Arguments are breakpoint numbers with spaces in between.\n\
15732 To disable all breakpoints, give no argument.\n\
15733 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15734 This command may be abbreviated \"disable\"."),
15735            &disablelist);
15736
15737   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15738 Delete some breakpoints or auto-display expressions.\n\
15739 Arguments are breakpoint numbers with spaces in between.\n\
15740 To delete all breakpoints, give no argument.\n\
15741 \n\
15742 Also a prefix command for deletion of other GDB objects.\n\
15743 The \"unset\" command is also an alias for \"delete\"."),
15744                   &deletelist, "delete ", 1, &cmdlist);
15745   add_com_alias ("d", "delete", class_breakpoint, 1);
15746   add_com_alias ("del", "delete", class_breakpoint, 1);
15747
15748   add_cmd ("breakpoints", class_alias, delete_command, _("\
15749 Delete some breakpoints or auto-display expressions.\n\
15750 Arguments are breakpoint numbers with spaces in between.\n\
15751 To delete all breakpoints, give no argument.\n\
15752 This command may be abbreviated \"delete\"."),
15753            &deletelist);
15754
15755   add_com ("clear", class_breakpoint, clear_command, _("\
15756 Clear breakpoint at specified location.\n\
15757 Argument may be a linespec, explicit, or address location as described below.\n\
15758 \n\
15759 With no argument, clears all breakpoints in the line that the selected frame\n\
15760 is executing in.\n"
15761 "\n" LOCATION_HELP_STRING "\n\
15762 See also the \"delete\" command which clears breakpoints by number."));
15763   add_com_alias ("cl", "clear", class_breakpoint, 1);
15764
15765   c = add_com ("break", class_breakpoint, break_command, _("\
15766 Set breakpoint at specified location.\n"
15767 BREAK_ARGS_HELP ("break")));
15768   set_cmd_completer (c, location_completer);
15769
15770   add_com_alias ("b", "break", class_run, 1);
15771   add_com_alias ("br", "break", class_run, 1);
15772   add_com_alias ("bre", "break", class_run, 1);
15773   add_com_alias ("brea", "break", class_run, 1);
15774
15775   if (dbx_commands)
15776     {
15777       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15778 Break in function/address or break at a line in the current file."),
15779                              &stoplist, "stop ", 1, &cmdlist);
15780       add_cmd ("in", class_breakpoint, stopin_command,
15781                _("Break in function or address."), &stoplist);
15782       add_cmd ("at", class_breakpoint, stopat_command,
15783                _("Break at a line in the current file."), &stoplist);
15784       add_com ("status", class_info, info_breakpoints_command, _("\
15785 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15786 The \"Type\" column indicates one of:\n\
15787 \tbreakpoint     - normal breakpoint\n\
15788 \twatchpoint     - watchpoint\n\
15789 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15790 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15791 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15792 address and file/line number respectively.\n\
15793 \n\
15794 Convenience variable \"$_\" and default examine address for \"x\"\n\
15795 are set to the address of the last breakpoint listed unless the command\n\
15796 is prefixed with \"server \".\n\n\
15797 Convenience variable \"$bpnum\" contains the number of the last\n\
15798 breakpoint set."));
15799     }
15800
15801   add_info ("breakpoints", info_breakpoints_command, _("\
15802 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15803 The \"Type\" column indicates one of:\n\
15804 \tbreakpoint     - normal breakpoint\n\
15805 \twatchpoint     - watchpoint\n\
15806 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15807 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15808 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15809 address and file/line number respectively.\n\
15810 \n\
15811 Convenience variable \"$_\" and default examine address for \"x\"\n\
15812 are set to the address of the last breakpoint listed unless the command\n\
15813 is prefixed with \"server \".\n\n\
15814 Convenience variable \"$bpnum\" contains the number of the last\n\
15815 breakpoint set."));
15816
15817   add_info_alias ("b", "breakpoints", 1);
15818
15819   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15820 Status of all breakpoints, or breakpoint number NUMBER.\n\
15821 The \"Type\" column indicates one of:\n\
15822 \tbreakpoint     - normal breakpoint\n\
15823 \twatchpoint     - watchpoint\n\
15824 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15825 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15826 \tuntil          - internal breakpoint used by the \"until\" command\n\
15827 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15828 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15829 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15830 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15831 address and file/line number respectively.\n\
15832 \n\
15833 Convenience variable \"$_\" and default examine address for \"x\"\n\
15834 are set to the address of the last breakpoint listed unless the command\n\
15835 is prefixed with \"server \".\n\n\
15836 Convenience variable \"$bpnum\" contains the number of the last\n\
15837 breakpoint set."),
15838            &maintenanceinfolist);
15839
15840   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15841 Set catchpoints to catch events."),
15842                   &catch_cmdlist, "catch ",
15843                   0/*allow-unknown*/, &cmdlist);
15844
15845   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15846 Set temporary catchpoints to catch events."),
15847                   &tcatch_cmdlist, "tcatch ",
15848                   0/*allow-unknown*/, &cmdlist);
15849
15850   add_catch_command ("fork", _("Catch calls to fork."),
15851                      catch_fork_command_1,
15852                      NULL,
15853                      (void *) (uintptr_t) catch_fork_permanent,
15854                      (void *) (uintptr_t) catch_fork_temporary);
15855   add_catch_command ("vfork", _("Catch calls to vfork."),
15856                      catch_fork_command_1,
15857                      NULL,
15858                      (void *) (uintptr_t) catch_vfork_permanent,
15859                      (void *) (uintptr_t) catch_vfork_temporary);
15860   add_catch_command ("exec", _("Catch calls to exec."),
15861                      catch_exec_command_1,
15862                      NULL,
15863                      CATCH_PERMANENT,
15864                      CATCH_TEMPORARY);
15865   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15866 Usage: catch load [REGEX]\n\
15867 If REGEX is given, only stop for libraries matching the regular expression."),
15868                      catch_load_command_1,
15869                      NULL,
15870                      CATCH_PERMANENT,
15871                      CATCH_TEMPORARY);
15872   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15873 Usage: catch unload [REGEX]\n\
15874 If REGEX is given, only stop for libraries matching the regular expression."),
15875                      catch_unload_command_1,
15876                      NULL,
15877                      CATCH_PERMANENT,
15878                      CATCH_TEMPORARY);
15879
15880   c = add_com ("watch", class_breakpoint, watch_command, _("\
15881 Set a watchpoint for an expression.\n\
15882 Usage: watch [-l|-location] EXPRESSION\n\
15883 A watchpoint stops execution of your program whenever the value of\n\
15884 an expression changes.\n\
15885 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15886 the memory to which it refers."));
15887   set_cmd_completer (c, expression_completer);
15888
15889   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15890 Set a read watchpoint for an expression.\n\
15891 Usage: rwatch [-l|-location] EXPRESSION\n\
15892 A watchpoint stops execution of your program whenever the value of\n\
15893 an expression is read.\n\
15894 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15895 the memory to which it refers."));
15896   set_cmd_completer (c, expression_completer);
15897
15898   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15899 Set a watchpoint for an expression.\n\
15900 Usage: awatch [-l|-location] EXPRESSION\n\
15901 A watchpoint stops execution of your program whenever the value of\n\
15902 an expression is either read or written.\n\
15903 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15904 the memory to which it refers."));
15905   set_cmd_completer (c, expression_completer);
15906
15907   add_info ("watchpoints", info_watchpoints_command, _("\
15908 Status of specified watchpoints (all watchpoints if no argument)."));
15909
15910   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15911      respond to changes - contrary to the description.  */
15912   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15913                             &can_use_hw_watchpoints, _("\
15914 Set debugger's willingness to use watchpoint hardware."), _("\
15915 Show debugger's willingness to use watchpoint hardware."), _("\
15916 If zero, gdb will not use hardware for new watchpoints, even if\n\
15917 such is available.  (However, any hardware watchpoints that were\n\
15918 created before setting this to nonzero, will continue to use watchpoint\n\
15919 hardware.)"),
15920                             NULL,
15921                             show_can_use_hw_watchpoints,
15922                             &setlist, &showlist);
15923
15924   can_use_hw_watchpoints = 1;
15925
15926   /* Tracepoint manipulation commands.  */
15927
15928   c = add_com ("trace", class_breakpoint, trace_command, _("\
15929 Set a tracepoint at specified location.\n\
15930 \n"
15931 BREAK_ARGS_HELP ("trace") "\n\
15932 Do \"help tracepoints\" for info on other tracepoint commands."));
15933   set_cmd_completer (c, location_completer);
15934
15935   add_com_alias ("tp", "trace", class_alias, 0);
15936   add_com_alias ("tr", "trace", class_alias, 1);
15937   add_com_alias ("tra", "trace", class_alias, 1);
15938   add_com_alias ("trac", "trace", class_alias, 1);
15939
15940   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15941 Set a fast tracepoint at specified location.\n\
15942 \n"
15943 BREAK_ARGS_HELP ("ftrace") "\n\
15944 Do \"help tracepoints\" for info on other tracepoint commands."));
15945   set_cmd_completer (c, location_completer);
15946
15947   c = add_com ("strace", class_breakpoint, strace_command, _("\
15948 Set a static tracepoint at location or marker.\n\
15949 \n\
15950 strace [LOCATION] [if CONDITION]\n\
15951 LOCATION may be a linespec, explicit, or address location (described below) \n\
15952 or -m MARKER_ID.\n\n\
15953 If a marker id is specified, probe the marker with that name.  With\n\
15954 no LOCATION, uses current execution address of the selected stack frame.\n\
15955 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15956 This collects arbitrary user data passed in the probe point call to the\n\
15957 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15958 by printing the $_sdata variable like any other convenience variable.\n\
15959 \n\
15960 CONDITION is a boolean expression.\n\
15961 \n" LOCATION_HELP_STRING "\n\
15962 Multiple tracepoints at one place are permitted, and useful if their\n\
15963 conditions are different.\n\
15964 \n\
15965 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15966 Do \"help tracepoints\" for info on other tracepoint commands."));
15967   set_cmd_completer (c, location_completer);
15968
15969   add_info ("tracepoints", info_tracepoints_command, _("\
15970 Status of specified tracepoints (all tracepoints if no argument).\n\
15971 Convenience variable \"$tpnum\" contains the number of the\n\
15972 last tracepoint set."));
15973
15974   add_info_alias ("tp", "tracepoints", 1);
15975
15976   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15977 Delete specified tracepoints.\n\
15978 Arguments are tracepoint numbers, separated by spaces.\n\
15979 No argument means delete all tracepoints."),
15980            &deletelist);
15981   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
15982
15983   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15984 Disable specified tracepoints.\n\
15985 Arguments are tracepoint numbers, separated by spaces.\n\
15986 No argument means disable all tracepoints."),
15987            &disablelist);
15988   deprecate_cmd (c, "disable");
15989
15990   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15991 Enable specified tracepoints.\n\
15992 Arguments are tracepoint numbers, separated by spaces.\n\
15993 No argument means enable all tracepoints."),
15994            &enablelist);
15995   deprecate_cmd (c, "enable");
15996
15997   add_com ("passcount", class_trace, trace_pass_command, _("\
15998 Set the passcount for a tracepoint.\n\
15999 The trace will end when the tracepoint has been passed 'count' times.\n\
16000 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16001 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16002
16003   add_prefix_cmd ("save", class_breakpoint, save_command,
16004                   _("Save breakpoint definitions as a script."),
16005                   &save_cmdlist, "save ",
16006                   0/*allow-unknown*/, &cmdlist);
16007
16008   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16009 Save current breakpoint definitions as a script.\n\
16010 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16011 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16012 session to restore them."),
16013                &save_cmdlist);
16014   set_cmd_completer (c, filename_completer);
16015
16016   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16017 Save current tracepoint definitions as a script.\n\
16018 Use the 'source' command in another debug session to restore them."),
16019                &save_cmdlist);
16020   set_cmd_completer (c, filename_completer);
16021
16022   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16023   deprecate_cmd (c, "save tracepoints");
16024
16025   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16026 Breakpoint specific settings\n\
16027 Configure various breakpoint-specific variables such as\n\
16028 pending breakpoint behavior"),
16029                   &breakpoint_set_cmdlist, "set breakpoint ",
16030                   0/*allow-unknown*/, &setlist);
16031   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16032 Breakpoint specific settings\n\
16033 Configure various breakpoint-specific variables such as\n\
16034 pending breakpoint behavior"),
16035                   &breakpoint_show_cmdlist, "show breakpoint ",
16036                   0/*allow-unknown*/, &showlist);
16037
16038   add_setshow_auto_boolean_cmd ("pending", no_class,
16039                                 &pending_break_support, _("\
16040 Set debugger's behavior regarding pending breakpoints."), _("\
16041 Show debugger's behavior regarding pending breakpoints."), _("\
16042 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16043 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16044 an error.  If auto, an unrecognized breakpoint location results in a\n\
16045 user-query to see if a pending breakpoint should be created."),
16046                                 NULL,
16047                                 show_pending_break_support,
16048                                 &breakpoint_set_cmdlist,
16049                                 &breakpoint_show_cmdlist);
16050
16051   pending_break_support = AUTO_BOOLEAN_AUTO;
16052
16053   add_setshow_boolean_cmd ("auto-hw", no_class,
16054                            &automatic_hardware_breakpoints, _("\
16055 Set automatic usage of hardware breakpoints."), _("\
16056 Show automatic usage of hardware breakpoints."), _("\
16057 If set, the debugger will automatically use hardware breakpoints for\n\
16058 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16059 a warning will be emitted for such breakpoints."),
16060                            NULL,
16061                            show_automatic_hardware_breakpoints,
16062                            &breakpoint_set_cmdlist,
16063                            &breakpoint_show_cmdlist);
16064
16065   add_setshow_boolean_cmd ("always-inserted", class_support,
16066                            &always_inserted_mode, _("\
16067 Set mode for inserting breakpoints."), _("\
16068 Show mode for inserting breakpoints."), _("\
16069 When this mode is on, breakpoints are inserted immediately as soon as\n\
16070 they're created, kept inserted even when execution stops, and removed\n\
16071 only when the user deletes them.  When this mode is off (the default),\n\
16072 breakpoints are inserted only when execution continues, and removed\n\
16073 when execution stops."),
16074                                 NULL,
16075                                 &show_always_inserted_mode,
16076                                 &breakpoint_set_cmdlist,
16077                                 &breakpoint_show_cmdlist);
16078
16079   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16080                         condition_evaluation_enums,
16081                         &condition_evaluation_mode_1, _("\
16082 Set mode of breakpoint condition evaluation."), _("\
16083 Show mode of breakpoint condition evaluation."), _("\
16084 When this is set to \"host\", breakpoint conditions will be\n\
16085 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16086 breakpoint conditions will be downloaded to the target (if the target\n\
16087 supports such feature) and conditions will be evaluated on the target's side.\n\
16088 If this is set to \"auto\" (default), this will be automatically set to\n\
16089 \"target\" if it supports condition evaluation, otherwise it will\n\
16090 be set to \"gdb\""),
16091                            &set_condition_evaluation_mode,
16092                            &show_condition_evaluation_mode,
16093                            &breakpoint_set_cmdlist,
16094                            &breakpoint_show_cmdlist);
16095
16096   add_com ("break-range", class_breakpoint, break_range_command, _("\
16097 Set a breakpoint for an address range.\n\
16098 break-range START-LOCATION, END-LOCATION\n\
16099 where START-LOCATION and END-LOCATION can be one of the following:\n\
16100   LINENUM, for that line in the current file,\n\
16101   FILE:LINENUM, for that line in that file,\n\
16102   +OFFSET, for that number of lines after the current line\n\
16103            or the start of the range\n\
16104   FUNCTION, for the first line in that function,\n\
16105   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16106   *ADDRESS, for the instruction at that address.\n\
16107 \n\
16108 The breakpoint will stop execution of the inferior whenever it executes\n\
16109 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16110 range (including START-LOCATION and END-LOCATION)."));
16111
16112   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16113 Set a dynamic printf at specified location.\n\
16114 dprintf location,format string,arg1,arg2,...\n\
16115 location may be a linespec, explicit, or address location.\n"
16116 "\n" LOCATION_HELP_STRING));
16117   set_cmd_completer (c, location_completer);
16118
16119   add_setshow_enum_cmd ("dprintf-style", class_support,
16120                         dprintf_style_enums, &dprintf_style, _("\
16121 Set the style of usage for dynamic printf."), _("\
16122 Show the style of usage for dynamic printf."), _("\
16123 This setting chooses how GDB will do a dynamic printf.\n\
16124 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16125 console, as with the \"printf\" command.\n\
16126 If the value is \"call\", the print is done by calling a function in your\n\
16127 program; by default printf(), but you can choose a different function or\n\
16128 output stream by setting dprintf-function and dprintf-channel."),
16129                         update_dprintf_commands, NULL,
16130                         &setlist, &showlist);
16131
16132   dprintf_function = xstrdup ("printf");
16133   add_setshow_string_cmd ("dprintf-function", class_support,
16134                           &dprintf_function, _("\
16135 Set the function to use for dynamic printf"), _("\
16136 Show the function to use for dynamic printf"), NULL,
16137                           update_dprintf_commands, NULL,
16138                           &setlist, &showlist);
16139
16140   dprintf_channel = xstrdup ("");
16141   add_setshow_string_cmd ("dprintf-channel", class_support,
16142                           &dprintf_channel, _("\
16143 Set the channel to use for dynamic printf"), _("\
16144 Show the channel to use for dynamic printf"), NULL,
16145                           update_dprintf_commands, NULL,
16146                           &setlist, &showlist);
16147
16148   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16149                            &disconnected_dprintf, _("\
16150 Set whether dprintf continues after GDB disconnects."), _("\
16151 Show whether dprintf continues after GDB disconnects."), _("\
16152 Use this to let dprintf commands continue to hit and produce output\n\
16153 even if GDB disconnects or detaches from the target."),
16154                            NULL,
16155                            NULL,
16156                            &setlist, &showlist);
16157
16158   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16159 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16160 (target agent only) This is useful for formatted output in user-defined commands."));
16161
16162   automatic_hardware_breakpoints = 1;
16163
16164   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16165   observer_attach_thread_exit (remove_threaded_breakpoints);
16166 }