b48c405b08491a80008498e9e19d193abc8b0907
[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       VEC (char_ptr) *result = NULL;
925
926       if (text[0] == '$')
927         {
928           /* We don't support completion of history indices.  */
929           if (!isdigit (text[1]))
930             complete_internalvar (tracker, &text[1]);
931           return;
932         }
933
934       /* We're completing the breakpoint number.  */
935       len = strlen (text);
936
937       ALL_BREAKPOINTS (b)
938         {
939           char number[50];
940
941           xsnprintf (number, sizeof (number), "%d", b->number);
942
943           if (strncmp (number, text, len) == 0)
944             {
945               gdb::unique_xmalloc_ptr<char> copy (xstrdup (number));
946               tracker.add_completion (std::move (copy));
947             }
948         }
949
950       return;
951     }
952
953   /* We're completing the expression part.  */
954   text = skip_spaces (space);
955   expression_completer (cmd, tracker, text, word);
956 }
957
958 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
959
960 static void
961 condition_command (const char *arg, int from_tty)
962 {
963   struct breakpoint *b;
964   const char *p;
965   int bnum;
966
967   if (arg == 0)
968     error_no_arg (_("breakpoint number"));
969
970   p = arg;
971   bnum = get_number (&p);
972   if (bnum == 0)
973     error (_("Bad breakpoint argument: '%s'"), arg);
974
975   ALL_BREAKPOINTS (b)
976     if (b->number == bnum)
977       {
978         /* Check if this breakpoint has a "stop" method implemented in an
979            extension language.  This method and conditions entered into GDB
980            from the CLI are mutually exclusive.  */
981         const struct extension_language_defn *extlang
982           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
983
984         if (extlang != NULL)
985           {
986             error (_("Only one stop condition allowed.  There is currently"
987                      " a %s stop condition defined for this breakpoint."),
988                    ext_lang_capitalized_name (extlang));
989           }
990         set_breakpoint_condition (b, p, from_tty);
991
992         if (is_breakpoint (b))
993           update_global_location_list (UGLL_MAY_INSERT);
994
995         return;
996       }
997
998   error (_("No breakpoint number %d."), bnum);
999 }
1000
1001 /* Check that COMMAND do not contain commands that are suitable
1002    only for tracepoints and not suitable for ordinary breakpoints.
1003    Throw if any such commands is found.  */
1004
1005 static void
1006 check_no_tracepoint_commands (struct command_line *commands)
1007 {
1008   struct command_line *c;
1009
1010   for (c = commands; c; c = c->next)
1011     {
1012       int i;
1013
1014       if (c->control_type == while_stepping_control)
1015         error (_("The 'while-stepping' command can "
1016                  "only be used for tracepoints"));
1017
1018       for (i = 0; i < c->body_count; ++i)
1019         check_no_tracepoint_commands ((c->body_list)[i]);
1020
1021       /* Not that command parsing removes leading whitespace and comment
1022          lines and also empty lines.  So, we only need to check for
1023          command directly.  */
1024       if (strstr (c->line, "collect ") == c->line)
1025         error (_("The 'collect' command can only be used for tracepoints"));
1026
1027       if (strstr (c->line, "teval ") == c->line)
1028         error (_("The 'teval' command can only be used for tracepoints"));
1029     }
1030 }
1031
1032 struct longjmp_breakpoint : public breakpoint
1033 {
1034   ~longjmp_breakpoint () override;
1035 };
1036
1037 /* Encapsulate tests for different types of tracepoints.  */
1038
1039 static bool
1040 is_tracepoint_type (bptype type)
1041 {
1042   return (type == bp_tracepoint
1043           || type == bp_fast_tracepoint
1044           || type == bp_static_tracepoint);
1045 }
1046
1047 static bool
1048 is_longjmp_type (bptype type)
1049 {
1050   return type == bp_longjmp || type == bp_exception;
1051 }
1052
1053 int
1054 is_tracepoint (const struct breakpoint *b)
1055 {
1056   return is_tracepoint_type (b->type);
1057 }
1058
1059 /* Factory function to create an appropriate instance of breakpoint given
1060    TYPE.  */
1061
1062 static std::unique_ptr<breakpoint>
1063 new_breakpoint_from_type (bptype type)
1064 {
1065   breakpoint *b;
1066
1067   if (is_tracepoint_type (type))
1068     b = new tracepoint ();
1069   else if (is_longjmp_type (type))
1070     b = new longjmp_breakpoint ();
1071   else
1072     b = new breakpoint ();
1073
1074   return std::unique_ptr<breakpoint> (b);
1075 }
1076
1077 /* A helper function that validates that COMMANDS are valid for a
1078    breakpoint.  This function will throw an exception if a problem is
1079    found.  */
1080
1081 static void
1082 validate_commands_for_breakpoint (struct breakpoint *b,
1083                                   struct command_line *commands)
1084 {
1085   if (is_tracepoint (b))
1086     {
1087       struct tracepoint *t = (struct tracepoint *) b;
1088       struct command_line *c;
1089       struct command_line *while_stepping = 0;
1090
1091       /* Reset the while-stepping step count.  The previous commands
1092          might have included a while-stepping action, while the new
1093          ones might not.  */
1094       t->step_count = 0;
1095
1096       /* We need to verify that each top-level element of commands is
1097          valid for tracepoints, that there's at most one
1098          while-stepping element, and that the while-stepping's body
1099          has valid tracing commands excluding nested while-stepping.
1100          We also need to validate the tracepoint action line in the
1101          context of the tracepoint --- validate_actionline actually
1102          has side effects, like setting the tracepoint's
1103          while-stepping STEP_COUNT, in addition to checking if the
1104          collect/teval actions parse and make sense in the
1105          tracepoint's context.  */
1106       for (c = commands; c; c = c->next)
1107         {
1108           if (c->control_type == while_stepping_control)
1109             {
1110               if (b->type == bp_fast_tracepoint)
1111                 error (_("The 'while-stepping' command "
1112                          "cannot be used for fast tracepoint"));
1113               else if (b->type == bp_static_tracepoint)
1114                 error (_("The 'while-stepping' command "
1115                          "cannot be used for static tracepoint"));
1116
1117               if (while_stepping)
1118                 error (_("The 'while-stepping' command "
1119                          "can be used only once"));
1120               else
1121                 while_stepping = c;
1122             }
1123
1124           validate_actionline (c->line, b);
1125         }
1126       if (while_stepping)
1127         {
1128           struct command_line *c2;
1129
1130           gdb_assert (while_stepping->body_count == 1);
1131           c2 = while_stepping->body_list[0];
1132           for (; c2; c2 = c2->next)
1133             {
1134               if (c2->control_type == while_stepping_control)
1135                 error (_("The 'while-stepping' command cannot be nested"));
1136             }
1137         }
1138     }
1139   else
1140     {
1141       check_no_tracepoint_commands (commands);
1142     }
1143 }
1144
1145 /* Return a vector of all the static tracepoints set at ADDR.  The
1146    caller is responsible for releasing the vector.  */
1147
1148 VEC(breakpoint_p) *
1149 static_tracepoints_here (CORE_ADDR addr)
1150 {
1151   struct breakpoint *b;
1152   VEC(breakpoint_p) *found = 0;
1153   struct bp_location *loc;
1154
1155   ALL_BREAKPOINTS (b)
1156     if (b->type == bp_static_tracepoint)
1157       {
1158         for (loc = b->loc; loc; loc = loc->next)
1159           if (loc->address == addr)
1160             VEC_safe_push(breakpoint_p, found, b);
1161       }
1162
1163   return found;
1164 }
1165
1166 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1167    validate that only allowed commands are included.  */
1168
1169 void
1170 breakpoint_set_commands (struct breakpoint *b, 
1171                          command_line_up &&commands)
1172 {
1173   validate_commands_for_breakpoint (b, commands.get ());
1174
1175   b->commands = std::move (commands);
1176   observer_notify_breakpoint_modified (b);
1177 }
1178
1179 /* Set the internal `silent' flag on the breakpoint.  Note that this
1180    is not the same as the "silent" that may appear in the breakpoint's
1181    commands.  */
1182
1183 void
1184 breakpoint_set_silent (struct breakpoint *b, int silent)
1185 {
1186   int old_silent = b->silent;
1187
1188   b->silent = silent;
1189   if (old_silent != silent)
1190     observer_notify_breakpoint_modified (b);
1191 }
1192
1193 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1194    breakpoint work for any thread.  */
1195
1196 void
1197 breakpoint_set_thread (struct breakpoint *b, int thread)
1198 {
1199   int old_thread = b->thread;
1200
1201   b->thread = thread;
1202   if (old_thread != thread)
1203     observer_notify_breakpoint_modified (b);
1204 }
1205
1206 /* Set the task for this breakpoint.  If TASK is 0, make the
1207    breakpoint work for any task.  */
1208
1209 void
1210 breakpoint_set_task (struct breakpoint *b, int task)
1211 {
1212   int old_task = b->task;
1213
1214   b->task = task;
1215   if (old_task != task)
1216     observer_notify_breakpoint_modified (b);
1217 }
1218
1219 void
1220 check_tracepoint_command (char *line, void *closure)
1221 {
1222   struct breakpoint *b = (struct breakpoint *) closure;
1223
1224   validate_actionline (line, b);
1225 }
1226
1227 static void
1228 commands_command_1 (const char *arg, int from_tty,
1229                     struct command_line *control)
1230 {
1231   counted_command_line cmd;
1232
1233   std::string new_arg;
1234
1235   if (arg == NULL || !*arg)
1236     {
1237       if (breakpoint_count - prev_breakpoint_count > 1)
1238         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1239                                  breakpoint_count);
1240       else if (breakpoint_count > 0)
1241         new_arg = string_printf ("%d", breakpoint_count);
1242       arg = new_arg.c_str ();
1243     }
1244
1245   map_breakpoint_numbers
1246     (arg, [&] (breakpoint *b)
1247      {
1248        if (cmd == NULL)
1249          {
1250            if (control != NULL)
1251              cmd = copy_command_lines (control->body_list[0]);
1252            else
1253              {
1254                std::string str
1255                  = string_printf (_("Type commands for breakpoint(s) "
1256                                     "%s, one per line."),
1257                                   arg);
1258
1259                cmd = read_command_lines (&str[0],
1260                                          from_tty, 1,
1261                                          (is_tracepoint (b)
1262                                           ? check_tracepoint_command : 0),
1263                                          b);
1264              }
1265          }
1266
1267        /* If a breakpoint was on the list more than once, we don't need to
1268           do anything.  */
1269        if (b->commands != cmd)
1270          {
1271            validate_commands_for_breakpoint (b, cmd.get ());
1272            b->commands = cmd;
1273            observer_notify_breakpoint_modified (b);
1274          }
1275      });
1276
1277   if (cmd == NULL)
1278     error (_("No breakpoints specified."));
1279 }
1280
1281 static void
1282 commands_command (const char *arg, int from_tty)
1283 {
1284   commands_command_1 (arg, from_tty, NULL);
1285 }
1286
1287 /* Like commands_command, but instead of reading the commands from
1288    input stream, takes them from an already parsed command structure.
1289
1290    This is used by cli-script.c to DTRT with breakpoint commands
1291    that are part of if and while bodies.  */
1292 enum command_control_type
1293 commands_from_control_command (const char *arg, struct command_line *cmd)
1294 {
1295   commands_command_1 (arg, 0, cmd);
1296   return simple_control;
1297 }
1298
1299 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1300
1301 static int
1302 bp_location_has_shadow (struct bp_location *bl)
1303 {
1304   if (bl->loc_type != bp_loc_software_breakpoint)
1305     return 0;
1306   if (!bl->inserted)
1307     return 0;
1308   if (bl->target_info.shadow_len == 0)
1309     /* BL isn't valid, or doesn't shadow memory.  */
1310     return 0;
1311   return 1;
1312 }
1313
1314 /* Update BUF, which is LEN bytes read from the target address
1315    MEMADDR, by replacing a memory breakpoint with its shadowed
1316    contents.
1317
1318    If READBUF is not NULL, this buffer must not overlap with the of
1319    the breakpoint location's shadow_contents buffer.  Otherwise, a
1320    failed assertion internal error will be raised.  */
1321
1322 static void
1323 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1324                             const gdb_byte *writebuf_org,
1325                             ULONGEST memaddr, LONGEST len,
1326                             struct bp_target_info *target_info,
1327                             struct gdbarch *gdbarch)
1328 {
1329   /* Now do full processing of the found relevant range of elements.  */
1330   CORE_ADDR bp_addr = 0;
1331   int bp_size = 0;
1332   int bptoffset = 0;
1333
1334   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1335                                  current_program_space->aspace, 0))
1336     {
1337       /* The breakpoint is inserted in a different address space.  */
1338       return;
1339     }
1340
1341   /* Addresses and length of the part of the breakpoint that
1342      we need to copy.  */
1343   bp_addr = target_info->placed_address;
1344   bp_size = target_info->shadow_len;
1345
1346   if (bp_addr + bp_size <= memaddr)
1347     {
1348       /* The breakpoint is entirely before the chunk of memory we are
1349          reading.  */
1350       return;
1351     }
1352
1353   if (bp_addr >= memaddr + len)
1354     {
1355       /* The breakpoint is entirely after the chunk of memory we are
1356          reading.  */
1357       return;
1358     }
1359
1360   /* Offset within shadow_contents.  */
1361   if (bp_addr < memaddr)
1362     {
1363       /* Only copy the second part of the breakpoint.  */
1364       bp_size -= memaddr - bp_addr;
1365       bptoffset = memaddr - bp_addr;
1366       bp_addr = memaddr;
1367     }
1368
1369   if (bp_addr + bp_size > memaddr + len)
1370     {
1371       /* Only copy the first part of the breakpoint.  */
1372       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1373     }
1374
1375   if (readbuf != NULL)
1376     {
1377       /* Verify that the readbuf buffer does not overlap with the
1378          shadow_contents buffer.  */
1379       gdb_assert (target_info->shadow_contents >= readbuf + len
1380                   || readbuf >= (target_info->shadow_contents
1381                                  + target_info->shadow_len));
1382
1383       /* Update the read buffer with this inserted breakpoint's
1384          shadow.  */
1385       memcpy (readbuf + bp_addr - memaddr,
1386               target_info->shadow_contents + bptoffset, bp_size);
1387     }
1388   else
1389     {
1390       const unsigned char *bp;
1391       CORE_ADDR addr = target_info->reqstd_address;
1392       int placed_size;
1393
1394       /* Update the shadow with what we want to write to memory.  */
1395       memcpy (target_info->shadow_contents + bptoffset,
1396               writebuf_org + bp_addr - memaddr, bp_size);
1397
1398       /* Determine appropriate breakpoint contents and size for this
1399          address.  */
1400       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1401
1402       /* Update the final write buffer with this inserted
1403          breakpoint's INSN.  */
1404       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1405     }
1406 }
1407
1408 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1409    by replacing any memory breakpoints with their shadowed contents.
1410
1411    If READBUF is not NULL, this buffer must not overlap with any of
1412    the breakpoint location's shadow_contents buffers.  Otherwise,
1413    a failed assertion internal error will be raised.
1414
1415    The range of shadowed area by each bp_location is:
1416      bl->address - bp_locations_placed_address_before_address_max
1417      up to bl->address + bp_locations_shadow_len_after_address_max
1418    The range we were requested to resolve shadows for is:
1419      memaddr ... memaddr + len
1420    Thus the safe cutoff boundaries for performance optimization are
1421      memaddr + len <= (bl->address
1422                        - bp_locations_placed_address_before_address_max)
1423    and:
1424      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1425
1426 void
1427 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1428                         const gdb_byte *writebuf_org,
1429                         ULONGEST memaddr, LONGEST len)
1430 {
1431   /* Left boundary, right boundary and median element of our binary
1432      search.  */
1433   unsigned bc_l, bc_r, bc;
1434
1435   /* Find BC_L which is a leftmost element which may affect BUF
1436      content.  It is safe to report lower value but a failure to
1437      report higher one.  */
1438
1439   bc_l = 0;
1440   bc_r = bp_locations_count;
1441   while (bc_l + 1 < bc_r)
1442     {
1443       struct bp_location *bl;
1444
1445       bc = (bc_l + bc_r) / 2;
1446       bl = bp_locations[bc];
1447
1448       /* Check first BL->ADDRESS will not overflow due to the added
1449          constant.  Then advance the left boundary only if we are sure
1450          the BC element can in no way affect the BUF content (MEMADDR
1451          to MEMADDR + LEN range).
1452
1453          Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1454          offset so that we cannot miss a breakpoint with its shadow
1455          range tail still reaching MEMADDR.  */
1456
1457       if ((bl->address + bp_locations_shadow_len_after_address_max
1458            >= bl->address)
1459           && (bl->address + bp_locations_shadow_len_after_address_max
1460               <= memaddr))
1461         bc_l = bc;
1462       else
1463         bc_r = bc;
1464     }
1465
1466   /* Due to the binary search above, we need to make sure we pick the
1467      first location that's at BC_L's address.  E.g., if there are
1468      multiple locations at the same address, BC_L may end up pointing
1469      at a duplicate location, and miss the "master"/"inserted"
1470      location.  Say, given locations L1, L2 and L3 at addresses A and
1471      B:
1472
1473       L1@A, L2@A, L3@B, ...
1474
1475      BC_L could end up pointing at location L2, while the "master"
1476      location could be L1.  Since the `loc->inserted' flag is only set
1477      on "master" locations, we'd forget to restore the shadow of L1
1478      and L2.  */
1479   while (bc_l > 0
1480          && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1481     bc_l--;
1482
1483   /* Now do full processing of the found relevant range of elements.  */
1484
1485   for (bc = bc_l; bc < bp_locations_count; bc++)
1486   {
1487     struct bp_location *bl = bp_locations[bc];
1488
1489     /* bp_location array has BL->OWNER always non-NULL.  */
1490     if (bl->owner->type == bp_none)
1491       warning (_("reading through apparently deleted breakpoint #%d?"),
1492                bl->owner->number);
1493
1494     /* Performance optimization: any further element can no longer affect BUF
1495        content.  */
1496
1497     if (bl->address >= bp_locations_placed_address_before_address_max
1498         && memaddr + len <= (bl->address
1499                              - bp_locations_placed_address_before_address_max))
1500       break;
1501
1502     if (!bp_location_has_shadow (bl))
1503       continue;
1504
1505     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1506                                 memaddr, len, &bl->target_info, bl->gdbarch);
1507   }
1508 }
1509
1510 \f
1511
1512 /* Return true if BPT is either a software breakpoint or a hardware
1513    breakpoint.  */
1514
1515 int
1516 is_breakpoint (const struct breakpoint *bpt)
1517 {
1518   return (bpt->type == bp_breakpoint
1519           || bpt->type == bp_hardware_breakpoint
1520           || bpt->type == bp_dprintf);
1521 }
1522
1523 /* Return true if BPT is of any hardware watchpoint kind.  */
1524
1525 static int
1526 is_hardware_watchpoint (const struct breakpoint *bpt)
1527 {
1528   return (bpt->type == bp_hardware_watchpoint
1529           || bpt->type == bp_read_watchpoint
1530           || bpt->type == bp_access_watchpoint);
1531 }
1532
1533 /* Return true if BPT is of any watchpoint kind, hardware or
1534    software.  */
1535
1536 int
1537 is_watchpoint (const struct breakpoint *bpt)
1538 {
1539   return (is_hardware_watchpoint (bpt)
1540           || bpt->type == bp_watchpoint);
1541 }
1542
1543 /* Returns true if the current thread and its running state are safe
1544    to evaluate or update watchpoint B.  Watchpoints on local
1545    expressions need to be evaluated in the context of the thread that
1546    was current when the watchpoint was created, and, that thread needs
1547    to be stopped to be able to select the correct frame context.
1548    Watchpoints on global expressions can be evaluated on any thread,
1549    and in any state.  It is presently left to the target allowing
1550    memory accesses when threads are running.  */
1551
1552 static int
1553 watchpoint_in_thread_scope (struct watchpoint *b)
1554 {
1555   return (b->pspace == current_program_space
1556           && (ptid_equal (b->watchpoint_thread, null_ptid)
1557               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1558                   && !is_executing (inferior_ptid))));
1559 }
1560
1561 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1562    associated bp_watchpoint_scope breakpoint.  */
1563
1564 static void
1565 watchpoint_del_at_next_stop (struct watchpoint *w)
1566 {
1567   if (w->related_breakpoint != w)
1568     {
1569       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1570       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1571       w->related_breakpoint->disposition = disp_del_at_next_stop;
1572       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1573       w->related_breakpoint = w;
1574     }
1575   w->disposition = disp_del_at_next_stop;
1576 }
1577
1578 /* Extract a bitfield value from value VAL using the bit parameters contained in
1579    watchpoint W.  */
1580
1581 static struct value *
1582 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1583 {
1584   struct value *bit_val;
1585
1586   if (val == NULL)
1587     return NULL;
1588
1589   bit_val = allocate_value (value_type (val));
1590
1591   unpack_value_bitfield (bit_val,
1592                          w->val_bitpos,
1593                          w->val_bitsize,
1594                          value_contents_for_printing (val),
1595                          value_offset (val),
1596                          val);
1597
1598   return bit_val;
1599 }
1600
1601 /* Allocate a dummy location and add it to B, which must be a software
1602    watchpoint.  This is required because even if a software watchpoint
1603    is not watching any memory, bpstat_stop_status requires a location
1604    to be able to report stops.  */
1605
1606 static void
1607 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1608                                             struct program_space *pspace)
1609 {
1610   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1611
1612   b->loc = allocate_bp_location (b);
1613   b->loc->pspace = pspace;
1614   b->loc->address = -1;
1615   b->loc->length = -1;
1616 }
1617
1618 /* Returns true if B is a software watchpoint that is not watching any
1619    memory (e.g., "watch $pc").  */
1620
1621 static int
1622 is_no_memory_software_watchpoint (struct breakpoint *b)
1623 {
1624   return (b->type == bp_watchpoint
1625           && b->loc != NULL
1626           && b->loc->next == NULL
1627           && b->loc->address == -1
1628           && b->loc->length == -1);
1629 }
1630
1631 /* Assuming that B is a watchpoint:
1632    - Reparse watchpoint expression, if REPARSE is non-zero
1633    - Evaluate expression and store the result in B->val
1634    - Evaluate the condition if there is one, and store the result
1635      in b->loc->cond.
1636    - Update the list of values that must be watched in B->loc.
1637
1638    If the watchpoint disposition is disp_del_at_next_stop, then do
1639    nothing.  If this is local watchpoint that is out of scope, delete
1640    it.
1641
1642    Even with `set breakpoint always-inserted on' the watchpoints are
1643    removed + inserted on each stop here.  Normal breakpoints must
1644    never be removed because they might be missed by a running thread
1645    when debugging in non-stop mode.  On the other hand, hardware
1646    watchpoints (is_hardware_watchpoint; processed here) are specific
1647    to each LWP since they are stored in each LWP's hardware debug
1648    registers.  Therefore, such LWP must be stopped first in order to
1649    be able to modify its hardware watchpoints.
1650
1651    Hardware watchpoints must be reset exactly once after being
1652    presented to the user.  It cannot be done sooner, because it would
1653    reset the data used to present the watchpoint hit to the user.  And
1654    it must not be done later because it could display the same single
1655    watchpoint hit during multiple GDB stops.  Note that the latter is
1656    relevant only to the hardware watchpoint types bp_read_watchpoint
1657    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1658    not user-visible - its hit is suppressed if the memory content has
1659    not changed.
1660
1661    The following constraints influence the location where we can reset
1662    hardware watchpoints:
1663
1664    * target_stopped_by_watchpoint and target_stopped_data_address are
1665      called several times when GDB stops.
1666
1667    [linux] 
1668    * Multiple hardware watchpoints can be hit at the same time,
1669      causing GDB to stop.  GDB only presents one hardware watchpoint
1670      hit at a time as the reason for stopping, and all the other hits
1671      are presented later, one after the other, each time the user
1672      requests the execution to be resumed.  Execution is not resumed
1673      for the threads still having pending hit event stored in
1674      LWP_INFO->STATUS.  While the watchpoint is already removed from
1675      the inferior on the first stop the thread hit event is kept being
1676      reported from its cached value by linux_nat_stopped_data_address
1677      until the real thread resume happens after the watchpoint gets
1678      presented and thus its LWP_INFO->STATUS gets reset.
1679
1680    Therefore the hardware watchpoint hit can get safely reset on the
1681    watchpoint removal from inferior.  */
1682
1683 static void
1684 update_watchpoint (struct watchpoint *b, int reparse)
1685 {
1686   int within_current_scope;
1687   struct frame_id saved_frame_id;
1688   int frame_saved;
1689
1690   /* If this is a local watchpoint, we only want to check if the
1691      watchpoint frame is in scope if the current thread is the thread
1692      that was used to create the watchpoint.  */
1693   if (!watchpoint_in_thread_scope (b))
1694     return;
1695
1696   if (b->disposition == disp_del_at_next_stop)
1697     return;
1698  
1699   frame_saved = 0;
1700
1701   /* Determine if the watchpoint is within scope.  */
1702   if (b->exp_valid_block == NULL)
1703     within_current_scope = 1;
1704   else
1705     {
1706       struct frame_info *fi = get_current_frame ();
1707       struct gdbarch *frame_arch = get_frame_arch (fi);
1708       CORE_ADDR frame_pc = get_frame_pc (fi);
1709
1710       /* If we're at a point where the stack has been destroyed
1711          (e.g. in a function epilogue), unwinding may not work
1712          properly. Do not attempt to recreate locations at this
1713          point.  See similar comments in watchpoint_check.  */
1714       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1715         return;
1716
1717       /* Save the current frame's ID so we can restore it after
1718          evaluating the watchpoint expression on its own frame.  */
1719       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1720          took a frame parameter, so that we didn't have to change the
1721          selected frame.  */
1722       frame_saved = 1;
1723       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1724
1725       fi = frame_find_by_id (b->watchpoint_frame);
1726       within_current_scope = (fi != NULL);
1727       if (within_current_scope)
1728         select_frame (fi);
1729     }
1730
1731   /* We don't free locations.  They are stored in the bp_location array
1732      and update_global_location_list will eventually delete them and
1733      remove breakpoints if needed.  */
1734   b->loc = NULL;
1735
1736   if (within_current_scope && reparse)
1737     {
1738       const char *s;
1739
1740       b->exp.reset ();
1741       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1742       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1743       /* If the meaning of expression itself changed, the old value is
1744          no longer relevant.  We don't want to report a watchpoint hit
1745          to the user when the old value and the new value may actually
1746          be completely different objects.  */
1747       value_free (b->val);
1748       b->val = NULL;
1749       b->val_valid = 0;
1750
1751       /* Note that unlike with breakpoints, the watchpoint's condition
1752          expression is stored in the breakpoint object, not in the
1753          locations (re)created below.  */
1754       if (b->cond_string != NULL)
1755         {
1756           b->cond_exp.reset ();
1757
1758           s = b->cond_string;
1759           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1760         }
1761     }
1762
1763   /* If we failed to parse the expression, for example because
1764      it refers to a global variable in a not-yet-loaded shared library,
1765      don't try to insert watchpoint.  We don't automatically delete
1766      such watchpoint, though, since failure to parse expression
1767      is different from out-of-scope watchpoint.  */
1768   if (!target_has_execution)
1769     {
1770       /* Without execution, memory can't change.  No use to try and
1771          set watchpoint locations.  The watchpoint will be reset when
1772          the target gains execution, through breakpoint_re_set.  */
1773       if (!can_use_hw_watchpoints)
1774         {
1775           if (b->ops->works_in_software_mode (b))
1776             b->type = bp_watchpoint;
1777           else
1778             error (_("Can't set read/access watchpoint when "
1779                      "hardware watchpoints are disabled."));
1780         }
1781     }
1782   else if (within_current_scope && b->exp)
1783     {
1784       int pc = 0;
1785       struct value *val_chain, *v, *result, *next;
1786       struct program_space *frame_pspace;
1787
1788       fetch_subexp_value (b->exp.get (), &pc, &v, &result, &val_chain, 0);
1789
1790       /* Avoid setting b->val if it's already set.  The meaning of
1791          b->val is 'the last value' user saw, and we should update
1792          it only if we reported that last value to user.  As it
1793          happens, the code that reports it updates b->val directly.
1794          We don't keep track of the memory value for masked
1795          watchpoints.  */
1796       if (!b->val_valid && !is_masked_watchpoint (b))
1797         {
1798           if (b->val_bitsize != 0)
1799             {
1800               v = extract_bitfield_from_watchpoint_value (b, v);
1801               if (v != NULL)
1802                 release_value (v);
1803             }
1804           b->val = v;
1805           b->val_valid = 1;
1806         }
1807
1808       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1809
1810       /* Look at each value on the value chain.  */
1811       for (v = val_chain; v; v = value_next (v))
1812         {
1813           /* If it's a memory location, and GDB actually needed
1814              its contents to evaluate the expression, then we
1815              must watch it.  If the first value returned is
1816              still lazy, that means an error occurred reading it;
1817              watch it anyway in case it becomes readable.  */
1818           if (VALUE_LVAL (v) == lval_memory
1819               && (v == val_chain || ! value_lazy (v)))
1820             {
1821               struct type *vtype = check_typedef (value_type (v));
1822
1823               /* We only watch structs and arrays if user asked
1824                  for it explicitly, never if they just happen to
1825                  appear in the middle of some value chain.  */
1826               if (v == result
1827                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1828                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1829                 {
1830                   CORE_ADDR addr;
1831                   enum target_hw_bp_type type;
1832                   struct bp_location *loc, **tmp;
1833                   int bitpos = 0, bitsize = 0;
1834
1835                   if (value_bitsize (v) != 0)
1836                     {
1837                       /* Extract the bit parameters out from the bitfield
1838                          sub-expression.  */
1839                       bitpos = value_bitpos (v);
1840                       bitsize = value_bitsize (v);
1841                     }
1842                   else if (v == result && b->val_bitsize != 0)
1843                     {
1844                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1845                         lvalue whose bit parameters are saved in the fields
1846                         VAL_BITPOS and VAL_BITSIZE.  */
1847                       bitpos = b->val_bitpos;
1848                       bitsize = b->val_bitsize;
1849                     }
1850
1851                   addr = value_address (v);
1852                   if (bitsize != 0)
1853                     {
1854                       /* Skip the bytes that don't contain the bitfield.  */
1855                       addr += bitpos / 8;
1856                     }
1857
1858                   type = hw_write;
1859                   if (b->type == bp_read_watchpoint)
1860                     type = hw_read;
1861                   else if (b->type == bp_access_watchpoint)
1862                     type = hw_access;
1863
1864                   loc = allocate_bp_location (b);
1865                   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
1866                     ;
1867                   *tmp = loc;
1868                   loc->gdbarch = get_type_arch (value_type (v));
1869
1870                   loc->pspace = frame_pspace;
1871                   loc->address = addr;
1872
1873                   if (bitsize != 0)
1874                     {
1875                       /* Just cover the bytes that make up the bitfield.  */
1876                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
1877                     }
1878                   else
1879                     loc->length = TYPE_LENGTH (value_type (v));
1880
1881                   loc->watchpoint_type = type;
1882                 }
1883             }
1884         }
1885
1886       /* Change the type of breakpoint between hardware assisted or
1887          an ordinary watchpoint depending on the hardware support
1888          and free hardware slots.  REPARSE is set when the inferior
1889          is started.  */
1890       if (reparse)
1891         {
1892           int reg_cnt;
1893           enum bp_loc_type loc_type;
1894           struct bp_location *bl;
1895
1896           reg_cnt = can_use_hardware_watchpoint (val_chain);
1897
1898           if (reg_cnt)
1899             {
1900               int i, target_resources_ok, other_type_used;
1901               enum bptype type;
1902
1903               /* Use an exact watchpoint when there's only one memory region to be
1904                  watched, and only one debug register is needed to watch it.  */
1905               b->exact = target_exact_watchpoints && reg_cnt == 1;
1906
1907               /* We need to determine how many resources are already
1908                  used for all other hardware watchpoints plus this one
1909                  to see if we still have enough resources to also fit
1910                  this watchpoint in as well.  */
1911
1912               /* If this is a software watchpoint, we try to turn it
1913                  to a hardware one -- count resources as if B was of
1914                  hardware watchpoint type.  */
1915               type = b->type;
1916               if (type == bp_watchpoint)
1917                 type = bp_hardware_watchpoint;
1918
1919               /* This watchpoint may or may not have been placed on
1920                  the list yet at this point (it won't be in the list
1921                  if we're trying to create it for the first time,
1922                  through watch_command), so always account for it
1923                  manually.  */
1924
1925               /* Count resources used by all watchpoints except B.  */
1926               i = hw_watchpoint_used_count_others (b, type, &other_type_used);
1927
1928               /* Add in the resources needed for B.  */
1929               i += hw_watchpoint_use_count (b);
1930
1931               target_resources_ok
1932                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1933               if (target_resources_ok <= 0)
1934                 {
1935                   int sw_mode = b->ops->works_in_software_mode (b);
1936
1937                   if (target_resources_ok == 0 && !sw_mode)
1938                     error (_("Target does not support this type of "
1939                              "hardware watchpoint."));
1940                   else if (target_resources_ok < 0 && !sw_mode)
1941                     error (_("There are not enough available hardware "
1942                              "resources for this watchpoint."));
1943
1944                   /* Downgrade to software watchpoint.  */
1945                   b->type = bp_watchpoint;
1946                 }
1947               else
1948                 {
1949                   /* If this was a software watchpoint, we've just
1950                      found we have enough resources to turn it to a
1951                      hardware watchpoint.  Otherwise, this is a
1952                      nop.  */
1953                   b->type = type;
1954                 }
1955             }
1956           else if (!b->ops->works_in_software_mode (b))
1957             {
1958               if (!can_use_hw_watchpoints)
1959                 error (_("Can't set read/access watchpoint when "
1960                          "hardware watchpoints are disabled."));
1961               else
1962                 error (_("Expression cannot be implemented with "
1963                          "read/access watchpoint."));
1964             }
1965           else
1966             b->type = bp_watchpoint;
1967
1968           loc_type = (b->type == bp_watchpoint? bp_loc_other
1969                       : bp_loc_hardware_watchpoint);
1970           for (bl = b->loc; bl; bl = bl->next)
1971             bl->loc_type = loc_type;
1972         }
1973
1974       for (v = val_chain; v; v = next)
1975         {
1976           next = value_next (v);
1977           if (v != b->val)
1978             value_free (v);
1979         }
1980
1981       /* If a software watchpoint is not watching any memory, then the
1982          above left it without any location set up.  But,
1983          bpstat_stop_status requires a location to be able to report
1984          stops, so make sure there's at least a dummy one.  */
1985       if (b->type == bp_watchpoint && b->loc == NULL)
1986         software_watchpoint_add_no_memory_location (b, frame_pspace);
1987     }
1988   else if (!within_current_scope)
1989     {
1990       printf_filtered (_("\
1991 Watchpoint %d deleted because the program has left the block\n\
1992 in which its expression is valid.\n"),
1993                        b->number);
1994       watchpoint_del_at_next_stop (b);
1995     }
1996
1997   /* Restore the selected frame.  */
1998   if (frame_saved)
1999     select_frame (frame_find_by_id (saved_frame_id));
2000 }
2001
2002
2003 /* Returns 1 iff breakpoint location should be
2004    inserted in the inferior.  We don't differentiate the type of BL's owner
2005    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2006    breakpoint_ops is not defined, because in insert_bp_location,
2007    tracepoint's insert_location will not be called.  */
2008 static int
2009 should_be_inserted (struct bp_location *bl)
2010 {
2011   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2012     return 0;
2013
2014   if (bl->owner->disposition == disp_del_at_next_stop)
2015     return 0;
2016
2017   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2018     return 0;
2019
2020   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2021     return 0;
2022
2023   /* This is set for example, when we're attached to the parent of a
2024      vfork, and have detached from the child.  The child is running
2025      free, and we expect it to do an exec or exit, at which point the
2026      OS makes the parent schedulable again (and the target reports
2027      that the vfork is done).  Until the child is done with the shared
2028      memory region, do not insert breakpoints in the parent, otherwise
2029      the child could still trip on the parent's breakpoints.  Since
2030      the parent is blocked anyway, it won't miss any breakpoint.  */
2031   if (bl->pspace->breakpoints_not_allowed)
2032     return 0;
2033
2034   /* Don't insert a breakpoint if we're trying to step past its
2035      location, except if the breakpoint is a single-step breakpoint,
2036      and the breakpoint's thread is the thread which is stepping past
2037      a breakpoint.  */
2038   if ((bl->loc_type == bp_loc_software_breakpoint
2039        || bl->loc_type == bp_loc_hardware_breakpoint)
2040       && stepping_past_instruction_at (bl->pspace->aspace,
2041                                        bl->address)
2042       /* The single-step breakpoint may be inserted at the location
2043          we're trying to step if the instruction branches to itself.
2044          However, the instruction won't be executed at all and it may
2045          break the semantics of the instruction, for example, the
2046          instruction is a conditional branch or updates some flags.
2047          We can't fix it unless GDB is able to emulate the instruction
2048          or switch to displaced stepping.  */
2049       && !(bl->owner->type == bp_single_step
2050            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2051     {
2052       if (debug_infrun)
2053         {
2054           fprintf_unfiltered (gdb_stdlog,
2055                               "infrun: skipping breakpoint: "
2056                               "stepping past insn at: %s\n",
2057                               paddress (bl->gdbarch, bl->address));
2058         }
2059       return 0;
2060     }
2061
2062   /* Don't insert watchpoints if we're trying to step past the
2063      instruction that triggered one.  */
2064   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2065       && stepping_past_nonsteppable_watchpoint ())
2066     {
2067       if (debug_infrun)
2068         {
2069           fprintf_unfiltered (gdb_stdlog,
2070                               "infrun: stepping past non-steppable watchpoint. "
2071                               "skipping watchpoint at %s:%d\n",
2072                               paddress (bl->gdbarch, bl->address),
2073                               bl->length);
2074         }
2075       return 0;
2076     }
2077
2078   return 1;
2079 }
2080
2081 /* Same as should_be_inserted but does the check assuming
2082    that the location is not duplicated.  */
2083
2084 static int
2085 unduplicated_should_be_inserted (struct bp_location *bl)
2086 {
2087   int result;
2088   const int save_duplicate = bl->duplicate;
2089
2090   bl->duplicate = 0;
2091   result = should_be_inserted (bl);
2092   bl->duplicate = save_duplicate;
2093   return result;
2094 }
2095
2096 /* Parses a conditional described by an expression COND into an
2097    agent expression bytecode suitable for evaluation
2098    by the bytecode interpreter.  Return NULL if there was
2099    any error during parsing.  */
2100
2101 static agent_expr_up
2102 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2103 {
2104   if (cond == NULL)
2105     return NULL;
2106
2107   agent_expr_up aexpr;
2108
2109   /* We don't want to stop processing, so catch any errors
2110      that may show up.  */
2111   TRY
2112     {
2113       aexpr = gen_eval_for_expr (scope, cond);
2114     }
2115
2116   CATCH (ex, RETURN_MASK_ERROR)
2117     {
2118       /* If we got here, it means the condition could not be parsed to a valid
2119          bytecode expression and thus can't be evaluated on the target's side.
2120          It's no use iterating through the conditions.  */
2121     }
2122   END_CATCH
2123
2124   /* We have a valid agent expression.  */
2125   return aexpr;
2126 }
2127
2128 /* Based on location BL, create a list of breakpoint conditions to be
2129    passed on to the target.  If we have duplicated locations with different
2130    conditions, we will add such conditions to the list.  The idea is that the
2131    target will evaluate the list of conditions and will only notify GDB when
2132    one of them is true.  */
2133
2134 static void
2135 build_target_condition_list (struct bp_location *bl)
2136 {
2137   struct bp_location **locp = NULL, **loc2p;
2138   int null_condition_or_parse_error = 0;
2139   int modified = bl->needs_update;
2140   struct bp_location *loc;
2141
2142   /* Release conditions left over from a previous insert.  */
2143   bl->target_info.conditions.clear ();
2144
2145   /* This is only meaningful if the target is
2146      evaluating conditions and if the user has
2147      opted for condition evaluation on the target's
2148      side.  */
2149   if (gdb_evaluates_breakpoint_condition_p ()
2150       || !target_supports_evaluation_of_breakpoint_conditions ())
2151     return;
2152
2153   /* Do a first pass to check for locations with no assigned
2154      conditions or conditions that fail to parse to a valid agent expression
2155      bytecode.  If any of these happen, then it's no use to send conditions
2156      to the target since this location will always trigger and generate a
2157      response back to GDB.  */
2158   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2159     {
2160       loc = (*loc2p);
2161       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2162         {
2163           if (modified)
2164             {
2165               /* Re-parse the conditions since something changed.  In that
2166                  case we already freed the condition bytecodes (see
2167                  force_breakpoint_reinsertion).  We just
2168                  need to parse the condition to bytecodes again.  */
2169               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2170                                                         loc->cond.get ());
2171             }
2172
2173           /* If we have a NULL bytecode expression, it means something
2174              went wrong or we have a null condition expression.  */
2175           if (!loc->cond_bytecode)
2176             {
2177               null_condition_or_parse_error = 1;
2178               break;
2179             }
2180         }
2181     }
2182
2183   /* If any of these happened, it means we will have to evaluate the conditions
2184      for the location's address on gdb's side.  It is no use keeping bytecodes
2185      for all the other duplicate locations, thus we free all of them here.
2186
2187      This is so we have a finer control over which locations' conditions are
2188      being evaluated by GDB or the remote stub.  */
2189   if (null_condition_or_parse_error)
2190     {
2191       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2192         {
2193           loc = (*loc2p);
2194           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2195             {
2196               /* Only go as far as the first NULL bytecode is
2197                  located.  */
2198               if (!loc->cond_bytecode)
2199                 return;
2200
2201               loc->cond_bytecode.reset ();
2202             }
2203         }
2204     }
2205
2206   /* No NULL conditions or failed bytecode generation.  Build a condition list
2207      for this location's address.  */
2208   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2209     {
2210       loc = (*loc2p);
2211       if (loc->cond
2212           && is_breakpoint (loc->owner)
2213           && loc->pspace->num == bl->pspace->num
2214           && loc->owner->enable_state == bp_enabled
2215           && loc->enabled)
2216         {
2217           /* Add the condition to the vector.  This will be used later
2218              to send the conditions to the target.  */
2219           bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2220         }
2221     }
2222
2223   return;
2224 }
2225
2226 /* Parses a command described by string CMD into an agent expression
2227    bytecode suitable for evaluation by the bytecode interpreter.
2228    Return NULL if there was any error during parsing.  */
2229
2230 static agent_expr_up
2231 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2232 {
2233   struct cleanup *old_cleanups = 0;
2234   struct expression **argvec;
2235   const char *cmdrest;
2236   const char *format_start, *format_end;
2237   struct format_piece *fpieces;
2238   int nargs;
2239   struct gdbarch *gdbarch = get_current_arch ();
2240
2241   if (cmd == NULL)
2242     return NULL;
2243
2244   cmdrest = cmd;
2245
2246   if (*cmdrest == ',')
2247     ++cmdrest;
2248   cmdrest = skip_spaces (cmdrest);
2249
2250   if (*cmdrest++ != '"')
2251     error (_("No format string following the location"));
2252
2253   format_start = cmdrest;
2254
2255   fpieces = parse_format_string (&cmdrest);
2256
2257   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2258
2259   format_end = cmdrest;
2260
2261   if (*cmdrest++ != '"')
2262     error (_("Bad format string, non-terminated '\"'."));
2263   
2264   cmdrest = skip_spaces (cmdrest);
2265
2266   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2267     error (_("Invalid argument syntax"));
2268
2269   if (*cmdrest == ',')
2270     cmdrest++;
2271   cmdrest = skip_spaces (cmdrest);
2272
2273   /* For each argument, make an expression.  */
2274
2275   argvec = (struct expression **) alloca (strlen (cmd)
2276                                          * sizeof (struct expression *));
2277
2278   nargs = 0;
2279   while (*cmdrest != '\0')
2280     {
2281       const char *cmd1;
2282
2283       cmd1 = cmdrest;
2284       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2285       argvec[nargs++] = expr.release ();
2286       cmdrest = cmd1;
2287       if (*cmdrest == ',')
2288         ++cmdrest;
2289     }
2290
2291   agent_expr_up aexpr;
2292
2293   /* We don't want to stop processing, so catch any errors
2294      that may show up.  */
2295   TRY
2296     {
2297       aexpr = gen_printf (scope, gdbarch, 0, 0,
2298                           format_start, format_end - format_start,
2299                           fpieces, nargs, argvec);
2300     }
2301   CATCH (ex, RETURN_MASK_ERROR)
2302     {
2303       /* If we got here, it means the command could not be parsed to a valid
2304          bytecode expression and thus can't be evaluated on the target's side.
2305          It's no use iterating through the other commands.  */
2306     }
2307   END_CATCH
2308
2309   do_cleanups (old_cleanups);
2310
2311   /* We have a valid agent expression, return it.  */
2312   return aexpr;
2313 }
2314
2315 /* Based on location BL, create a list of breakpoint commands to be
2316    passed on to the target.  If we have duplicated locations with
2317    different commands, we will add any such to the list.  */
2318
2319 static void
2320 build_target_command_list (struct bp_location *bl)
2321 {
2322   struct bp_location **locp = NULL, **loc2p;
2323   int null_command_or_parse_error = 0;
2324   int modified = bl->needs_update;
2325   struct bp_location *loc;
2326
2327   /* Clear commands left over from a previous insert.  */
2328   bl->target_info.tcommands.clear ();
2329
2330   if (!target_can_run_breakpoint_commands ())
2331     return;
2332
2333   /* For now, limit to agent-style dprintf breakpoints.  */
2334   if (dprintf_style != dprintf_style_agent)
2335     return;
2336
2337   /* For now, if we have any duplicate location that isn't a dprintf,
2338      don't install the target-side commands, as that would make the
2339      breakpoint not be reported to the core, and we'd lose
2340      control.  */
2341   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2342     {
2343       loc = (*loc2p);
2344       if (is_breakpoint (loc->owner)
2345           && loc->pspace->num == bl->pspace->num
2346           && loc->owner->type != bp_dprintf)
2347         return;
2348     }
2349
2350   /* Do a first pass to check for locations with no assigned
2351      conditions or conditions that fail to parse to a valid agent expression
2352      bytecode.  If any of these happen, then it's no use to send conditions
2353      to the target since this location will always trigger and generate a
2354      response back to GDB.  */
2355   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2356     {
2357       loc = (*loc2p);
2358       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2359         {
2360           if (modified)
2361             {
2362               /* Re-parse the commands since something changed.  In that
2363                  case we already freed the command bytecodes (see
2364                  force_breakpoint_reinsertion).  We just
2365                  need to parse the command to bytecodes again.  */
2366               loc->cmd_bytecode
2367                 = parse_cmd_to_aexpr (bl->address,
2368                                       loc->owner->extra_string);
2369             }
2370
2371           /* If we have a NULL bytecode expression, it means something
2372              went wrong or we have a null command expression.  */
2373           if (!loc->cmd_bytecode)
2374             {
2375               null_command_or_parse_error = 1;
2376               break;
2377             }
2378         }
2379     }
2380
2381   /* If anything failed, then we're not doing target-side commands,
2382      and so clean up.  */
2383   if (null_command_or_parse_error)
2384     {
2385       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2386         {
2387           loc = (*loc2p);
2388           if (is_breakpoint (loc->owner)
2389               && loc->pspace->num == bl->pspace->num)
2390             {
2391               /* Only go as far as the first NULL bytecode is
2392                  located.  */
2393               if (loc->cmd_bytecode == NULL)
2394                 return;
2395
2396               loc->cmd_bytecode.reset ();
2397             }
2398         }
2399     }
2400
2401   /* No NULL commands or failed bytecode generation.  Build a command list
2402      for this location's address.  */
2403   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2404     {
2405       loc = (*loc2p);
2406       if (loc->owner->extra_string
2407           && is_breakpoint (loc->owner)
2408           && loc->pspace->num == bl->pspace->num
2409           && loc->owner->enable_state == bp_enabled
2410           && loc->enabled)
2411         {
2412           /* Add the command to the vector.  This will be used later
2413              to send the commands to the target.  */
2414           bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2415         }
2416     }
2417
2418   bl->target_info.persist = 0;
2419   /* Maybe flag this location as persistent.  */
2420   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2421     bl->target_info.persist = 1;
2422 }
2423
2424 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2425    of breakpoint according to ADDR except single-step breakpoint.
2426    Get the kind of single-step breakpoint according to the current
2427    registers state.  */
2428
2429 static int
2430 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2431 {
2432   if (bl->owner->type == bp_single_step)
2433     {
2434       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2435       struct regcache *regcache;
2436
2437       regcache = get_thread_regcache (thr->ptid);
2438
2439       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2440                                                          regcache, addr);
2441     }
2442   else
2443     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2444 }
2445
2446 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2447    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2448    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2449    Returns 0 for success, 1 if the bp_location type is not supported or
2450    -1 for failure.
2451
2452    NOTE drow/2003-09-09: This routine could be broken down to an
2453    object-style method for each breakpoint or catchpoint type.  */
2454 static int
2455 insert_bp_location (struct bp_location *bl,
2456                     struct ui_file *tmp_error_stream,
2457                     int *disabled_breaks,
2458                     int *hw_breakpoint_error,
2459                     int *hw_bp_error_explained_already)
2460 {
2461   gdb_exception bp_excpt = exception_none;
2462
2463   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2464     return 0;
2465
2466   /* Note we don't initialize bl->target_info, as that wipes out
2467      the breakpoint location's shadow_contents if the breakpoint
2468      is still inserted at that location.  This in turn breaks
2469      target_read_memory which depends on these buffers when
2470      a memory read is requested at the breakpoint location:
2471      Once the target_info has been wiped, we fail to see that
2472      we have a breakpoint inserted at that address and thus
2473      read the breakpoint instead of returning the data saved in
2474      the breakpoint location's shadow contents.  */
2475   bl->target_info.reqstd_address = bl->address;
2476   bl->target_info.placed_address_space = bl->pspace->aspace;
2477   bl->target_info.length = bl->length;
2478
2479   /* When working with target-side conditions, we must pass all the conditions
2480      for the same breakpoint address down to the target since GDB will not
2481      insert those locations.  With a list of breakpoint conditions, the target
2482      can decide when to stop and notify GDB.  */
2483
2484   if (is_breakpoint (bl->owner))
2485     {
2486       build_target_condition_list (bl);
2487       build_target_command_list (bl);
2488       /* Reset the modification marker.  */
2489       bl->needs_update = 0;
2490     }
2491
2492   if (bl->loc_type == bp_loc_software_breakpoint
2493       || bl->loc_type == bp_loc_hardware_breakpoint)
2494     {
2495       if (bl->owner->type != bp_hardware_breakpoint)
2496         {
2497           /* If the explicitly specified breakpoint type
2498              is not hardware breakpoint, check the memory map to see
2499              if the breakpoint address is in read only memory or not.
2500
2501              Two important cases are:
2502              - location type is not hardware breakpoint, memory
2503              is readonly.  We change the type of the location to
2504              hardware breakpoint.
2505              - location type is hardware breakpoint, memory is
2506              read-write.  This means we've previously made the
2507              location hardware one, but then the memory map changed,
2508              so we undo.
2509              
2510              When breakpoints are removed, remove_breakpoints will use
2511              location types we've just set here, the only possible
2512              problem is that memory map has changed during running
2513              program, but it's not going to work anyway with current
2514              gdb.  */
2515           struct mem_region *mr 
2516             = lookup_mem_region (bl->target_info.reqstd_address);
2517           
2518           if (mr)
2519             {
2520               if (automatic_hardware_breakpoints)
2521                 {
2522                   enum bp_loc_type new_type;
2523                   
2524                   if (mr->attrib.mode != MEM_RW)
2525                     new_type = bp_loc_hardware_breakpoint;
2526                   else 
2527                     new_type = bp_loc_software_breakpoint;
2528                   
2529                   if (new_type != bl->loc_type)
2530                     {
2531                       static int said = 0;
2532
2533                       bl->loc_type = new_type;
2534                       if (!said)
2535                         {
2536                           fprintf_filtered (gdb_stdout,
2537                                             _("Note: automatically using "
2538                                               "hardware breakpoints for "
2539                                               "read-only addresses.\n"));
2540                           said = 1;
2541                         }
2542                     }
2543                 }
2544               else if (bl->loc_type == bp_loc_software_breakpoint
2545                        && mr->attrib.mode != MEM_RW)
2546                 {
2547                   fprintf_unfiltered (tmp_error_stream,
2548                                       _("Cannot insert breakpoint %d.\n"
2549                                         "Cannot set software breakpoint "
2550                                         "at read-only address %s\n"),
2551                                       bl->owner->number,
2552                                       paddress (bl->gdbarch, bl->address));
2553                   return 1;
2554                 }
2555             }
2556         }
2557         
2558       /* First check to see if we have to handle an overlay.  */
2559       if (overlay_debugging == ovly_off
2560           || bl->section == NULL
2561           || !(section_is_overlay (bl->section)))
2562         {
2563           /* No overlay handling: just set the breakpoint.  */
2564           TRY
2565             {
2566               int val;
2567
2568               val = bl->owner->ops->insert_location (bl);
2569               if (val)
2570                 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2571             }
2572           CATCH (e, RETURN_MASK_ALL)
2573             {
2574               bp_excpt = e;
2575             }
2576           END_CATCH
2577         }
2578       else
2579         {
2580           /* This breakpoint is in an overlay section.
2581              Shall we set a breakpoint at the LMA?  */
2582           if (!overlay_events_enabled)
2583             {
2584               /* Yes -- overlay event support is not active, 
2585                  so we must try to set a breakpoint at the LMA.
2586                  This will not work for a hardware breakpoint.  */
2587               if (bl->loc_type == bp_loc_hardware_breakpoint)
2588                 warning (_("hardware breakpoint %d not supported in overlay!"),
2589                          bl->owner->number);
2590               else
2591                 {
2592                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2593                                                              bl->section);
2594                   /* Set a software (trap) breakpoint at the LMA.  */
2595                   bl->overlay_target_info = bl->target_info;
2596                   bl->overlay_target_info.reqstd_address = addr;
2597
2598                   /* No overlay handling: just set the breakpoint.  */
2599                   TRY
2600                     {
2601                       int val;
2602
2603                       bl->overlay_target_info.kind
2604                         = breakpoint_kind (bl, &addr);
2605                       bl->overlay_target_info.placed_address = addr;
2606                       val = target_insert_breakpoint (bl->gdbarch,
2607                                                       &bl->overlay_target_info);
2608                       if (val)
2609                         bp_excpt
2610                           = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2611                     }
2612                   CATCH (e, RETURN_MASK_ALL)
2613                     {
2614                       bp_excpt = e;
2615                     }
2616                   END_CATCH
2617
2618                   if (bp_excpt.reason != 0)
2619                     fprintf_unfiltered (tmp_error_stream,
2620                                         "Overlay breakpoint %d "
2621                                         "failed: in ROM?\n",
2622                                         bl->owner->number);
2623                 }
2624             }
2625           /* Shall we set a breakpoint at the VMA? */
2626           if (section_is_mapped (bl->section))
2627             {
2628               /* Yes.  This overlay section is mapped into memory.  */
2629               TRY
2630                 {
2631                   int val;
2632
2633                   val = bl->owner->ops->insert_location (bl);
2634                   if (val)
2635                     bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2636                 }
2637               CATCH (e, RETURN_MASK_ALL)
2638                 {
2639                   bp_excpt = e;
2640                 }
2641               END_CATCH
2642             }
2643           else
2644             {
2645               /* No.  This breakpoint will not be inserted.  
2646                  No error, but do not mark the bp as 'inserted'.  */
2647               return 0;
2648             }
2649         }
2650
2651       if (bp_excpt.reason != 0)
2652         {
2653           /* Can't set the breakpoint.  */
2654
2655           /* In some cases, we might not be able to insert a
2656              breakpoint in a shared library that has already been
2657              removed, but we have not yet processed the shlib unload
2658              event.  Unfortunately, some targets that implement
2659              breakpoint insertion themselves can't tell why the
2660              breakpoint insertion failed (e.g., the remote target
2661              doesn't define error codes), so we must treat generic
2662              errors as memory errors.  */
2663           if (bp_excpt.reason == RETURN_ERROR
2664               && (bp_excpt.error == GENERIC_ERROR
2665                   || bp_excpt.error == MEMORY_ERROR)
2666               && bl->loc_type == bp_loc_software_breakpoint
2667               && (solib_name_from_address (bl->pspace, bl->address)
2668                   || shared_objfile_contains_address_p (bl->pspace,
2669                                                         bl->address)))
2670             {
2671               /* See also: disable_breakpoints_in_shlibs.  */
2672               bl->shlib_disabled = 1;
2673               observer_notify_breakpoint_modified (bl->owner);
2674               if (!*disabled_breaks)
2675                 {
2676                   fprintf_unfiltered (tmp_error_stream, 
2677                                       "Cannot insert breakpoint %d.\n", 
2678                                       bl->owner->number);
2679                   fprintf_unfiltered (tmp_error_stream, 
2680                                       "Temporarily disabling shared "
2681                                       "library breakpoints:\n");
2682                 }
2683               *disabled_breaks = 1;
2684               fprintf_unfiltered (tmp_error_stream,
2685                                   "breakpoint #%d\n", bl->owner->number);
2686               return 0;
2687             }
2688           else
2689             {
2690               if (bl->loc_type == bp_loc_hardware_breakpoint)
2691                 {
2692                   *hw_breakpoint_error = 1;
2693                   *hw_bp_error_explained_already = bp_excpt.message != NULL;
2694                   fprintf_unfiltered (tmp_error_stream,
2695                                       "Cannot insert hardware breakpoint %d%s",
2696                                       bl->owner->number,
2697                                       bp_excpt.message ? ":" : ".\n");
2698                   if (bp_excpt.message != NULL)
2699                     fprintf_unfiltered (tmp_error_stream, "%s.\n",
2700                                         bp_excpt.message);
2701                 }
2702               else
2703                 {
2704                   if (bp_excpt.message == NULL)
2705                     {
2706                       std::string message
2707                         = memory_error_message (TARGET_XFER_E_IO,
2708                                                 bl->gdbarch, bl->address);
2709
2710                       fprintf_unfiltered (tmp_error_stream,
2711                                           "Cannot insert breakpoint %d.\n"
2712                                           "%s\n",
2713                                           bl->owner->number, message.c_str ());
2714                     }
2715                   else
2716                     {
2717                       fprintf_unfiltered (tmp_error_stream,
2718                                           "Cannot insert breakpoint %d: %s\n",
2719                                           bl->owner->number,
2720                                           bp_excpt.message);
2721                     }
2722                 }
2723               return 1;
2724
2725             }
2726         }
2727       else
2728         bl->inserted = 1;
2729
2730       return 0;
2731     }
2732
2733   else if (bl->loc_type == bp_loc_hardware_watchpoint
2734            /* NOTE drow/2003-09-08: This state only exists for removing
2735               watchpoints.  It's not clear that it's necessary...  */
2736            && bl->owner->disposition != disp_del_at_next_stop)
2737     {
2738       int val;
2739
2740       gdb_assert (bl->owner->ops != NULL
2741                   && bl->owner->ops->insert_location != NULL);
2742
2743       val = bl->owner->ops->insert_location (bl);
2744
2745       /* If trying to set a read-watchpoint, and it turns out it's not
2746          supported, try emulating one with an access watchpoint.  */
2747       if (val == 1 && bl->watchpoint_type == hw_read)
2748         {
2749           struct bp_location *loc, **loc_temp;
2750
2751           /* But don't try to insert it, if there's already another
2752              hw_access location that would be considered a duplicate
2753              of this one.  */
2754           ALL_BP_LOCATIONS (loc, loc_temp)
2755             if (loc != bl
2756                 && loc->watchpoint_type == hw_access
2757                 && watchpoint_locations_match (bl, loc))
2758               {
2759                 bl->duplicate = 1;
2760                 bl->inserted = 1;
2761                 bl->target_info = loc->target_info;
2762                 bl->watchpoint_type = hw_access;
2763                 val = 0;
2764                 break;
2765               }
2766
2767           if (val == 1)
2768             {
2769               bl->watchpoint_type = hw_access;
2770               val = bl->owner->ops->insert_location (bl);
2771
2772               if (val)
2773                 /* Back to the original value.  */
2774                 bl->watchpoint_type = hw_read;
2775             }
2776         }
2777
2778       bl->inserted = (val == 0);
2779     }
2780
2781   else if (bl->owner->type == bp_catchpoint)
2782     {
2783       int val;
2784
2785       gdb_assert (bl->owner->ops != NULL
2786                   && bl->owner->ops->insert_location != NULL);
2787
2788       val = bl->owner->ops->insert_location (bl);
2789       if (val)
2790         {
2791           bl->owner->enable_state = bp_disabled;
2792
2793           if (val == 1)
2794             warning (_("\
2795 Error inserting catchpoint %d: Your system does not support this type\n\
2796 of catchpoint."), bl->owner->number);
2797           else
2798             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2799         }
2800
2801       bl->inserted = (val == 0);
2802
2803       /* We've already printed an error message if there was a problem
2804          inserting this catchpoint, and we've disabled the catchpoint,
2805          so just return success.  */
2806       return 0;
2807     }
2808
2809   return 0;
2810 }
2811
2812 /* This function is called when program space PSPACE is about to be
2813    deleted.  It takes care of updating breakpoints to not reference
2814    PSPACE anymore.  */
2815
2816 void
2817 breakpoint_program_space_exit (struct program_space *pspace)
2818 {
2819   struct breakpoint *b, *b_temp;
2820   struct bp_location *loc, **loc_temp;
2821
2822   /* Remove any breakpoint that was set through this program space.  */
2823   ALL_BREAKPOINTS_SAFE (b, b_temp)
2824     {
2825       if (b->pspace == pspace)
2826         delete_breakpoint (b);
2827     }
2828
2829   /* Breakpoints set through other program spaces could have locations
2830      bound to PSPACE as well.  Remove those.  */
2831   ALL_BP_LOCATIONS (loc, loc_temp)
2832     {
2833       struct bp_location *tmp;
2834
2835       if (loc->pspace == pspace)
2836         {
2837           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2838           if (loc->owner->loc == loc)
2839             loc->owner->loc = loc->next;
2840           else
2841             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2842               if (tmp->next == loc)
2843                 {
2844                   tmp->next = loc->next;
2845                   break;
2846                 }
2847         }
2848     }
2849
2850   /* Now update the global location list to permanently delete the
2851      removed locations above.  */
2852   update_global_location_list (UGLL_DONT_INSERT);
2853 }
2854
2855 /* Make sure all breakpoints are inserted in inferior.
2856    Throws exception on any error.
2857    A breakpoint that is already inserted won't be inserted
2858    again, so calling this function twice is safe.  */
2859 void
2860 insert_breakpoints (void)
2861 {
2862   struct breakpoint *bpt;
2863
2864   ALL_BREAKPOINTS (bpt)
2865     if (is_hardware_watchpoint (bpt))
2866       {
2867         struct watchpoint *w = (struct watchpoint *) bpt;
2868
2869         update_watchpoint (w, 0 /* don't reparse.  */);
2870       }
2871
2872   /* Updating watchpoints creates new locations, so update the global
2873      location list.  Explicitly tell ugll to insert locations and
2874      ignore breakpoints_always_inserted_mode.  */
2875   update_global_location_list (UGLL_INSERT);
2876 }
2877
2878 /* Invoke CALLBACK for each of bp_location.  */
2879
2880 void
2881 iterate_over_bp_locations (walk_bp_location_callback callback)
2882 {
2883   struct bp_location *loc, **loc_tmp;
2884
2885   ALL_BP_LOCATIONS (loc, loc_tmp)
2886     {
2887       callback (loc, NULL);
2888     }
2889 }
2890
2891 /* This is used when we need to synch breakpoint conditions between GDB and the
2892    target.  It is the case with deleting and disabling of breakpoints when using
2893    always-inserted mode.  */
2894
2895 static void
2896 update_inserted_breakpoint_locations (void)
2897 {
2898   struct bp_location *bl, **blp_tmp;
2899   int error_flag = 0;
2900   int val = 0;
2901   int disabled_breaks = 0;
2902   int hw_breakpoint_error = 0;
2903   int hw_bp_details_reported = 0;
2904
2905   string_file tmp_error_stream;
2906
2907   /* Explicitly mark the warning -- this will only be printed if
2908      there was an error.  */
2909   tmp_error_stream.puts ("Warning:\n");
2910
2911   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2912
2913   ALL_BP_LOCATIONS (bl, blp_tmp)
2914     {
2915       /* We only want to update software breakpoints and hardware
2916          breakpoints.  */
2917       if (!is_breakpoint (bl->owner))
2918         continue;
2919
2920       /* We only want to update locations that are already inserted
2921          and need updating.  This is to avoid unwanted insertion during
2922          deletion of breakpoints.  */
2923       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2924         continue;
2925
2926       switch_to_program_space_and_thread (bl->pspace);
2927
2928       /* For targets that support global breakpoints, there's no need
2929          to select an inferior to insert breakpoint to.  In fact, even
2930          if we aren't attached to any process yet, we should still
2931          insert breakpoints.  */
2932       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2933           && ptid_equal (inferior_ptid, null_ptid))
2934         continue;
2935
2936       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2937                                     &hw_breakpoint_error, &hw_bp_details_reported);
2938       if (val)
2939         error_flag = val;
2940     }
2941
2942   if (error_flag)
2943     {
2944       target_terminal::ours_for_output ();
2945       error_stream (tmp_error_stream);
2946     }
2947 }
2948
2949 /* Used when starting or continuing the program.  */
2950
2951 static void
2952 insert_breakpoint_locations (void)
2953 {
2954   struct breakpoint *bpt;
2955   struct bp_location *bl, **blp_tmp;
2956   int error_flag = 0;
2957   int val = 0;
2958   int disabled_breaks = 0;
2959   int hw_breakpoint_error = 0;
2960   int hw_bp_error_explained_already = 0;
2961
2962   string_file tmp_error_stream;
2963
2964   /* Explicitly mark the warning -- this will only be printed if
2965      there was an error.  */
2966   tmp_error_stream.puts ("Warning:\n");
2967
2968   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2969
2970   ALL_BP_LOCATIONS (bl, blp_tmp)
2971     {
2972       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2973         continue;
2974
2975       /* There is no point inserting thread-specific breakpoints if
2976          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2977          has BL->OWNER always non-NULL.  */
2978       if (bl->owner->thread != -1
2979           && !valid_global_thread_id (bl->owner->thread))
2980         continue;
2981
2982       switch_to_program_space_and_thread (bl->pspace);
2983
2984       /* For targets that support global breakpoints, there's no need
2985          to select an inferior to insert breakpoint to.  In fact, even
2986          if we aren't attached to any process yet, we should still
2987          insert breakpoints.  */
2988       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2989           && ptid_equal (inferior_ptid, null_ptid))
2990         continue;
2991
2992       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2993                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
2994       if (val)
2995         error_flag = val;
2996     }
2997
2998   /* If we failed to insert all locations of a watchpoint, remove
2999      them, as half-inserted watchpoint is of limited use.  */
3000   ALL_BREAKPOINTS (bpt)  
3001     {
3002       int some_failed = 0;
3003       struct bp_location *loc;
3004
3005       if (!is_hardware_watchpoint (bpt))
3006         continue;
3007
3008       if (!breakpoint_enabled (bpt))
3009         continue;
3010
3011       if (bpt->disposition == disp_del_at_next_stop)
3012         continue;
3013       
3014       for (loc = bpt->loc; loc; loc = loc->next)
3015         if (!loc->inserted && should_be_inserted (loc))
3016           {
3017             some_failed = 1;
3018             break;
3019           }
3020       if (some_failed)
3021         {
3022           for (loc = bpt->loc; loc; loc = loc->next)
3023             if (loc->inserted)
3024               remove_breakpoint (loc);
3025
3026           hw_breakpoint_error = 1;
3027           tmp_error_stream.printf ("Could not insert "
3028                                    "hardware watchpoint %d.\n",
3029                                    bpt->number);
3030           error_flag = -1;
3031         }
3032     }
3033
3034   if (error_flag)
3035     {
3036       /* If a hardware breakpoint or watchpoint was inserted, add a
3037          message about possibly exhausted resources.  */
3038       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3039         {
3040           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3041 You may have requested too many hardware breakpoints/watchpoints.\n");
3042         }
3043       target_terminal::ours_for_output ();
3044       error_stream (tmp_error_stream);
3045     }
3046 }
3047
3048 /* Used when the program stops.
3049    Returns zero if successful, or non-zero if there was a problem
3050    removing a breakpoint location.  */
3051
3052 int
3053 remove_breakpoints (void)
3054 {
3055   struct bp_location *bl, **blp_tmp;
3056   int val = 0;
3057
3058   ALL_BP_LOCATIONS (bl, blp_tmp)
3059   {
3060     if (bl->inserted && !is_tracepoint (bl->owner))
3061       val |= remove_breakpoint (bl);
3062   }
3063   return val;
3064 }
3065
3066 /* When a thread exits, remove breakpoints that are related to
3067    that thread.  */
3068
3069 static void
3070 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3071 {
3072   struct breakpoint *b, *b_tmp;
3073
3074   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3075     {
3076       if (b->thread == tp->global_num && user_breakpoint_p (b))
3077         {
3078           b->disposition = disp_del_at_next_stop;
3079
3080           printf_filtered (_("\
3081 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3082                            b->number, print_thread_id (tp));
3083
3084           /* Hide it from the user.  */
3085           b->number = 0;
3086        }
3087     }
3088 }
3089
3090 /* Remove breakpoints of process PID.  */
3091
3092 int
3093 remove_breakpoints_pid (int pid)
3094 {
3095   struct bp_location *bl, **blp_tmp;
3096   int val;
3097   struct inferior *inf = find_inferior_pid (pid);
3098
3099   ALL_BP_LOCATIONS (bl, blp_tmp)
3100   {
3101     if (bl->pspace != inf->pspace)
3102       continue;
3103
3104     if (bl->inserted && !bl->target_info.persist)
3105       {
3106         val = remove_breakpoint (bl);
3107         if (val != 0)
3108           return val;
3109       }
3110   }
3111   return 0;
3112 }
3113
3114 static int internal_breakpoint_number = -1;
3115
3116 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3117    If INTERNAL is non-zero, the breakpoint number will be populated
3118    from internal_breakpoint_number and that variable decremented.
3119    Otherwise the breakpoint number will be populated from
3120    breakpoint_count and that value incremented.  Internal breakpoints
3121    do not set the internal var bpnum.  */
3122 static void
3123 set_breakpoint_number (int internal, struct breakpoint *b)
3124 {
3125   if (internal)
3126     b->number = internal_breakpoint_number--;
3127   else
3128     {
3129       set_breakpoint_count (breakpoint_count + 1);
3130       b->number = breakpoint_count;
3131     }
3132 }
3133
3134 static struct breakpoint *
3135 create_internal_breakpoint (struct gdbarch *gdbarch,
3136                             CORE_ADDR address, enum bptype type,
3137                             const struct breakpoint_ops *ops)
3138 {
3139   symtab_and_line sal;
3140   sal.pc = address;
3141   sal.section = find_pc_overlay (sal.pc);
3142   sal.pspace = current_program_space;
3143
3144   breakpoint *b = set_raw_breakpoint (gdbarch, sal, type, ops);
3145   b->number = internal_breakpoint_number--;
3146   b->disposition = disp_donttouch;
3147
3148   return b;
3149 }
3150
3151 static const char *const longjmp_names[] =
3152   {
3153     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3154   };
3155 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3156
3157 /* Per-objfile data private to breakpoint.c.  */
3158 struct breakpoint_objfile_data
3159 {
3160   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3161   struct bound_minimal_symbol overlay_msym {};
3162
3163   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3164   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES] {};
3165
3166   /* True if we have looked for longjmp probes.  */
3167   int longjmp_searched = 0;
3168
3169   /* SystemTap probe points for longjmp (if any).  These are non-owning
3170      references.  */
3171   std::vector<probe *> longjmp_probes;
3172
3173   /* Minimal symbol for "std::terminate()" (if any).  */
3174   struct bound_minimal_symbol terminate_msym {};
3175
3176   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3177   struct bound_minimal_symbol exception_msym {};
3178
3179   /* True if we have looked for exception probes.  */
3180   int exception_searched = 0;
3181
3182   /* SystemTap probe points for unwinding (if any).  These are non-owning
3183      references.  */
3184   std::vector<probe *> exception_probes;
3185 };
3186
3187 static const struct objfile_data *breakpoint_objfile_key;
3188
3189 /* Minimal symbol not found sentinel.  */
3190 static struct minimal_symbol msym_not_found;
3191
3192 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3193
3194 static int
3195 msym_not_found_p (const struct minimal_symbol *msym)
3196 {
3197   return msym == &msym_not_found;
3198 }
3199
3200 /* Return per-objfile data needed by breakpoint.c.
3201    Allocate the data if necessary.  */
3202
3203 static struct breakpoint_objfile_data *
3204 get_breakpoint_objfile_data (struct objfile *objfile)
3205 {
3206   struct breakpoint_objfile_data *bp_objfile_data;
3207
3208   bp_objfile_data = ((struct breakpoint_objfile_data *)
3209                      objfile_data (objfile, breakpoint_objfile_key));
3210   if (bp_objfile_data == NULL)
3211     {
3212       bp_objfile_data = new breakpoint_objfile_data ();
3213       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3214     }
3215   return bp_objfile_data;
3216 }
3217
3218 static void
3219 free_breakpoint_objfile_data (struct objfile *obj, void *data)
3220 {
3221   struct breakpoint_objfile_data *bp_objfile_data
3222     = (struct breakpoint_objfile_data *) data;
3223
3224   delete bp_objfile_data;
3225 }
3226
3227 static void
3228 create_overlay_event_breakpoint (void)
3229 {
3230   struct objfile *objfile;
3231   const char *const func_name = "_ovly_debug_event";
3232
3233   ALL_OBJFILES (objfile)
3234     {
3235       struct breakpoint *b;
3236       struct breakpoint_objfile_data *bp_objfile_data;
3237       CORE_ADDR addr;
3238       struct explicit_location explicit_loc;
3239
3240       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3241
3242       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3243         continue;
3244
3245       if (bp_objfile_data->overlay_msym.minsym == NULL)
3246         {
3247           struct bound_minimal_symbol m;
3248
3249           m = lookup_minimal_symbol_text (func_name, objfile);
3250           if (m.minsym == NULL)
3251             {
3252               /* Avoid future lookups in this objfile.  */
3253               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3254               continue;
3255             }
3256           bp_objfile_data->overlay_msym = m;
3257         }
3258
3259       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3260       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3261                                       bp_overlay_event,
3262                                       &internal_breakpoint_ops);
3263       initialize_explicit_location (&explicit_loc);
3264       explicit_loc.function_name = ASTRDUP (func_name);
3265       b->location = new_explicit_location (&explicit_loc);
3266
3267       if (overlay_debugging == ovly_auto)
3268         {
3269           b->enable_state = bp_enabled;
3270           overlay_events_enabled = 1;
3271         }
3272       else
3273        {
3274          b->enable_state = bp_disabled;
3275          overlay_events_enabled = 0;
3276        }
3277     }
3278 }
3279
3280 static void
3281 create_longjmp_master_breakpoint (void)
3282 {
3283   struct program_space *pspace;
3284
3285   scoped_restore_current_program_space restore_pspace;
3286
3287   ALL_PSPACES (pspace)
3288   {
3289     struct objfile *objfile;
3290
3291     set_current_program_space (pspace);
3292
3293     ALL_OBJFILES (objfile)
3294     {
3295       int i;
3296       struct gdbarch *gdbarch;
3297       struct breakpoint_objfile_data *bp_objfile_data;
3298
3299       gdbarch = get_objfile_arch (objfile);
3300
3301       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3302
3303       if (!bp_objfile_data->longjmp_searched)
3304         {
3305           std::vector<probe *> ret
3306             = find_probes_in_objfile (objfile, "libc", "longjmp");
3307
3308           if (!ret.empty ())
3309             {
3310               /* We are only interested in checking one element.  */
3311               probe *p = ret[0];
3312
3313               if (!p->can_evaluate_arguments ())
3314                 {
3315                   /* We cannot use the probe interface here, because it does
3316                      not know how to evaluate arguments.  */
3317                   ret.clear ();
3318                 }
3319             }
3320           bp_objfile_data->longjmp_probes = ret;
3321           bp_objfile_data->longjmp_searched = 1;
3322         }
3323
3324       if (!bp_objfile_data->longjmp_probes.empty ())
3325         {
3326           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3327
3328           for (probe *p : bp_objfile_data->longjmp_probes)
3329             {
3330               struct breakpoint *b;
3331
3332               b = create_internal_breakpoint (gdbarch,
3333                                               p->get_relocated_address (objfile),
3334                                               bp_longjmp_master,
3335                                               &internal_breakpoint_ops);
3336               b->location = new_probe_location ("-probe-stap libc:longjmp");
3337               b->enable_state = bp_disabled;
3338             }
3339
3340           continue;
3341         }
3342
3343       if (!gdbarch_get_longjmp_target_p (gdbarch))
3344         continue;
3345
3346       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3347         {
3348           struct breakpoint *b;
3349           const char *func_name;
3350           CORE_ADDR addr;
3351           struct explicit_location explicit_loc;
3352
3353           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3354             continue;
3355
3356           func_name = longjmp_names[i];
3357           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3358             {
3359               struct bound_minimal_symbol m;
3360
3361               m = lookup_minimal_symbol_text (func_name, objfile);
3362               if (m.minsym == NULL)
3363                 {
3364                   /* Prevent future lookups in this objfile.  */
3365                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3366                   continue;
3367                 }
3368               bp_objfile_data->longjmp_msym[i] = m;
3369             }
3370
3371           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3372           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3373                                           &internal_breakpoint_ops);
3374           initialize_explicit_location (&explicit_loc);
3375           explicit_loc.function_name = ASTRDUP (func_name);
3376           b->location = new_explicit_location (&explicit_loc);
3377           b->enable_state = bp_disabled;
3378         }
3379     }
3380   }
3381 }
3382
3383 /* Create a master std::terminate breakpoint.  */
3384 static void
3385 create_std_terminate_master_breakpoint (void)
3386 {
3387   struct program_space *pspace;
3388   const char *const func_name = "std::terminate()";
3389
3390   scoped_restore_current_program_space restore_pspace;
3391
3392   ALL_PSPACES (pspace)
3393   {
3394     struct objfile *objfile;
3395     CORE_ADDR addr;
3396
3397     set_current_program_space (pspace);
3398
3399     ALL_OBJFILES (objfile)
3400     {
3401       struct breakpoint *b;
3402       struct breakpoint_objfile_data *bp_objfile_data;
3403       struct explicit_location explicit_loc;
3404
3405       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3406
3407       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3408         continue;
3409
3410       if (bp_objfile_data->terminate_msym.minsym == NULL)
3411         {
3412           struct bound_minimal_symbol m;
3413
3414           m = lookup_minimal_symbol (func_name, NULL, objfile);
3415           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3416                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3417             {
3418               /* Prevent future lookups in this objfile.  */
3419               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3420               continue;
3421             }
3422           bp_objfile_data->terminate_msym = m;
3423         }
3424
3425       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3426       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3427                                       bp_std_terminate_master,
3428                                       &internal_breakpoint_ops);
3429       initialize_explicit_location (&explicit_loc);
3430       explicit_loc.function_name = ASTRDUP (func_name);
3431       b->location = new_explicit_location (&explicit_loc);
3432       b->enable_state = bp_disabled;
3433     }
3434   }
3435 }
3436
3437 /* Install a master breakpoint on the unwinder's debug hook.  */
3438
3439 static void
3440 create_exception_master_breakpoint (void)
3441 {
3442   struct objfile *objfile;
3443   const char *const func_name = "_Unwind_DebugHook";
3444
3445   ALL_OBJFILES (objfile)
3446     {
3447       struct breakpoint *b;
3448       struct gdbarch *gdbarch;
3449       struct breakpoint_objfile_data *bp_objfile_data;
3450       CORE_ADDR addr;
3451       struct explicit_location explicit_loc;
3452
3453       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3454
3455       /* We prefer the SystemTap probe point if it exists.  */
3456       if (!bp_objfile_data->exception_searched)
3457         {
3458           std::vector<probe *> ret
3459             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3460
3461           if (!ret.empty ())
3462             {
3463               /* We are only interested in checking one element.  */
3464               probe *p = ret[0];
3465
3466               if (!p->can_evaluate_arguments ())
3467                 {
3468                   /* We cannot use the probe interface here, because it does
3469                      not know how to evaluate arguments.  */
3470                   ret.clear ();
3471                 }
3472             }
3473           bp_objfile_data->exception_probes = ret;
3474           bp_objfile_data->exception_searched = 1;
3475         }
3476
3477       if (!bp_objfile_data->exception_probes.empty ())
3478         {
3479           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3480
3481           for (probe *p : bp_objfile_data->exception_probes)
3482             {
3483               struct breakpoint *b;
3484
3485               b = create_internal_breakpoint (gdbarch,
3486                                               p->get_relocated_address (objfile),
3487                                               bp_exception_master,
3488                                               &internal_breakpoint_ops);
3489               b->location = new_probe_location ("-probe-stap libgcc:unwind");
3490               b->enable_state = bp_disabled;
3491             }
3492
3493           continue;
3494         }
3495
3496       /* Otherwise, try the hook function.  */
3497
3498       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3499         continue;
3500
3501       gdbarch = get_objfile_arch (objfile);
3502
3503       if (bp_objfile_data->exception_msym.minsym == NULL)
3504         {
3505           struct bound_minimal_symbol debug_hook;
3506
3507           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3508           if (debug_hook.minsym == NULL)
3509             {
3510               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3511               continue;
3512             }
3513
3514           bp_objfile_data->exception_msym = debug_hook;
3515         }
3516
3517       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3518       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3519                                                  &current_target);
3520       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3521                                       &internal_breakpoint_ops);
3522       initialize_explicit_location (&explicit_loc);
3523       explicit_loc.function_name = ASTRDUP (func_name);
3524       b->location = new_explicit_location (&explicit_loc);
3525       b->enable_state = bp_disabled;
3526     }
3527 }
3528
3529 /* Does B have a location spec?  */
3530
3531 static int
3532 breakpoint_event_location_empty_p (const struct breakpoint *b)
3533 {
3534   return b->location != NULL && event_location_empty_p (b->location.get ());
3535 }
3536
3537 void
3538 update_breakpoints_after_exec (void)
3539 {
3540   struct breakpoint *b, *b_tmp;
3541   struct bp_location *bploc, **bplocp_tmp;
3542
3543   /* We're about to delete breakpoints from GDB's lists.  If the
3544      INSERTED flag is true, GDB will try to lift the breakpoints by
3545      writing the breakpoints' "shadow contents" back into memory.  The
3546      "shadow contents" are NOT valid after an exec, so GDB should not
3547      do that.  Instead, the target is responsible from marking
3548      breakpoints out as soon as it detects an exec.  We don't do that
3549      here instead, because there may be other attempts to delete
3550      breakpoints after detecting an exec and before reaching here.  */
3551   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3552     if (bploc->pspace == current_program_space)
3553       gdb_assert (!bploc->inserted);
3554
3555   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3556   {
3557     if (b->pspace != current_program_space)
3558       continue;
3559
3560     /* Solib breakpoints must be explicitly reset after an exec().  */
3561     if (b->type == bp_shlib_event)
3562       {
3563         delete_breakpoint (b);
3564         continue;
3565       }
3566
3567     /* JIT breakpoints must be explicitly reset after an exec().  */
3568     if (b->type == bp_jit_event)
3569       {
3570         delete_breakpoint (b);
3571         continue;
3572       }
3573
3574     /* Thread event breakpoints must be set anew after an exec(),
3575        as must overlay event and longjmp master breakpoints.  */
3576     if (b->type == bp_thread_event || b->type == bp_overlay_event
3577         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3578         || b->type == bp_exception_master)
3579       {
3580         delete_breakpoint (b);
3581         continue;
3582       }
3583
3584     /* Step-resume breakpoints are meaningless after an exec().  */
3585     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3586       {
3587         delete_breakpoint (b);
3588         continue;
3589       }
3590
3591     /* Just like single-step breakpoints.  */
3592     if (b->type == bp_single_step)
3593       {
3594         delete_breakpoint (b);
3595         continue;
3596       }
3597
3598     /* Longjmp and longjmp-resume breakpoints are also meaningless
3599        after an exec.  */
3600     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3601         || b->type == bp_longjmp_call_dummy
3602         || b->type == bp_exception || b->type == bp_exception_resume)
3603       {
3604         delete_breakpoint (b);
3605         continue;
3606       }
3607
3608     if (b->type == bp_catchpoint)
3609       {
3610         /* For now, none of the bp_catchpoint breakpoints need to
3611            do anything at this point.  In the future, if some of
3612            the catchpoints need to something, we will need to add
3613            a new method, and call this method from here.  */
3614         continue;
3615       }
3616
3617     /* bp_finish is a special case.  The only way we ought to be able
3618        to see one of these when an exec() has happened, is if the user
3619        caught a vfork, and then said "finish".  Ordinarily a finish just
3620        carries them to the call-site of the current callee, by setting
3621        a temporary bp there and resuming.  But in this case, the finish
3622        will carry them entirely through the vfork & exec.
3623
3624        We don't want to allow a bp_finish to remain inserted now.  But
3625        we can't safely delete it, 'cause finish_command has a handle to
3626        the bp on a bpstat, and will later want to delete it.  There's a
3627        chance (and I've seen it happen) that if we delete the bp_finish
3628        here, that its storage will get reused by the time finish_command
3629        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3630        We really must allow finish_command to delete a bp_finish.
3631
3632        In the absence of a general solution for the "how do we know
3633        it's safe to delete something others may have handles to?"
3634        problem, what we'll do here is just uninsert the bp_finish, and
3635        let finish_command delete it.
3636
3637        (We know the bp_finish is "doomed" in the sense that it's
3638        momentary, and will be deleted as soon as finish_command sees
3639        the inferior stopped.  So it doesn't matter that the bp's
3640        address is probably bogus in the new a.out, unlike e.g., the
3641        solib breakpoints.)  */
3642
3643     if (b->type == bp_finish)
3644       {
3645         continue;
3646       }
3647
3648     /* Without a symbolic address, we have little hope of the
3649        pre-exec() address meaning the same thing in the post-exec()
3650        a.out.  */
3651     if (breakpoint_event_location_empty_p (b))
3652       {
3653         delete_breakpoint (b);
3654         continue;
3655       }
3656   }
3657 }
3658
3659 int
3660 detach_breakpoints (ptid_t ptid)
3661 {
3662   struct bp_location *bl, **blp_tmp;
3663   int val = 0;
3664   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3665   struct inferior *inf = current_inferior ();
3666
3667   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3668     error (_("Cannot detach breakpoints of inferior_ptid"));
3669
3670   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3671   inferior_ptid = ptid;
3672   ALL_BP_LOCATIONS (bl, blp_tmp)
3673   {
3674     if (bl->pspace != inf->pspace)
3675       continue;
3676
3677     /* This function must physically remove breakpoints locations
3678        from the specified ptid, without modifying the breakpoint
3679        package's state.  Locations of type bp_loc_other are only
3680        maintained at GDB side.  So, there is no need to remove
3681        these bp_loc_other locations.  Moreover, removing these
3682        would modify the breakpoint package's state.  */
3683     if (bl->loc_type == bp_loc_other)
3684       continue;
3685
3686     if (bl->inserted)
3687       val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3688   }
3689
3690   return val;
3691 }
3692
3693 /* Remove the breakpoint location BL from the current address space.
3694    Note that this is used to detach breakpoints from a child fork.
3695    When we get here, the child isn't in the inferior list, and neither
3696    do we have objects to represent its address space --- we should
3697    *not* look at bl->pspace->aspace here.  */
3698
3699 static int
3700 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3701 {
3702   int val;
3703
3704   /* BL is never in moribund_locations by our callers.  */
3705   gdb_assert (bl->owner != NULL);
3706
3707   /* The type of none suggests that owner is actually deleted.
3708      This should not ever happen.  */
3709   gdb_assert (bl->owner->type != bp_none);
3710
3711   if (bl->loc_type == bp_loc_software_breakpoint
3712       || bl->loc_type == bp_loc_hardware_breakpoint)
3713     {
3714       /* "Normal" instruction breakpoint: either the standard
3715          trap-instruction bp (bp_breakpoint), or a
3716          bp_hardware_breakpoint.  */
3717
3718       /* First check to see if we have to handle an overlay.  */
3719       if (overlay_debugging == ovly_off
3720           || bl->section == NULL
3721           || !(section_is_overlay (bl->section)))
3722         {
3723           /* No overlay handling: just remove the breakpoint.  */
3724
3725           /* If we're trying to uninsert a memory breakpoint that we
3726              know is set in a dynamic object that is marked
3727              shlib_disabled, then either the dynamic object was
3728              removed with "remove-symbol-file" or with
3729              "nosharedlibrary".  In the former case, we don't know
3730              whether another dynamic object might have loaded over the
3731              breakpoint's address -- the user might well let us know
3732              about it next with add-symbol-file (the whole point of
3733              add-symbol-file is letting the user manually maintain a
3734              list of dynamically loaded objects).  If we have the
3735              breakpoint's shadow memory, that is, this is a software
3736              breakpoint managed by GDB, check whether the breakpoint
3737              is still inserted in memory, to avoid overwriting wrong
3738              code with stale saved shadow contents.  Note that HW
3739              breakpoints don't have shadow memory, as they're
3740              implemented using a mechanism that is not dependent on
3741              being able to modify the target's memory, and as such
3742              they should always be removed.  */
3743           if (bl->shlib_disabled
3744               && bl->target_info.shadow_len != 0
3745               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3746             val = 0;
3747           else
3748             val = bl->owner->ops->remove_location (bl, reason);
3749         }
3750       else
3751         {
3752           /* This breakpoint is in an overlay section.
3753              Did we set a breakpoint at the LMA?  */
3754           if (!overlay_events_enabled)
3755               {
3756                 /* Yes -- overlay event support is not active, so we
3757                    should have set a breakpoint at the LMA.  Remove it.  
3758                 */
3759                 /* Ignore any failures: if the LMA is in ROM, we will
3760                    have already warned when we failed to insert it.  */
3761                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3762                   target_remove_hw_breakpoint (bl->gdbarch,
3763                                                &bl->overlay_target_info);
3764                 else
3765                   target_remove_breakpoint (bl->gdbarch,
3766                                             &bl->overlay_target_info,
3767                                             reason);
3768               }
3769           /* Did we set a breakpoint at the VMA? 
3770              If so, we will have marked the breakpoint 'inserted'.  */
3771           if (bl->inserted)
3772             {
3773               /* Yes -- remove it.  Previously we did not bother to
3774                  remove the breakpoint if the section had been
3775                  unmapped, but let's not rely on that being safe.  We
3776                  don't know what the overlay manager might do.  */
3777
3778               /* However, we should remove *software* breakpoints only
3779                  if the section is still mapped, or else we overwrite
3780                  wrong code with the saved shadow contents.  */
3781               if (bl->loc_type == bp_loc_hardware_breakpoint
3782                   || section_is_mapped (bl->section))
3783                 val = bl->owner->ops->remove_location (bl, reason);
3784               else
3785                 val = 0;
3786             }
3787           else
3788             {
3789               /* No -- not inserted, so no need to remove.  No error.  */
3790               val = 0;
3791             }
3792         }
3793
3794       /* In some cases, we might not be able to remove a breakpoint in
3795          a shared library that has already been removed, but we have
3796          not yet processed the shlib unload event.  Similarly for an
3797          unloaded add-symbol-file object - the user might not yet have
3798          had the chance to remove-symbol-file it.  shlib_disabled will
3799          be set if the library/object has already been removed, but
3800          the breakpoint hasn't been uninserted yet, e.g., after
3801          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3802          always-inserted mode.  */
3803       if (val
3804           && (bl->loc_type == bp_loc_software_breakpoint
3805               && (bl->shlib_disabled
3806                   || solib_name_from_address (bl->pspace, bl->address)
3807                   || shared_objfile_contains_address_p (bl->pspace,
3808                                                         bl->address))))
3809         val = 0;
3810
3811       if (val)
3812         return val;
3813       bl->inserted = (reason == DETACH_BREAKPOINT);
3814     }
3815   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3816     {
3817       gdb_assert (bl->owner->ops != NULL
3818                   && bl->owner->ops->remove_location != NULL);
3819
3820       bl->inserted = (reason == DETACH_BREAKPOINT);
3821       bl->owner->ops->remove_location (bl, reason);
3822
3823       /* Failure to remove any of the hardware watchpoints comes here.  */
3824       if (reason == REMOVE_BREAKPOINT && bl->inserted)
3825         warning (_("Could not remove hardware watchpoint %d."),
3826                  bl->owner->number);
3827     }
3828   else if (bl->owner->type == bp_catchpoint
3829            && breakpoint_enabled (bl->owner)
3830            && !bl->duplicate)
3831     {
3832       gdb_assert (bl->owner->ops != NULL
3833                   && bl->owner->ops->remove_location != NULL);
3834
3835       val = bl->owner->ops->remove_location (bl, reason);
3836       if (val)
3837         return val;
3838
3839       bl->inserted = (reason == DETACH_BREAKPOINT);
3840     }
3841
3842   return 0;
3843 }
3844
3845 static int
3846 remove_breakpoint (struct bp_location *bl)
3847 {
3848   /* BL is never in moribund_locations by our callers.  */
3849   gdb_assert (bl->owner != NULL);
3850
3851   /* The type of none suggests that owner is actually deleted.
3852      This should not ever happen.  */
3853   gdb_assert (bl->owner->type != bp_none);
3854
3855   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3856
3857   switch_to_program_space_and_thread (bl->pspace);
3858
3859   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
3860 }
3861
3862 /* Clear the "inserted" flag in all breakpoints.  */
3863
3864 void
3865 mark_breakpoints_out (void)
3866 {
3867   struct bp_location *bl, **blp_tmp;
3868
3869   ALL_BP_LOCATIONS (bl, blp_tmp)
3870     if (bl->pspace == current_program_space)
3871       bl->inserted = 0;
3872 }
3873
3874 /* Clear the "inserted" flag in all breakpoints and delete any
3875    breakpoints which should go away between runs of the program.
3876
3877    Plus other such housekeeping that has to be done for breakpoints
3878    between runs.
3879
3880    Note: this function gets called at the end of a run (by
3881    generic_mourn_inferior) and when a run begins (by
3882    init_wait_for_inferior).  */
3883
3884
3885
3886 void
3887 breakpoint_init_inferior (enum inf_context context)
3888 {
3889   struct breakpoint *b, *b_tmp;
3890   struct bp_location *bl;
3891   int ix;
3892   struct program_space *pspace = current_program_space;
3893
3894   /* If breakpoint locations are shared across processes, then there's
3895      nothing to do.  */
3896   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3897     return;
3898
3899   mark_breakpoints_out ();
3900
3901   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3902   {
3903     if (b->loc && b->loc->pspace != pspace)
3904       continue;
3905
3906     switch (b->type)
3907       {
3908       case bp_call_dummy:
3909       case bp_longjmp_call_dummy:
3910
3911         /* If the call dummy breakpoint is at the entry point it will
3912            cause problems when the inferior is rerun, so we better get
3913            rid of it.  */
3914
3915       case bp_watchpoint_scope:
3916
3917         /* Also get rid of scope breakpoints.  */
3918
3919       case bp_shlib_event:
3920
3921         /* Also remove solib event breakpoints.  Their addresses may
3922            have changed since the last time we ran the program.
3923            Actually we may now be debugging against different target;
3924            and so the solib backend that installed this breakpoint may
3925            not be used in by the target.  E.g.,
3926
3927            (gdb) file prog-linux
3928            (gdb) run               # native linux target
3929            ...
3930            (gdb) kill
3931            (gdb) file prog-win.exe
3932            (gdb) tar rem :9999     # remote Windows gdbserver.
3933         */
3934
3935       case bp_step_resume:
3936
3937         /* Also remove step-resume breakpoints.  */
3938
3939       case bp_single_step:
3940
3941         /* Also remove single-step breakpoints.  */
3942
3943         delete_breakpoint (b);
3944         break;
3945
3946       case bp_watchpoint:
3947       case bp_hardware_watchpoint:
3948       case bp_read_watchpoint:
3949       case bp_access_watchpoint:
3950         {
3951           struct watchpoint *w = (struct watchpoint *) b;
3952
3953           /* Likewise for watchpoints on local expressions.  */
3954           if (w->exp_valid_block != NULL)
3955             delete_breakpoint (b);
3956           else
3957             {
3958               /* Get rid of existing locations, which are no longer
3959                  valid.  New ones will be created in
3960                  update_watchpoint, when the inferior is restarted.
3961                  The next update_global_location_list call will
3962                  garbage collect them.  */
3963               b->loc = NULL;
3964
3965               if (context == inf_starting)
3966                 {
3967                   /* Reset val field to force reread of starting value in
3968                      insert_breakpoints.  */
3969                   if (w->val)
3970                     value_free (w->val);
3971                   w->val = NULL;
3972                   w->val_valid = 0;
3973                 }
3974             }
3975         }
3976         break;
3977       default:
3978         break;
3979       }
3980   }
3981
3982   /* Get rid of the moribund locations.  */
3983   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3984     decref_bp_location (&bl);
3985   VEC_free (bp_location_p, moribund_locations);
3986 }
3987
3988 /* These functions concern about actual breakpoints inserted in the
3989    target --- to e.g. check if we need to do decr_pc adjustment or if
3990    we need to hop over the bkpt --- so we check for address space
3991    match, not program space.  */
3992
3993 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3994    exists at PC.  It returns ordinary_breakpoint_here if it's an
3995    ordinary breakpoint, or permanent_breakpoint_here if it's a
3996    permanent breakpoint.
3997    - When continuing from a location with an ordinary breakpoint, we
3998      actually single step once before calling insert_breakpoints.
3999    - When continuing from a location with a permanent breakpoint, we
4000      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4001      the target, to advance the PC past the breakpoint.  */
4002
4003 enum breakpoint_here
4004 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4005 {
4006   struct bp_location *bl, **blp_tmp;
4007   int any_breakpoint_here = 0;
4008
4009   ALL_BP_LOCATIONS (bl, blp_tmp)
4010     {
4011       if (bl->loc_type != bp_loc_software_breakpoint
4012           && bl->loc_type != bp_loc_hardware_breakpoint)
4013         continue;
4014
4015       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4016       if ((breakpoint_enabled (bl->owner)
4017            || bl->permanent)
4018           && breakpoint_location_address_match (bl, aspace, pc))
4019         {
4020           if (overlay_debugging 
4021               && section_is_overlay (bl->section)
4022               && !section_is_mapped (bl->section))
4023             continue;           /* unmapped overlay -- can't be a match */
4024           else if (bl->permanent)
4025             return permanent_breakpoint_here;
4026           else
4027             any_breakpoint_here = 1;
4028         }
4029     }
4030
4031   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4032 }
4033
4034 /* See breakpoint.h.  */
4035
4036 int
4037 breakpoint_in_range_p (const address_space *aspace,
4038                        CORE_ADDR addr, ULONGEST len)
4039 {
4040   struct bp_location *bl, **blp_tmp;
4041
4042   ALL_BP_LOCATIONS (bl, blp_tmp)
4043     {
4044       if (bl->loc_type != bp_loc_software_breakpoint
4045           && bl->loc_type != bp_loc_hardware_breakpoint)
4046         continue;
4047
4048       if ((breakpoint_enabled (bl->owner)
4049            || bl->permanent)
4050           && breakpoint_location_address_range_overlap (bl, aspace,
4051                                                         addr, len))
4052         {
4053           if (overlay_debugging
4054               && section_is_overlay (bl->section)
4055               && !section_is_mapped (bl->section))
4056             {
4057               /* Unmapped overlay -- can't be a match.  */
4058               continue;
4059             }
4060
4061           return 1;
4062         }
4063     }
4064
4065   return 0;
4066 }
4067
4068 /* Return true if there's a moribund breakpoint at PC.  */
4069
4070 int
4071 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4072 {
4073   struct bp_location *loc;
4074   int ix;
4075
4076   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4077     if (breakpoint_location_address_match (loc, aspace, pc))
4078       return 1;
4079
4080   return 0;
4081 }
4082
4083 /* Returns non-zero iff BL is inserted at PC, in address space
4084    ASPACE.  */
4085
4086 static int
4087 bp_location_inserted_here_p (struct bp_location *bl,
4088                              const address_space *aspace, CORE_ADDR pc)
4089 {
4090   if (bl->inserted
4091       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4092                                    aspace, pc))
4093     {
4094       if (overlay_debugging
4095           && section_is_overlay (bl->section)
4096           && !section_is_mapped (bl->section))
4097         return 0;               /* unmapped overlay -- can't be a match */
4098       else
4099         return 1;
4100     }
4101   return 0;
4102 }
4103
4104 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4105
4106 int
4107 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4108 {
4109   struct bp_location **blp, **blp_tmp = NULL;
4110
4111   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4112     {
4113       struct bp_location *bl = *blp;
4114
4115       if (bl->loc_type != bp_loc_software_breakpoint
4116           && bl->loc_type != bp_loc_hardware_breakpoint)
4117         continue;
4118
4119       if (bp_location_inserted_here_p (bl, aspace, pc))
4120         return 1;
4121     }
4122   return 0;
4123 }
4124
4125 /* This function returns non-zero iff there is a software breakpoint
4126    inserted at PC.  */
4127
4128 int
4129 software_breakpoint_inserted_here_p (const address_space *aspace,
4130                                      CORE_ADDR pc)
4131 {
4132   struct bp_location **blp, **blp_tmp = NULL;
4133
4134   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4135     {
4136       struct bp_location *bl = *blp;
4137
4138       if (bl->loc_type != bp_loc_software_breakpoint)
4139         continue;
4140
4141       if (bp_location_inserted_here_p (bl, aspace, pc))
4142         return 1;
4143     }
4144
4145   return 0;
4146 }
4147
4148 /* See breakpoint.h.  */
4149
4150 int
4151 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4152                                      CORE_ADDR pc)
4153 {
4154   struct bp_location **blp, **blp_tmp = NULL;
4155
4156   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4157     {
4158       struct bp_location *bl = *blp;
4159
4160       if (bl->loc_type != bp_loc_hardware_breakpoint)
4161         continue;
4162
4163       if (bp_location_inserted_here_p (bl, aspace, pc))
4164         return 1;
4165     }
4166
4167   return 0;
4168 }
4169
4170 int
4171 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4172                                        CORE_ADDR addr, ULONGEST len)
4173 {
4174   struct breakpoint *bpt;
4175
4176   ALL_BREAKPOINTS (bpt)
4177     {
4178       struct bp_location *loc;
4179
4180       if (bpt->type != bp_hardware_watchpoint
4181           && bpt->type != bp_access_watchpoint)
4182         continue;
4183
4184       if (!breakpoint_enabled (bpt))
4185         continue;
4186
4187       for (loc = bpt->loc; loc; loc = loc->next)
4188         if (loc->pspace->aspace == aspace && loc->inserted)
4189           {
4190             CORE_ADDR l, h;
4191
4192             /* Check for intersection.  */
4193             l = std::max<CORE_ADDR> (loc->address, addr);
4194             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4195             if (l < h)
4196               return 1;
4197           }
4198     }
4199   return 0;
4200 }
4201 \f
4202
4203 /* bpstat stuff.  External routines' interfaces are documented
4204    in breakpoint.h.  */
4205
4206 int
4207 is_catchpoint (struct breakpoint *ep)
4208 {
4209   return (ep->type == bp_catchpoint);
4210 }
4211
4212 /* Frees any storage that is part of a bpstat.  Does not walk the
4213    'next' chain.  */
4214
4215 bpstats::~bpstats ()
4216 {
4217   if (old_val != NULL)
4218     value_free (old_val);
4219   if (bp_location_at != NULL)
4220     decref_bp_location (&bp_location_at);
4221 }
4222
4223 /* Clear a bpstat so that it says we are not at any breakpoint.
4224    Also free any storage that is part of a bpstat.  */
4225
4226 void
4227 bpstat_clear (bpstat *bsp)
4228 {
4229   bpstat p;
4230   bpstat q;
4231
4232   if (bsp == 0)
4233     return;
4234   p = *bsp;
4235   while (p != NULL)
4236     {
4237       q = p->next;
4238       delete p;
4239       p = q;
4240     }
4241   *bsp = NULL;
4242 }
4243
4244 bpstats::bpstats (const bpstats &other)
4245   : next (NULL),
4246     bp_location_at (other.bp_location_at),
4247     breakpoint_at (other.breakpoint_at),
4248     commands (other.commands),
4249     old_val (other.old_val),
4250     print (other.print),
4251     stop (other.stop),
4252     print_it (other.print_it)
4253 {
4254   if (old_val != NULL)
4255     {
4256       old_val = value_copy (old_val);
4257       release_value (old_val);
4258     }
4259   incref_bp_location (bp_location_at);
4260 }
4261
4262 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4263    is part of the bpstat is copied as well.  */
4264
4265 bpstat
4266 bpstat_copy (bpstat bs)
4267 {
4268   bpstat p = NULL;
4269   bpstat tmp;
4270   bpstat retval = NULL;
4271
4272   if (bs == NULL)
4273     return bs;
4274
4275   for (; bs != NULL; bs = bs->next)
4276     {
4277       tmp = new bpstats (*bs);
4278
4279       if (p == NULL)
4280         /* This is the first thing in the chain.  */
4281         retval = tmp;
4282       else
4283         p->next = tmp;
4284       p = tmp;
4285     }
4286   p->next = NULL;
4287   return retval;
4288 }
4289
4290 /* Find the bpstat associated with this breakpoint.  */
4291
4292 bpstat
4293 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4294 {
4295   if (bsp == NULL)
4296     return NULL;
4297
4298   for (; bsp != NULL; bsp = bsp->next)
4299     {
4300       if (bsp->breakpoint_at == breakpoint)
4301         return bsp;
4302     }
4303   return NULL;
4304 }
4305
4306 /* See breakpoint.h.  */
4307
4308 int
4309 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4310 {
4311   for (; bsp != NULL; bsp = bsp->next)
4312     {
4313       if (bsp->breakpoint_at == NULL)
4314         {
4315           /* A moribund location can never explain a signal other than
4316              GDB_SIGNAL_TRAP.  */
4317           if (sig == GDB_SIGNAL_TRAP)
4318             return 1;
4319         }
4320       else
4321         {
4322           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4323                                                         sig))
4324             return 1;
4325         }
4326     }
4327
4328   return 0;
4329 }
4330
4331 /* Put in *NUM the breakpoint number of the first breakpoint we are
4332    stopped at.  *BSP upon return is a bpstat which points to the
4333    remaining breakpoints stopped at (but which is not guaranteed to be
4334    good for anything but further calls to bpstat_num).
4335
4336    Return 0 if passed a bpstat which does not indicate any breakpoints.
4337    Return -1 if stopped at a breakpoint that has been deleted since
4338    we set it.
4339    Return 1 otherwise.  */
4340
4341 int
4342 bpstat_num (bpstat *bsp, int *num)
4343 {
4344   struct breakpoint *b;
4345
4346   if ((*bsp) == NULL)
4347     return 0;                   /* No more breakpoint values */
4348
4349   /* We assume we'll never have several bpstats that correspond to a
4350      single breakpoint -- otherwise, this function might return the
4351      same number more than once and this will look ugly.  */
4352   b = (*bsp)->breakpoint_at;
4353   *bsp = (*bsp)->next;
4354   if (b == NULL)
4355     return -1;                  /* breakpoint that's been deleted since */
4356
4357   *num = b->number;             /* We have its number */
4358   return 1;
4359 }
4360
4361 /* See breakpoint.h.  */
4362
4363 void
4364 bpstat_clear_actions (void)
4365 {
4366   struct thread_info *tp;
4367   bpstat bs;
4368
4369   if (ptid_equal (inferior_ptid, null_ptid))
4370     return;
4371
4372   tp = find_thread_ptid (inferior_ptid);
4373   if (tp == NULL)
4374     return;
4375
4376   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4377     {
4378       bs->commands = NULL;
4379
4380       if (bs->old_val != NULL)
4381         {
4382           value_free (bs->old_val);
4383           bs->old_val = NULL;
4384         }
4385     }
4386 }
4387
4388 /* Called when a command is about to proceed the inferior.  */
4389
4390 static void
4391 breakpoint_about_to_proceed (void)
4392 {
4393   if (!ptid_equal (inferior_ptid, null_ptid))
4394     {
4395       struct thread_info *tp = inferior_thread ();
4396
4397       /* Allow inferior function calls in breakpoint commands to not
4398          interrupt the command list.  When the call finishes
4399          successfully, the inferior will be standing at the same
4400          breakpoint as if nothing happened.  */
4401       if (tp->control.in_infcall)
4402         return;
4403     }
4404
4405   breakpoint_proceeded = 1;
4406 }
4407
4408 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4409    or its equivalent.  */
4410
4411 static int
4412 command_line_is_silent (struct command_line *cmd)
4413 {
4414   return cmd && (strcmp ("silent", cmd->line) == 0);
4415 }
4416
4417 /* Execute all the commands associated with all the breakpoints at
4418    this location.  Any of these commands could cause the process to
4419    proceed beyond this point, etc.  We look out for such changes by
4420    checking the global "breakpoint_proceeded" after each command.
4421
4422    Returns true if a breakpoint command resumed the inferior.  In that
4423    case, it is the caller's responsibility to recall it again with the
4424    bpstat of the current thread.  */
4425
4426 static int
4427 bpstat_do_actions_1 (bpstat *bsp)
4428 {
4429   bpstat bs;
4430   int again = 0;
4431
4432   /* Avoid endless recursion if a `source' command is contained
4433      in bs->commands.  */
4434   if (executing_breakpoint_commands)
4435     return 0;
4436
4437   scoped_restore save_executing
4438     = make_scoped_restore (&executing_breakpoint_commands, 1);
4439
4440   scoped_restore preventer = prevent_dont_repeat ();
4441
4442   /* This pointer will iterate over the list of bpstat's.  */
4443   bs = *bsp;
4444
4445   breakpoint_proceeded = 0;
4446   for (; bs != NULL; bs = bs->next)
4447     {
4448       struct command_line *cmd = NULL;
4449
4450       /* Take ownership of the BSP's command tree, if it has one.
4451
4452          The command tree could legitimately contain commands like
4453          'step' and 'next', which call clear_proceed_status, which
4454          frees stop_bpstat's command tree.  To make sure this doesn't
4455          free the tree we're executing out from under us, we need to
4456          take ownership of the tree ourselves.  Since a given bpstat's
4457          commands are only executed once, we don't need to copy it; we
4458          can clear the pointer in the bpstat, and make sure we free
4459          the tree when we're done.  */
4460       counted_command_line ccmd = bs->commands;
4461       bs->commands = NULL;
4462       if (ccmd != NULL)
4463         cmd = ccmd.get ();
4464       if (command_line_is_silent (cmd))
4465         {
4466           /* The action has been already done by bpstat_stop_status.  */
4467           cmd = cmd->next;
4468         }
4469
4470       while (cmd != NULL)
4471         {
4472           execute_control_command (cmd);
4473
4474           if (breakpoint_proceeded)
4475             break;
4476           else
4477             cmd = cmd->next;
4478         }
4479
4480       if (breakpoint_proceeded)
4481         {
4482           if (current_ui->async)
4483             /* If we are in async mode, then the target might be still
4484                running, not stopped at any breakpoint, so nothing for
4485                us to do here -- just return to the event loop.  */
4486             ;
4487           else
4488             /* In sync mode, when execute_control_command returns
4489                we're already standing on the next breakpoint.
4490                Breakpoint commands for that stop were not run, since
4491                execute_command does not run breakpoint commands --
4492                only command_line_handler does, but that one is not
4493                involved in execution of breakpoint commands.  So, we
4494                can now execute breakpoint commands.  It should be
4495                noted that making execute_command do bpstat actions is
4496                not an option -- in this case we'll have recursive
4497                invocation of bpstat for each breakpoint with a
4498                command, and can easily blow up GDB stack.  Instead, we
4499                return true, which will trigger the caller to recall us
4500                with the new stop_bpstat.  */
4501             again = 1;
4502           break;
4503         }
4504     }
4505   return again;
4506 }
4507
4508 void
4509 bpstat_do_actions (void)
4510 {
4511   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4512
4513   /* Do any commands attached to breakpoint we are stopped at.  */
4514   while (!ptid_equal (inferior_ptid, null_ptid)
4515          && target_has_execution
4516          && !is_exited (inferior_ptid)
4517          && !is_executing (inferior_ptid))
4518     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4519        and only return when it is stopped at the next breakpoint, we
4520        keep doing breakpoint actions until it returns false to
4521        indicate the inferior was not resumed.  */
4522     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4523       break;
4524
4525   discard_cleanups (cleanup_if_error);
4526 }
4527
4528 /* Print out the (old or new) value associated with a watchpoint.  */
4529
4530 static void
4531 watchpoint_value_print (struct value *val, struct ui_file *stream)
4532 {
4533   if (val == NULL)
4534     fprintf_unfiltered (stream, _("<unreadable>"));
4535   else
4536     {
4537       struct value_print_options opts;
4538       get_user_print_options (&opts);
4539       value_print (val, stream, &opts);
4540     }
4541 }
4542
4543 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4544    debugging multiple threads.  */
4545
4546 void
4547 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4548 {
4549   if (uiout->is_mi_like_p ())
4550     return;
4551
4552   uiout->text ("\n");
4553
4554   if (show_thread_that_caused_stop ())
4555     {
4556       const char *name;
4557       struct thread_info *thr = inferior_thread ();
4558
4559       uiout->text ("Thread ");
4560       uiout->field_fmt ("thread-id", "%s", print_thread_id (thr));
4561
4562       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4563       if (name != NULL)
4564         {
4565           uiout->text (" \"");
4566           uiout->field_fmt ("name", "%s", name);
4567           uiout->text ("\"");
4568         }
4569
4570       uiout->text (" hit ");
4571     }
4572 }
4573
4574 /* Generic routine for printing messages indicating why we
4575    stopped.  The behavior of this function depends on the value
4576    'print_it' in the bpstat structure.  Under some circumstances we
4577    may decide not to print anything here and delegate the task to
4578    normal_stop().  */
4579
4580 static enum print_stop_action
4581 print_bp_stop_message (bpstat bs)
4582 {
4583   switch (bs->print_it)
4584     {
4585     case print_it_noop:
4586       /* Nothing should be printed for this bpstat entry.  */
4587       return PRINT_UNKNOWN;
4588       break;
4589
4590     case print_it_done:
4591       /* We still want to print the frame, but we already printed the
4592          relevant messages.  */
4593       return PRINT_SRC_AND_LOC;
4594       break;
4595
4596     case print_it_normal:
4597       {
4598         struct breakpoint *b = bs->breakpoint_at;
4599
4600         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4601            which has since been deleted.  */
4602         if (b == NULL)
4603           return PRINT_UNKNOWN;
4604
4605         /* Normal case.  Call the breakpoint's print_it method.  */
4606         return b->ops->print_it (bs);
4607       }
4608       break;
4609
4610     default:
4611       internal_error (__FILE__, __LINE__,
4612                       _("print_bp_stop_message: unrecognized enum value"));
4613       break;
4614     }
4615 }
4616
4617 /* A helper function that prints a shared library stopped event.  */
4618
4619 static void
4620 print_solib_event (int is_catchpoint)
4621 {
4622   int any_deleted
4623     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4624   int any_added
4625     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4626
4627   if (!is_catchpoint)
4628     {
4629       if (any_added || any_deleted)
4630         current_uiout->text (_("Stopped due to shared library event:\n"));
4631       else
4632         current_uiout->text (_("Stopped due to shared library event (no "
4633                                "libraries added or removed)\n"));
4634     }
4635
4636   if (current_uiout->is_mi_like_p ())
4637     current_uiout->field_string ("reason",
4638                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4639
4640   if (any_deleted)
4641     {
4642       char *name;
4643       int ix;
4644
4645       current_uiout->text (_("  Inferior unloaded "));
4646       ui_out_emit_list list_emitter (current_uiout, "removed");
4647       for (ix = 0;
4648            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4649                         ix, name);
4650            ++ix)
4651         {
4652           if (ix > 0)
4653             current_uiout->text ("    ");
4654           current_uiout->field_string ("library", name);
4655           current_uiout->text ("\n");
4656         }
4657     }
4658
4659   if (any_added)
4660     {
4661       struct so_list *iter;
4662       int ix;
4663
4664       current_uiout->text (_("  Inferior loaded "));
4665       ui_out_emit_list list_emitter (current_uiout, "added");
4666       for (ix = 0;
4667            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4668                         ix, iter);
4669            ++ix)
4670         {
4671           if (ix > 0)
4672             current_uiout->text ("    ");
4673           current_uiout->field_string ("library", iter->so_name);
4674           current_uiout->text ("\n");
4675         }
4676     }
4677 }
4678
4679 /* Print a message indicating what happened.  This is called from
4680    normal_stop().  The input to this routine is the head of the bpstat
4681    list - a list of the eventpoints that caused this stop.  KIND is
4682    the target_waitkind for the stopping event.  This
4683    routine calls the generic print routine for printing a message
4684    about reasons for stopping.  This will print (for example) the
4685    "Breakpoint n," part of the output.  The return value of this
4686    routine is one of:
4687
4688    PRINT_UNKNOWN: Means we printed nothing.
4689    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4690    code to print the location.  An example is 
4691    "Breakpoint 1, " which should be followed by
4692    the location.
4693    PRINT_SRC_ONLY: Means we printed something, but there is no need
4694    to also print the location part of the message.
4695    An example is the catch/throw messages, which
4696    don't require a location appended to the end.
4697    PRINT_NOTHING: We have done some printing and we don't need any 
4698    further info to be printed.  */
4699
4700 enum print_stop_action
4701 bpstat_print (bpstat bs, int kind)
4702 {
4703   enum print_stop_action val;
4704
4705   /* Maybe another breakpoint in the chain caused us to stop.
4706      (Currently all watchpoints go on the bpstat whether hit or not.
4707      That probably could (should) be changed, provided care is taken
4708      with respect to bpstat_explains_signal).  */
4709   for (; bs; bs = bs->next)
4710     {
4711       val = print_bp_stop_message (bs);
4712       if (val == PRINT_SRC_ONLY 
4713           || val == PRINT_SRC_AND_LOC 
4714           || val == PRINT_NOTHING)
4715         return val;
4716     }
4717
4718   /* If we had hit a shared library event breakpoint,
4719      print_bp_stop_message would print out this message.  If we hit an
4720      OS-level shared library event, do the same thing.  */
4721   if (kind == TARGET_WAITKIND_LOADED)
4722     {
4723       print_solib_event (0);
4724       return PRINT_NOTHING;
4725     }
4726
4727   /* We reached the end of the chain, or we got a null BS to start
4728      with and nothing was printed.  */
4729   return PRINT_UNKNOWN;
4730 }
4731
4732 /* Evaluate the boolean expression EXP and return the result.  */
4733
4734 static bool
4735 breakpoint_cond_eval (expression *exp)
4736 {
4737   struct value *mark = value_mark ();
4738   bool res = value_true (evaluate_expression (exp));
4739
4740   value_free_to_mark (mark);
4741   return res;
4742 }
4743
4744 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4745
4746 bpstats::bpstats (struct bp_location *bl, bpstat **bs_link_pointer)
4747   : next (NULL),
4748     bp_location_at (bl),
4749     breakpoint_at (bl->owner),
4750     commands (NULL),
4751     old_val (NULL),
4752     print (0),
4753     stop (0),
4754     print_it (print_it_normal)
4755 {
4756   incref_bp_location (bl);
4757   **bs_link_pointer = this;
4758   *bs_link_pointer = &next;
4759 }
4760
4761 bpstats::bpstats ()
4762   : next (NULL),
4763     bp_location_at (NULL),
4764     breakpoint_at (NULL),
4765     commands (NULL),
4766     old_val (NULL),
4767     print (0),
4768     stop (0),
4769     print_it (print_it_normal)
4770 {
4771 }
4772 \f
4773 /* The target has stopped with waitstatus WS.  Check if any hardware
4774    watchpoints have triggered, according to the target.  */
4775
4776 int
4777 watchpoints_triggered (struct target_waitstatus *ws)
4778 {
4779   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4780   CORE_ADDR addr;
4781   struct breakpoint *b;
4782
4783   if (!stopped_by_watchpoint)
4784     {
4785       /* We were not stopped by a watchpoint.  Mark all watchpoints
4786          as not triggered.  */
4787       ALL_BREAKPOINTS (b)
4788         if (is_hardware_watchpoint (b))
4789           {
4790             struct watchpoint *w = (struct watchpoint *) b;
4791
4792             w->watchpoint_triggered = watch_triggered_no;
4793           }
4794
4795       return 0;
4796     }
4797
4798   if (!target_stopped_data_address (&current_target, &addr))
4799     {
4800       /* We were stopped by a watchpoint, but we don't know where.
4801          Mark all watchpoints as unknown.  */
4802       ALL_BREAKPOINTS (b)
4803         if (is_hardware_watchpoint (b))
4804           {
4805             struct watchpoint *w = (struct watchpoint *) b;
4806
4807             w->watchpoint_triggered = watch_triggered_unknown;
4808           }
4809
4810       return 1;
4811     }
4812
4813   /* The target could report the data address.  Mark watchpoints
4814      affected by this data address as triggered, and all others as not
4815      triggered.  */
4816
4817   ALL_BREAKPOINTS (b)
4818     if (is_hardware_watchpoint (b))
4819       {
4820         struct watchpoint *w = (struct watchpoint *) b;
4821         struct bp_location *loc;
4822
4823         w->watchpoint_triggered = watch_triggered_no;
4824         for (loc = b->loc; loc; loc = loc->next)
4825           {
4826             if (is_masked_watchpoint (b))
4827               {
4828                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4829                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4830
4831                 if (newaddr == start)
4832                   {
4833                     w->watchpoint_triggered = watch_triggered_yes;
4834                     break;
4835                   }
4836               }
4837             /* Exact match not required.  Within range is sufficient.  */
4838             else if (target_watchpoint_addr_within_range (&current_target,
4839                                                          addr, loc->address,
4840                                                          loc->length))
4841               {
4842                 w->watchpoint_triggered = watch_triggered_yes;
4843                 break;
4844               }
4845           }
4846       }
4847
4848   return 1;
4849 }
4850
4851 /* Possible return values for watchpoint_check.  */
4852 enum wp_check_result
4853   {
4854     /* The watchpoint has been deleted.  */
4855     WP_DELETED = 1,
4856
4857     /* The value has changed.  */
4858     WP_VALUE_CHANGED = 2,
4859
4860     /* The value has not changed.  */
4861     WP_VALUE_NOT_CHANGED = 3,
4862
4863     /* Ignore this watchpoint, no matter if the value changed or not.  */
4864     WP_IGNORE = 4,
4865   };
4866
4867 #define BP_TEMPFLAG 1
4868 #define BP_HARDWAREFLAG 2
4869
4870 /* Evaluate watchpoint condition expression and check if its value
4871    changed.  */
4872
4873 static wp_check_result
4874 watchpoint_check (bpstat bs)
4875 {
4876   struct watchpoint *b;
4877   struct frame_info *fr;
4878   int within_current_scope;
4879
4880   /* BS is built from an existing struct breakpoint.  */
4881   gdb_assert (bs->breakpoint_at != NULL);
4882   b = (struct watchpoint *) bs->breakpoint_at;
4883
4884   /* If this is a local watchpoint, we only want to check if the
4885      watchpoint frame is in scope if the current thread is the thread
4886      that was used to create the watchpoint.  */
4887   if (!watchpoint_in_thread_scope (b))
4888     return WP_IGNORE;
4889
4890   if (b->exp_valid_block == NULL)
4891     within_current_scope = 1;
4892   else
4893     {
4894       struct frame_info *frame = get_current_frame ();
4895       struct gdbarch *frame_arch = get_frame_arch (frame);
4896       CORE_ADDR frame_pc = get_frame_pc (frame);
4897
4898       /* stack_frame_destroyed_p() returns a non-zero value if we're
4899          still in the function but the stack frame has already been
4900          invalidated.  Since we can't rely on the values of local
4901          variables after the stack has been destroyed, we are treating
4902          the watchpoint in that state as `not changed' without further
4903          checking.  Don't mark watchpoints as changed if the current
4904          frame is in an epilogue - even if they are in some other
4905          frame, our view of the stack is likely to be wrong and
4906          frame_find_by_id could error out.  */
4907       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
4908         return WP_IGNORE;
4909
4910       fr = frame_find_by_id (b->watchpoint_frame);
4911       within_current_scope = (fr != NULL);
4912
4913       /* If we've gotten confused in the unwinder, we might have
4914          returned a frame that can't describe this variable.  */
4915       if (within_current_scope)
4916         {
4917           struct symbol *function;
4918
4919           function = get_frame_function (fr);
4920           if (function == NULL
4921               || !contained_in (b->exp_valid_block,
4922                                 SYMBOL_BLOCK_VALUE (function)))
4923             within_current_scope = 0;
4924         }
4925
4926       if (within_current_scope)
4927         /* If we end up stopping, the current frame will get selected
4928            in normal_stop.  So this call to select_frame won't affect
4929            the user.  */
4930         select_frame (fr);
4931     }
4932
4933   if (within_current_scope)
4934     {
4935       /* We use value_{,free_to_}mark because it could be a *long*
4936          time before we return to the command level and call
4937          free_all_values.  We can't call free_all_values because we
4938          might be in the middle of evaluating a function call.  */
4939
4940       int pc = 0;
4941       struct value *mark;
4942       struct value *new_val;
4943
4944       if (is_masked_watchpoint (b))
4945         /* Since we don't know the exact trigger address (from
4946            stopped_data_address), just tell the user we've triggered
4947            a mask watchpoint.  */
4948         return WP_VALUE_CHANGED;
4949
4950       mark = value_mark ();
4951       fetch_subexp_value (b->exp.get (), &pc, &new_val, NULL, NULL, 0);
4952
4953       if (b->val_bitsize != 0)
4954         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
4955
4956       /* We use value_equal_contents instead of value_equal because
4957          the latter coerces an array to a pointer, thus comparing just
4958          the address of the array instead of its contents.  This is
4959          not what we want.  */
4960       if ((b->val != NULL) != (new_val != NULL)
4961           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4962         {
4963           if (new_val != NULL)
4964             {
4965               release_value (new_val);
4966               value_free_to_mark (mark);
4967             }
4968           bs->old_val = b->val;
4969           b->val = new_val;
4970           b->val_valid = 1;
4971           return WP_VALUE_CHANGED;
4972         }
4973       else
4974         {
4975           /* Nothing changed.  */
4976           value_free_to_mark (mark);
4977           return WP_VALUE_NOT_CHANGED;
4978         }
4979     }
4980   else
4981     {
4982       /* This seems like the only logical thing to do because
4983          if we temporarily ignored the watchpoint, then when
4984          we reenter the block in which it is valid it contains
4985          garbage (in the case of a function, it may have two
4986          garbage values, one before and one after the prologue).
4987          So we can't even detect the first assignment to it and
4988          watch after that (since the garbage may or may not equal
4989          the first value assigned).  */
4990       /* We print all the stop information in
4991          breakpoint_ops->print_it, but in this case, by the time we
4992          call breakpoint_ops->print_it this bp will be deleted
4993          already.  So we have no choice but print the information
4994          here.  */
4995
4996       SWITCH_THRU_ALL_UIS ()
4997         {
4998           struct ui_out *uiout = current_uiout;
4999
5000           if (uiout->is_mi_like_p ())
5001             uiout->field_string
5002               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5003           uiout->text ("\nWatchpoint ");
5004           uiout->field_int ("wpnum", b->number);
5005           uiout->text (" deleted because the program has left the block in\n"
5006                        "which its expression is valid.\n");
5007         }
5008
5009       /* Make sure the watchpoint's commands aren't executed.  */
5010       b->commands = NULL;
5011       watchpoint_del_at_next_stop (b);
5012
5013       return WP_DELETED;
5014     }
5015 }
5016
5017 /* Return true if it looks like target has stopped due to hitting
5018    breakpoint location BL.  This function does not check if we should
5019    stop, only if BL explains the stop.  */
5020
5021 static int
5022 bpstat_check_location (const struct bp_location *bl,
5023                        const address_space *aspace, CORE_ADDR bp_addr,
5024                        const struct target_waitstatus *ws)
5025 {
5026   struct breakpoint *b = bl->owner;
5027
5028   /* BL is from an existing breakpoint.  */
5029   gdb_assert (b != NULL);
5030
5031   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5032 }
5033
5034 /* Determine if the watched values have actually changed, and we
5035    should stop.  If not, set BS->stop to 0.  */
5036
5037 static void
5038 bpstat_check_watchpoint (bpstat bs)
5039 {
5040   const struct bp_location *bl;
5041   struct watchpoint *b;
5042
5043   /* BS is built for existing struct breakpoint.  */
5044   bl = bs->bp_location_at;
5045   gdb_assert (bl != NULL);
5046   b = (struct watchpoint *) bs->breakpoint_at;
5047   gdb_assert (b != NULL);
5048
5049     {
5050       int must_check_value = 0;
5051       
5052       if (b->type == bp_watchpoint)
5053         /* For a software watchpoint, we must always check the
5054            watched value.  */
5055         must_check_value = 1;
5056       else if (b->watchpoint_triggered == watch_triggered_yes)
5057         /* We have a hardware watchpoint (read, write, or access)
5058            and the target earlier reported an address watched by
5059            this watchpoint.  */
5060         must_check_value = 1;
5061       else if (b->watchpoint_triggered == watch_triggered_unknown
5062                && b->type == bp_hardware_watchpoint)
5063         /* We were stopped by a hardware watchpoint, but the target could
5064            not report the data address.  We must check the watchpoint's
5065            value.  Access and read watchpoints are out of luck; without
5066            a data address, we can't figure it out.  */
5067         must_check_value = 1;
5068
5069       if (must_check_value)
5070         {
5071           wp_check_result e;
5072
5073           TRY
5074             {
5075               e = watchpoint_check (bs);
5076             }
5077           CATCH (ex, RETURN_MASK_ALL)
5078             {
5079               exception_fprintf (gdb_stderr, ex,
5080                                  "Error evaluating expression "
5081                                  "for watchpoint %d\n",
5082                                  b->number);
5083
5084               SWITCH_THRU_ALL_UIS ()
5085                 {
5086                   printf_filtered (_("Watchpoint %d deleted.\n"),
5087                                    b->number);
5088                 }
5089               watchpoint_del_at_next_stop (b);
5090               e = WP_DELETED;
5091             }
5092           END_CATCH
5093
5094           switch (e)
5095             {
5096             case WP_DELETED:
5097               /* We've already printed what needs to be printed.  */
5098               bs->print_it = print_it_done;
5099               /* Stop.  */
5100               break;
5101             case WP_IGNORE:
5102               bs->print_it = print_it_noop;
5103               bs->stop = 0;
5104               break;
5105             case WP_VALUE_CHANGED:
5106               if (b->type == bp_read_watchpoint)
5107                 {
5108                   /* There are two cases to consider here:
5109
5110                      1. We're watching the triggered memory for reads.
5111                      In that case, trust the target, and always report
5112                      the watchpoint hit to the user.  Even though
5113                      reads don't cause value changes, the value may
5114                      have changed since the last time it was read, and
5115                      since we're not trapping writes, we will not see
5116                      those, and as such we should ignore our notion of
5117                      old value.
5118
5119                      2. We're watching the triggered memory for both
5120                      reads and writes.  There are two ways this may
5121                      happen:
5122
5123                      2.1. This is a target that can't break on data
5124                      reads only, but can break on accesses (reads or
5125                      writes), such as e.g., x86.  We detect this case
5126                      at the time we try to insert read watchpoints.
5127
5128                      2.2. Otherwise, the target supports read
5129                      watchpoints, but, the user set an access or write
5130                      watchpoint watching the same memory as this read
5131                      watchpoint.
5132
5133                      If we're watching memory writes as well as reads,
5134                      ignore watchpoint hits when we find that the
5135                      value hasn't changed, as reads don't cause
5136                      changes.  This still gives false positives when
5137                      the program writes the same value to memory as
5138                      what there was already in memory (we will confuse
5139                      it for a read), but it's much better than
5140                      nothing.  */
5141
5142                   int other_write_watchpoint = 0;
5143
5144                   if (bl->watchpoint_type == hw_read)
5145                     {
5146                       struct breakpoint *other_b;
5147
5148                       ALL_BREAKPOINTS (other_b)
5149                         if (other_b->type == bp_hardware_watchpoint
5150                             || other_b->type == bp_access_watchpoint)
5151                           {
5152                             struct watchpoint *other_w =
5153                               (struct watchpoint *) other_b;
5154
5155                             if (other_w->watchpoint_triggered
5156                                 == watch_triggered_yes)
5157                               {
5158                                 other_write_watchpoint = 1;
5159                                 break;
5160                               }
5161                           }
5162                     }
5163
5164                   if (other_write_watchpoint
5165                       || bl->watchpoint_type == hw_access)
5166                     {
5167                       /* We're watching the same memory for writes,
5168                          and the value changed since the last time we
5169                          updated it, so this trap must be for a write.
5170                          Ignore it.  */
5171                       bs->print_it = print_it_noop;
5172                       bs->stop = 0;
5173                     }
5174                 }
5175               break;
5176             case WP_VALUE_NOT_CHANGED:
5177               if (b->type == bp_hardware_watchpoint
5178                   || b->type == bp_watchpoint)
5179                 {
5180                   /* Don't stop: write watchpoints shouldn't fire if
5181                      the value hasn't changed.  */
5182                   bs->print_it = print_it_noop;
5183                   bs->stop = 0;
5184                 }
5185               /* Stop.  */
5186               break;
5187             default:
5188               /* Can't happen.  */
5189               break;
5190             }
5191         }
5192       else      /* must_check_value == 0 */
5193         {
5194           /* This is a case where some watchpoint(s) triggered, but
5195              not at the address of this watchpoint, or else no
5196              watchpoint triggered after all.  So don't print
5197              anything for this watchpoint.  */
5198           bs->print_it = print_it_noop;
5199           bs->stop = 0;
5200         }
5201     }
5202 }
5203
5204 /* For breakpoints that are currently marked as telling gdb to stop,
5205    check conditions (condition proper, frame, thread and ignore count)
5206    of breakpoint referred to by BS.  If we should not stop for this
5207    breakpoint, set BS->stop to 0.  */
5208
5209 static void
5210 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5211 {
5212   const struct bp_location *bl;
5213   struct breakpoint *b;
5214   /* Assume stop.  */
5215   bool condition_result = true;
5216   struct expression *cond;
5217
5218   gdb_assert (bs->stop);
5219
5220   /* BS is built for existing struct breakpoint.  */
5221   bl = bs->bp_location_at;
5222   gdb_assert (bl != NULL);
5223   b = bs->breakpoint_at;
5224   gdb_assert (b != NULL);
5225
5226   /* Even if the target evaluated the condition on its end and notified GDB, we
5227      need to do so again since GDB does not know if we stopped due to a
5228      breakpoint or a single step breakpoint.  */
5229
5230   if (frame_id_p (b->frame_id)
5231       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5232     {
5233       bs->stop = 0;
5234       return;
5235     }
5236
5237   /* If this is a thread/task-specific breakpoint, don't waste cpu
5238      evaluating the condition if this isn't the specified
5239      thread/task.  */
5240   if ((b->thread != -1 && b->thread != ptid_to_global_thread_id (ptid))
5241       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5242
5243     {
5244       bs->stop = 0;
5245       return;
5246     }
5247
5248   /* Evaluate extension language breakpoints that have a "stop" method
5249      implemented.  */
5250   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5251
5252   if (is_watchpoint (b))
5253     {
5254       struct watchpoint *w = (struct watchpoint *) b;
5255
5256       cond = w->cond_exp.get ();
5257     }
5258   else
5259     cond = bl->cond.get ();
5260
5261   if (cond && b->disposition != disp_del_at_next_stop)
5262     {
5263       int within_current_scope = 1;
5264       struct watchpoint * w;
5265
5266       /* We use value_mark and value_free_to_mark because it could
5267          be a long time before we return to the command level and
5268          call free_all_values.  We can't call free_all_values
5269          because we might be in the middle of evaluating a
5270          function call.  */
5271       struct value *mark = value_mark ();
5272
5273       if (is_watchpoint (b))
5274         w = (struct watchpoint *) b;
5275       else
5276         w = NULL;
5277
5278       /* Need to select the frame, with all that implies so that
5279          the conditions will have the right context.  Because we
5280          use the frame, we will not see an inlined function's
5281          variables when we arrive at a breakpoint at the start
5282          of the inlined function; the current frame will be the
5283          call site.  */
5284       if (w == NULL || w->cond_exp_valid_block == NULL)
5285         select_frame (get_current_frame ());
5286       else
5287         {
5288           struct frame_info *frame;
5289
5290           /* For local watchpoint expressions, which particular
5291              instance of a local is being watched matters, so we
5292              keep track of the frame to evaluate the expression
5293              in.  To evaluate the condition however, it doesn't
5294              really matter which instantiation of the function
5295              where the condition makes sense triggers the
5296              watchpoint.  This allows an expression like "watch
5297              global if q > 10" set in `func', catch writes to
5298              global on all threads that call `func', or catch
5299              writes on all recursive calls of `func' by a single
5300              thread.  We simply always evaluate the condition in
5301              the innermost frame that's executing where it makes
5302              sense to evaluate the condition.  It seems
5303              intuitive.  */
5304           frame = block_innermost_frame (w->cond_exp_valid_block);
5305           if (frame != NULL)
5306             select_frame (frame);
5307           else
5308             within_current_scope = 0;
5309         }
5310       if (within_current_scope)
5311         {
5312           TRY
5313             {
5314               condition_result = breakpoint_cond_eval (cond);
5315             }
5316           CATCH (ex, RETURN_MASK_ALL)
5317             {
5318               exception_fprintf (gdb_stderr, ex,
5319                                  "Error in testing breakpoint condition:\n");
5320             }
5321           END_CATCH
5322         }
5323       else
5324         {
5325           warning (_("Watchpoint condition cannot be tested "
5326                      "in the current scope"));
5327           /* If we failed to set the right context for this
5328              watchpoint, unconditionally report it.  */
5329         }
5330       /* FIXME-someday, should give breakpoint #.  */
5331       value_free_to_mark (mark);
5332     }
5333
5334   if (cond && !condition_result)
5335     {
5336       bs->stop = 0;
5337     }
5338   else if (b->ignore_count > 0)
5339     {
5340       b->ignore_count--;
5341       bs->stop = 0;
5342       /* Increase the hit count even though we don't stop.  */
5343       ++(b->hit_count);
5344       observer_notify_breakpoint_modified (b);
5345     }   
5346 }
5347
5348 /* Returns true if we need to track moribund locations of LOC's type
5349    on the current target.  */
5350
5351 static int
5352 need_moribund_for_location_type (struct bp_location *loc)
5353 {
5354   return ((loc->loc_type == bp_loc_software_breakpoint
5355            && !target_supports_stopped_by_sw_breakpoint ())
5356           || (loc->loc_type == bp_loc_hardware_breakpoint
5357               && !target_supports_stopped_by_hw_breakpoint ()));
5358 }
5359
5360
5361 /* Get a bpstat associated with having just stopped at address
5362    BP_ADDR in thread PTID.
5363
5364    Determine whether we stopped at a breakpoint, etc, or whether we
5365    don't understand this stop.  Result is a chain of bpstat's such
5366    that:
5367
5368    if we don't understand the stop, the result is a null pointer.
5369
5370    if we understand why we stopped, the result is not null.
5371
5372    Each element of the chain refers to a particular breakpoint or
5373    watchpoint at which we have stopped.  (We may have stopped for
5374    several reasons concurrently.)
5375
5376    Each element of the chain has valid next, breakpoint_at,
5377    commands, FIXME??? fields.  */
5378
5379 bpstat
5380 bpstat_stop_status (const address_space *aspace,
5381                     CORE_ADDR bp_addr, ptid_t ptid,
5382                     const struct target_waitstatus *ws)
5383 {
5384   struct breakpoint *b = NULL;
5385   struct bp_location *bl;
5386   struct bp_location *loc;
5387   /* First item of allocated bpstat's.  */
5388   bpstat bs_head = NULL, *bs_link = &bs_head;
5389   /* Pointer to the last thing in the chain currently.  */
5390   bpstat bs;
5391   int ix;
5392   int need_remove_insert;
5393   int removed_any;
5394
5395   /* First, build the bpstat chain with locations that explain a
5396      target stop, while being careful to not set the target running,
5397      as that may invalidate locations (in particular watchpoint
5398      locations are recreated).  Resuming will happen here with
5399      breakpoint conditions or watchpoint expressions that include
5400      inferior function calls.  */
5401
5402   ALL_BREAKPOINTS (b)
5403     {
5404       if (!breakpoint_enabled (b))
5405         continue;
5406
5407       for (bl = b->loc; bl != NULL; bl = bl->next)
5408         {
5409           /* For hardware watchpoints, we look only at the first
5410              location.  The watchpoint_check function will work on the
5411              entire expression, not the individual locations.  For
5412              read watchpoints, the watchpoints_triggered function has
5413              checked all locations already.  */
5414           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5415             break;
5416
5417           if (!bl->enabled || bl->shlib_disabled)
5418             continue;
5419
5420           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5421             continue;
5422
5423           /* Come here if it's a watchpoint, or if the break address
5424              matches.  */
5425
5426           bs = new bpstats (bl, &bs_link);      /* Alloc a bpstat to
5427                                                    explain stop.  */
5428
5429           /* Assume we stop.  Should we find a watchpoint that is not
5430              actually triggered, or if the condition of the breakpoint
5431              evaluates as false, we'll reset 'stop' to 0.  */
5432           bs->stop = 1;
5433           bs->print = 1;
5434
5435           /* If this is a scope breakpoint, mark the associated
5436              watchpoint as triggered so that we will handle the
5437              out-of-scope event.  We'll get to the watchpoint next
5438              iteration.  */
5439           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5440             {
5441               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5442
5443               w->watchpoint_triggered = watch_triggered_yes;
5444             }
5445         }
5446     }
5447
5448   /* Check if a moribund breakpoint explains the stop.  */
5449   if (!target_supports_stopped_by_sw_breakpoint ()
5450       || !target_supports_stopped_by_hw_breakpoint ())
5451     {
5452       for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5453         {
5454           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5455               && need_moribund_for_location_type (loc))
5456             {
5457               bs = new bpstats (loc, &bs_link);
5458               /* For hits of moribund locations, we should just proceed.  */
5459               bs->stop = 0;
5460               bs->print = 0;
5461               bs->print_it = print_it_noop;
5462             }
5463         }
5464     }
5465
5466   /* A bit of special processing for shlib breakpoints.  We need to
5467      process solib loading here, so that the lists of loaded and
5468      unloaded libraries are correct before we handle "catch load" and
5469      "catch unload".  */
5470   for (bs = bs_head; bs != NULL; bs = bs->next)
5471     {
5472       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5473         {
5474           handle_solib_event ();
5475           break;
5476         }
5477     }
5478
5479   /* Now go through the locations that caused the target to stop, and
5480      check whether we're interested in reporting this stop to higher
5481      layers, or whether we should resume the target transparently.  */
5482
5483   removed_any = 0;
5484
5485   for (bs = bs_head; bs != NULL; bs = bs->next)
5486     {
5487       if (!bs->stop)
5488         continue;
5489
5490       b = bs->breakpoint_at;
5491       b->ops->check_status (bs);
5492       if (bs->stop)
5493         {
5494           bpstat_check_breakpoint_conditions (bs, ptid);
5495
5496           if (bs->stop)
5497             {
5498               ++(b->hit_count);
5499               observer_notify_breakpoint_modified (b);
5500
5501               /* We will stop here.  */
5502               if (b->disposition == disp_disable)
5503                 {
5504                   --(b->enable_count);
5505                   if (b->enable_count <= 0)
5506                     b->enable_state = bp_disabled;
5507                   removed_any = 1;
5508                 }
5509               if (b->silent)
5510                 bs->print = 0;
5511               bs->commands = b->commands;
5512               if (command_line_is_silent (bs->commands
5513                                           ? bs->commands.get () : NULL))
5514                 bs->print = 0;
5515
5516               b->ops->after_condition_true (bs);
5517             }
5518
5519         }
5520
5521       /* Print nothing for this entry if we don't stop or don't
5522          print.  */
5523       if (!bs->stop || !bs->print)
5524         bs->print_it = print_it_noop;
5525     }
5526
5527   /* If we aren't stopping, the value of some hardware watchpoint may
5528      not have changed, but the intermediate memory locations we are
5529      watching may have.  Don't bother if we're stopping; this will get
5530      done later.  */
5531   need_remove_insert = 0;
5532   if (! bpstat_causes_stop (bs_head))
5533     for (bs = bs_head; bs != NULL; bs = bs->next)
5534       if (!bs->stop
5535           && bs->breakpoint_at
5536           && is_hardware_watchpoint (bs->breakpoint_at))
5537         {
5538           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5539
5540           update_watchpoint (w, 0 /* don't reparse.  */);
5541           need_remove_insert = 1;
5542         }
5543
5544   if (need_remove_insert)
5545     update_global_location_list (UGLL_MAY_INSERT);
5546   else if (removed_any)
5547     update_global_location_list (UGLL_DONT_INSERT);
5548
5549   return bs_head;
5550 }
5551
5552 static void
5553 handle_jit_event (void)
5554 {
5555   struct frame_info *frame;
5556   struct gdbarch *gdbarch;
5557
5558   if (debug_infrun)
5559     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5560
5561   /* Switch terminal for any messages produced by
5562      breakpoint_re_set.  */
5563   target_terminal::ours_for_output ();
5564
5565   frame = get_current_frame ();
5566   gdbarch = get_frame_arch (frame);
5567
5568   jit_event_handler (gdbarch);
5569
5570   target_terminal::inferior ();
5571 }
5572
5573 /* Prepare WHAT final decision for infrun.  */
5574
5575 /* Decide what infrun needs to do with this bpstat.  */
5576
5577 struct bpstat_what
5578 bpstat_what (bpstat bs_head)
5579 {
5580   struct bpstat_what retval;
5581   bpstat bs;
5582
5583   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5584   retval.call_dummy = STOP_NONE;
5585   retval.is_longjmp = 0;
5586
5587   for (bs = bs_head; bs != NULL; bs = bs->next)
5588     {
5589       /* Extract this BS's action.  After processing each BS, we check
5590          if its action overrides all we've seem so far.  */
5591       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5592       enum bptype bptype;
5593
5594       if (bs->breakpoint_at == NULL)
5595         {
5596           /* I suspect this can happen if it was a momentary
5597              breakpoint which has since been deleted.  */
5598           bptype = bp_none;
5599         }
5600       else
5601         bptype = bs->breakpoint_at->type;
5602
5603       switch (bptype)
5604         {
5605         case bp_none:
5606           break;
5607         case bp_breakpoint:
5608         case bp_hardware_breakpoint:
5609         case bp_single_step:
5610         case bp_until:
5611         case bp_finish:
5612         case bp_shlib_event:
5613           if (bs->stop)
5614             {
5615               if (bs->print)
5616                 this_action = BPSTAT_WHAT_STOP_NOISY;
5617               else
5618                 this_action = BPSTAT_WHAT_STOP_SILENT;
5619             }
5620           else
5621             this_action = BPSTAT_WHAT_SINGLE;
5622           break;
5623         case bp_watchpoint:
5624         case bp_hardware_watchpoint:
5625         case bp_read_watchpoint:
5626         case bp_access_watchpoint:
5627           if (bs->stop)
5628             {
5629               if (bs->print)
5630                 this_action = BPSTAT_WHAT_STOP_NOISY;
5631               else
5632                 this_action = BPSTAT_WHAT_STOP_SILENT;
5633             }
5634           else
5635             {
5636               /* There was a watchpoint, but we're not stopping.
5637                  This requires no further action.  */
5638             }
5639           break;
5640         case bp_longjmp:
5641         case bp_longjmp_call_dummy:
5642         case bp_exception:
5643           if (bs->stop)
5644             {
5645               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5646               retval.is_longjmp = bptype != bp_exception;
5647             }
5648           else
5649             this_action = BPSTAT_WHAT_SINGLE;
5650           break;
5651         case bp_longjmp_resume:
5652         case bp_exception_resume:
5653           if (bs->stop)
5654             {
5655               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5656               retval.is_longjmp = bptype == bp_longjmp_resume;
5657             }
5658           else
5659             this_action = BPSTAT_WHAT_SINGLE;
5660           break;
5661         case bp_step_resume:
5662           if (bs->stop)
5663             this_action = BPSTAT_WHAT_STEP_RESUME;
5664           else
5665             {
5666               /* It is for the wrong frame.  */
5667               this_action = BPSTAT_WHAT_SINGLE;
5668             }
5669           break;
5670         case bp_hp_step_resume:
5671           if (bs->stop)
5672             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5673           else
5674             {
5675               /* It is for the wrong frame.  */
5676               this_action = BPSTAT_WHAT_SINGLE;
5677             }
5678           break;
5679         case bp_watchpoint_scope:
5680         case bp_thread_event:
5681         case bp_overlay_event:
5682         case bp_longjmp_master:
5683         case bp_std_terminate_master:
5684         case bp_exception_master:
5685           this_action = BPSTAT_WHAT_SINGLE;
5686           break;
5687         case bp_catchpoint:
5688           if (bs->stop)
5689             {
5690               if (bs->print)
5691                 this_action = BPSTAT_WHAT_STOP_NOISY;
5692               else
5693                 this_action = BPSTAT_WHAT_STOP_SILENT;
5694             }
5695           else
5696             {
5697               /* There was a catchpoint, but we're not stopping.
5698                  This requires no further action.  */
5699             }
5700           break;
5701         case bp_jit_event:
5702           this_action = BPSTAT_WHAT_SINGLE;
5703           break;
5704         case bp_call_dummy:
5705           /* Make sure the action is stop (silent or noisy),
5706              so infrun.c pops the dummy frame.  */
5707           retval.call_dummy = STOP_STACK_DUMMY;
5708           this_action = BPSTAT_WHAT_STOP_SILENT;
5709           break;
5710         case bp_std_terminate:
5711           /* Make sure the action is stop (silent or noisy),
5712              so infrun.c pops the dummy frame.  */
5713           retval.call_dummy = STOP_STD_TERMINATE;
5714           this_action = BPSTAT_WHAT_STOP_SILENT;
5715           break;
5716         case bp_tracepoint:
5717         case bp_fast_tracepoint:
5718         case bp_static_tracepoint:
5719           /* Tracepoint hits should not be reported back to GDB, and
5720              if one got through somehow, it should have been filtered
5721              out already.  */
5722           internal_error (__FILE__, __LINE__,
5723                           _("bpstat_what: tracepoint encountered"));
5724           break;
5725         case bp_gnu_ifunc_resolver:
5726           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5727           this_action = BPSTAT_WHAT_SINGLE;
5728           break;
5729         case bp_gnu_ifunc_resolver_return:
5730           /* The breakpoint will be removed, execution will restart from the
5731              PC of the former breakpoint.  */
5732           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5733           break;
5734
5735         case bp_dprintf:
5736           if (bs->stop)
5737             this_action = BPSTAT_WHAT_STOP_SILENT;
5738           else
5739             this_action = BPSTAT_WHAT_SINGLE;
5740           break;
5741
5742         default:
5743           internal_error (__FILE__, __LINE__,
5744                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5745         }
5746
5747       retval.main_action = std::max (retval.main_action, this_action);
5748     }
5749
5750   return retval;
5751 }
5752
5753 void
5754 bpstat_run_callbacks (bpstat bs_head)
5755 {
5756   bpstat bs;
5757
5758   for (bs = bs_head; bs != NULL; bs = bs->next)
5759     {
5760       struct breakpoint *b = bs->breakpoint_at;
5761
5762       if (b == NULL)
5763         continue;
5764       switch (b->type)
5765         {
5766         case bp_jit_event:
5767           handle_jit_event ();
5768           break;
5769         case bp_gnu_ifunc_resolver:
5770           gnu_ifunc_resolver_stop (b);
5771           break;
5772         case bp_gnu_ifunc_resolver_return:
5773           gnu_ifunc_resolver_return_stop (b);
5774           break;
5775         }
5776     }
5777 }
5778
5779 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5780    without hardware support).  This isn't related to a specific bpstat,
5781    just to things like whether watchpoints are set.  */
5782
5783 int
5784 bpstat_should_step (void)
5785 {
5786   struct breakpoint *b;
5787
5788   ALL_BREAKPOINTS (b)
5789     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5790       return 1;
5791   return 0;
5792 }
5793
5794 int
5795 bpstat_causes_stop (bpstat bs)
5796 {
5797   for (; bs != NULL; bs = bs->next)
5798     if (bs->stop)
5799       return 1;
5800
5801   return 0;
5802 }
5803
5804 \f
5805
5806 /* Compute a string of spaces suitable to indent the next line
5807    so it starts at the position corresponding to the table column
5808    named COL_NAME in the currently active table of UIOUT.  */
5809
5810 static char *
5811 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5812 {
5813   static char wrap_indent[80];
5814   int i, total_width, width, align;
5815   const char *text;
5816
5817   total_width = 0;
5818   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
5819     {
5820       if (strcmp (text, col_name) == 0)
5821         {
5822           gdb_assert (total_width < sizeof wrap_indent);
5823           memset (wrap_indent, ' ', total_width);
5824           wrap_indent[total_width] = 0;
5825
5826           return wrap_indent;
5827         }
5828
5829       total_width += width + 1;
5830     }
5831
5832   return NULL;
5833 }
5834
5835 /* Determine if the locations of this breakpoint will have their conditions
5836    evaluated by the target, host or a mix of both.  Returns the following:
5837
5838     "host": Host evals condition.
5839     "host or target": Host or Target evals condition.
5840     "target": Target evals condition.
5841 */
5842
5843 static const char *
5844 bp_condition_evaluator (struct breakpoint *b)
5845 {
5846   struct bp_location *bl;
5847   char host_evals = 0;
5848   char target_evals = 0;
5849
5850   if (!b)
5851     return NULL;
5852
5853   if (!is_breakpoint (b))
5854     return NULL;
5855
5856   if (gdb_evaluates_breakpoint_condition_p ()
5857       || !target_supports_evaluation_of_breakpoint_conditions ())
5858     return condition_evaluation_host;
5859
5860   for (bl = b->loc; bl; bl = bl->next)
5861     {
5862       if (bl->cond_bytecode)
5863         target_evals++;
5864       else
5865         host_evals++;
5866     }
5867
5868   if (host_evals && target_evals)
5869     return condition_evaluation_both;
5870   else if (target_evals)
5871     return condition_evaluation_target;
5872   else
5873     return condition_evaluation_host;
5874 }
5875
5876 /* Determine the breakpoint location's condition evaluator.  This is
5877    similar to bp_condition_evaluator, but for locations.  */
5878
5879 static const char *
5880 bp_location_condition_evaluator (struct bp_location *bl)
5881 {
5882   if (bl && !is_breakpoint (bl->owner))
5883     return NULL;
5884
5885   if (gdb_evaluates_breakpoint_condition_p ()
5886       || !target_supports_evaluation_of_breakpoint_conditions ())
5887     return condition_evaluation_host;
5888
5889   if (bl && bl->cond_bytecode)
5890     return condition_evaluation_target;
5891   else
5892     return condition_evaluation_host;
5893 }
5894
5895 /* Print the LOC location out of the list of B->LOC locations.  */
5896
5897 static void
5898 print_breakpoint_location (struct breakpoint *b,
5899                            struct bp_location *loc)
5900 {
5901   struct ui_out *uiout = current_uiout;
5902
5903   scoped_restore_current_program_space restore_pspace;
5904
5905   if (loc != NULL && loc->shlib_disabled)
5906     loc = NULL;
5907
5908   if (loc != NULL)
5909     set_current_program_space (loc->pspace);
5910
5911   if (b->display_canonical)
5912     uiout->field_string ("what", event_location_to_string (b->location.get ()));
5913   else if (loc && loc->symtab)
5914     {
5915       const struct symbol *sym = loc->symbol;
5916
5917       if (sym == NULL)
5918         sym = find_pc_sect_function (loc->address, loc->section);
5919
5920       if (sym)
5921         {
5922           uiout->text ("in ");
5923           uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
5924           uiout->text (" ");
5925           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
5926           uiout->text ("at ");
5927         }
5928       uiout->field_string ("file",
5929                            symtab_to_filename_for_display (loc->symtab));
5930       uiout->text (":");
5931
5932       if (uiout->is_mi_like_p ())
5933         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
5934       
5935       uiout->field_int ("line", loc->line_number);
5936     }
5937   else if (loc)
5938     {
5939       string_file stb;
5940
5941       print_address_symbolic (loc->gdbarch, loc->address, &stb,
5942                               demangle, "");
5943       uiout->field_stream ("at", stb);
5944     }
5945   else
5946     {
5947       uiout->field_string ("pending",
5948                            event_location_to_string (b->location.get ()));
5949       /* If extra_string is available, it could be holding a condition
5950          or dprintf arguments.  In either case, make sure it is printed,
5951          too, but only for non-MI streams.  */
5952       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
5953         {
5954           if (b->type == bp_dprintf)
5955             uiout->text (",");
5956           else
5957             uiout->text (" ");
5958           uiout->text (b->extra_string);
5959         }
5960     }
5961
5962   if (loc && is_breakpoint (b)
5963       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5964       && bp_condition_evaluator (b) == condition_evaluation_both)
5965     {
5966       uiout->text (" (");
5967       uiout->field_string ("evaluated-by",
5968                            bp_location_condition_evaluator (loc));
5969       uiout->text (")");
5970     }
5971 }
5972
5973 static const char *
5974 bptype_string (enum bptype type)
5975 {
5976   struct ep_type_description
5977     {
5978       enum bptype type;
5979       const char *description;
5980     };
5981   static struct ep_type_description bptypes[] =
5982   {
5983     {bp_none, "?deleted?"},
5984     {bp_breakpoint, "breakpoint"},
5985     {bp_hardware_breakpoint, "hw breakpoint"},
5986     {bp_single_step, "sw single-step"},
5987     {bp_until, "until"},
5988     {bp_finish, "finish"},
5989     {bp_watchpoint, "watchpoint"},
5990     {bp_hardware_watchpoint, "hw watchpoint"},
5991     {bp_read_watchpoint, "read watchpoint"},
5992     {bp_access_watchpoint, "acc watchpoint"},
5993     {bp_longjmp, "longjmp"},
5994     {bp_longjmp_resume, "longjmp resume"},
5995     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5996     {bp_exception, "exception"},
5997     {bp_exception_resume, "exception resume"},
5998     {bp_step_resume, "step resume"},
5999     {bp_hp_step_resume, "high-priority step resume"},
6000     {bp_watchpoint_scope, "watchpoint scope"},
6001     {bp_call_dummy, "call dummy"},
6002     {bp_std_terminate, "std::terminate"},
6003     {bp_shlib_event, "shlib events"},
6004     {bp_thread_event, "thread events"},
6005     {bp_overlay_event, "overlay events"},
6006     {bp_longjmp_master, "longjmp master"},
6007     {bp_std_terminate_master, "std::terminate master"},
6008     {bp_exception_master, "exception master"},
6009     {bp_catchpoint, "catchpoint"},
6010     {bp_tracepoint, "tracepoint"},
6011     {bp_fast_tracepoint, "fast tracepoint"},
6012     {bp_static_tracepoint, "static tracepoint"},
6013     {bp_dprintf, "dprintf"},
6014     {bp_jit_event, "jit events"},
6015     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6016     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6017   };
6018
6019   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6020       || ((int) type != bptypes[(int) type].type))
6021     internal_error (__FILE__, __LINE__,
6022                     _("bptypes table does not describe type #%d."),
6023                     (int) type);
6024
6025   return bptypes[(int) type].description;
6026 }
6027
6028 /* For MI, output a field named 'thread-groups' with a list as the value.
6029    For CLI, prefix the list with the string 'inf'. */
6030
6031 static void
6032 output_thread_groups (struct ui_out *uiout,
6033                       const char *field_name,
6034                       const std::vector<int> &inf_nums,
6035                       int mi_only)
6036 {
6037   int is_mi = uiout->is_mi_like_p ();
6038
6039   /* For backward compatibility, don't display inferiors in CLI unless
6040      there are several.  Always display them for MI. */
6041   if (!is_mi && mi_only)
6042     return;
6043
6044   ui_out_emit_list list_emitter (uiout, field_name);
6045
6046   for (size_t i = 0; i < inf_nums.size (); i++)
6047     {
6048       if (is_mi)
6049         {
6050           char mi_group[10];
6051
6052           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf_nums[i]);
6053           uiout->field_string (NULL, mi_group);
6054         }
6055       else
6056         {
6057           if (i == 0)
6058             uiout->text (" inf ");
6059           else
6060             uiout->text (", ");
6061         
6062           uiout->text (plongest (inf_nums[i]));
6063         }
6064     }
6065 }
6066
6067 /* Print B to gdb_stdout.  */
6068
6069 static void
6070 print_one_breakpoint_location (struct breakpoint *b,
6071                                struct bp_location *loc,
6072                                int loc_number,
6073                                struct bp_location **last_loc,
6074                                int allflag)
6075 {
6076   struct command_line *l;
6077   static char bpenables[] = "nynny";
6078
6079   struct ui_out *uiout = current_uiout;
6080   int header_of_multiple = 0;
6081   int part_of_multiple = (loc != NULL);
6082   struct value_print_options opts;
6083
6084   get_user_print_options (&opts);
6085
6086   gdb_assert (!loc || loc_number != 0);
6087   /* See comment in print_one_breakpoint concerning treatment of
6088      breakpoints with single disabled location.  */
6089   if (loc == NULL 
6090       && (b->loc != NULL 
6091           && (b->loc->next != NULL || !b->loc->enabled)))
6092     header_of_multiple = 1;
6093   if (loc == NULL)
6094     loc = b->loc;
6095
6096   annotate_record ();
6097
6098   /* 1 */
6099   annotate_field (0);
6100   if (part_of_multiple)
6101     {
6102       char *formatted;
6103       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6104       uiout->field_string ("number", formatted);
6105       xfree (formatted);
6106     }
6107   else
6108     {
6109       uiout->field_int ("number", b->number);
6110     }
6111
6112   /* 2 */
6113   annotate_field (1);
6114   if (part_of_multiple)
6115     uiout->field_skip ("type");
6116   else
6117     uiout->field_string ("type", bptype_string (b->type));
6118
6119   /* 3 */
6120   annotate_field (2);
6121   if (part_of_multiple)
6122     uiout->field_skip ("disp");
6123   else
6124     uiout->field_string ("disp", bpdisp_text (b->disposition));
6125
6126
6127   /* 4 */
6128   annotate_field (3);
6129   if (part_of_multiple)
6130     uiout->field_string ("enabled", loc->enabled ? "y" : "n");
6131   else
6132     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6133   uiout->spaces (2);
6134
6135   
6136   /* 5 and 6 */
6137   if (b->ops != NULL && b->ops->print_one != NULL)
6138     {
6139       /* Although the print_one can possibly print all locations,
6140          calling it here is not likely to get any nice result.  So,
6141          make sure there's just one location.  */
6142       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6143       b->ops->print_one (b, last_loc);
6144     }
6145   else
6146     switch (b->type)
6147       {
6148       case bp_none:
6149         internal_error (__FILE__, __LINE__,
6150                         _("print_one_breakpoint: bp_none encountered\n"));
6151         break;
6152
6153       case bp_watchpoint:
6154       case bp_hardware_watchpoint:
6155       case bp_read_watchpoint:
6156       case bp_access_watchpoint:
6157         {
6158           struct watchpoint *w = (struct watchpoint *) b;
6159
6160           /* Field 4, the address, is omitted (which makes the columns
6161              not line up too nicely with the headers, but the effect
6162              is relatively readable).  */
6163           if (opts.addressprint)
6164             uiout->field_skip ("addr");
6165           annotate_field (5);
6166           uiout->field_string ("what", w->exp_string);
6167         }
6168         break;
6169
6170       case bp_breakpoint:
6171       case bp_hardware_breakpoint:
6172       case bp_single_step:
6173       case bp_until:
6174       case bp_finish:
6175       case bp_longjmp:
6176       case bp_longjmp_resume:
6177       case bp_longjmp_call_dummy:
6178       case bp_exception:
6179       case bp_exception_resume:
6180       case bp_step_resume:
6181       case bp_hp_step_resume:
6182       case bp_watchpoint_scope:
6183       case bp_call_dummy:
6184       case bp_std_terminate:
6185       case bp_shlib_event:
6186       case bp_thread_event:
6187       case bp_overlay_event:
6188       case bp_longjmp_master:
6189       case bp_std_terminate_master:
6190       case bp_exception_master:
6191       case bp_tracepoint:
6192       case bp_fast_tracepoint:
6193       case bp_static_tracepoint:
6194       case bp_dprintf:
6195       case bp_jit_event:
6196       case bp_gnu_ifunc_resolver:
6197       case bp_gnu_ifunc_resolver_return:
6198         if (opts.addressprint)
6199           {
6200             annotate_field (4);
6201             if (header_of_multiple)
6202               uiout->field_string ("addr", "<MULTIPLE>");
6203             else if (b->loc == NULL || loc->shlib_disabled)
6204               uiout->field_string ("addr", "<PENDING>");
6205             else
6206               uiout->field_core_addr ("addr",
6207                                       loc->gdbarch, loc->address);
6208           }
6209         annotate_field (5);
6210         if (!header_of_multiple)
6211           print_breakpoint_location (b, loc);
6212         if (b->loc)
6213           *last_loc = b->loc;
6214         break;
6215       }
6216
6217
6218   if (loc != NULL && !header_of_multiple)
6219     {
6220       struct inferior *inf;
6221       std::vector<int> inf_nums;
6222       int mi_only = 1;
6223
6224       ALL_INFERIORS (inf)
6225         {
6226           if (inf->pspace == loc->pspace)
6227             inf_nums.push_back (inf->num);
6228         }
6229
6230         /* For backward compatibility, don't display inferiors in CLI unless
6231            there are several.  Always display for MI. */
6232         if (allflag
6233             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6234                 && (number_of_program_spaces () > 1
6235                     || number_of_inferiors () > 1)
6236                 /* LOC is for existing B, it cannot be in
6237                    moribund_locations and thus having NULL OWNER.  */
6238                 && loc->owner->type != bp_catchpoint))
6239         mi_only = 0;
6240       output_thread_groups (uiout, "thread-groups", inf_nums, mi_only);
6241     }
6242
6243   if (!part_of_multiple)
6244     {
6245       if (b->thread != -1)
6246         {
6247           /* FIXME: This seems to be redundant and lost here; see the
6248              "stop only in" line a little further down.  */
6249           uiout->text (" thread ");
6250           uiout->field_int ("thread", b->thread);
6251         }
6252       else if (b->task != 0)
6253         {
6254           uiout->text (" task ");
6255           uiout->field_int ("task", b->task);
6256         }
6257     }
6258
6259   uiout->text ("\n");
6260
6261   if (!part_of_multiple)
6262     b->ops->print_one_detail (b, uiout);
6263
6264   if (part_of_multiple && frame_id_p (b->frame_id))
6265     {
6266       annotate_field (6);
6267       uiout->text ("\tstop only in stack frame at ");
6268       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6269          the frame ID.  */
6270       uiout->field_core_addr ("frame",
6271                               b->gdbarch, b->frame_id.stack_addr);
6272       uiout->text ("\n");
6273     }
6274   
6275   if (!part_of_multiple && b->cond_string)
6276     {
6277       annotate_field (7);
6278       if (is_tracepoint (b))
6279         uiout->text ("\ttrace only if ");
6280       else
6281         uiout->text ("\tstop only if ");
6282       uiout->field_string ("cond", b->cond_string);
6283
6284       /* Print whether the target is doing the breakpoint's condition
6285          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6286       if (is_breakpoint (b)
6287           && breakpoint_condition_evaluation_mode ()
6288           == condition_evaluation_target)
6289         {
6290           uiout->text (" (");
6291           uiout->field_string ("evaluated-by",
6292                                bp_condition_evaluator (b));
6293           uiout->text (" evals)");
6294         }
6295       uiout->text ("\n");
6296     }
6297
6298   if (!part_of_multiple && b->thread != -1)
6299     {
6300       /* FIXME should make an annotation for this.  */
6301       uiout->text ("\tstop only in thread ");
6302       if (uiout->is_mi_like_p ())
6303         uiout->field_int ("thread", b->thread);
6304       else
6305         {
6306           struct thread_info *thr = find_thread_global_id (b->thread);
6307
6308           uiout->field_string ("thread", print_thread_id (thr));
6309         }
6310       uiout->text ("\n");
6311     }
6312   
6313   if (!part_of_multiple)
6314     {
6315       if (b->hit_count)
6316         {
6317           /* FIXME should make an annotation for this.  */
6318           if (is_catchpoint (b))
6319             uiout->text ("\tcatchpoint");
6320           else if (is_tracepoint (b))
6321             uiout->text ("\ttracepoint");
6322           else
6323             uiout->text ("\tbreakpoint");
6324           uiout->text (" already hit ");
6325           uiout->field_int ("times", b->hit_count);
6326           if (b->hit_count == 1)
6327             uiout->text (" time\n");
6328           else
6329             uiout->text (" times\n");
6330         }
6331       else
6332         {
6333           /* Output the count also if it is zero, but only if this is mi.  */
6334           if (uiout->is_mi_like_p ())
6335             uiout->field_int ("times", b->hit_count);
6336         }
6337     }
6338
6339   if (!part_of_multiple && b->ignore_count)
6340     {
6341       annotate_field (8);
6342       uiout->text ("\tignore next ");
6343       uiout->field_int ("ignore", b->ignore_count);
6344       uiout->text (" hits\n");
6345     }
6346
6347   /* Note that an enable count of 1 corresponds to "enable once"
6348      behavior, which is reported by the combination of enablement and
6349      disposition, so we don't need to mention it here.  */
6350   if (!part_of_multiple && b->enable_count > 1)
6351     {
6352       annotate_field (8);
6353       uiout->text ("\tdisable after ");
6354       /* Tweak the wording to clarify that ignore and enable counts
6355          are distinct, and have additive effect.  */
6356       if (b->ignore_count)
6357         uiout->text ("additional ");
6358       else
6359         uiout->text ("next ");
6360       uiout->field_int ("enable", b->enable_count);
6361       uiout->text (" hits\n");
6362     }
6363
6364   if (!part_of_multiple && is_tracepoint (b))
6365     {
6366       struct tracepoint *tp = (struct tracepoint *) b;
6367
6368       if (tp->traceframe_usage)
6369         {
6370           uiout->text ("\ttrace buffer usage ");
6371           uiout->field_int ("traceframe-usage", tp->traceframe_usage);
6372           uiout->text (" bytes\n");
6373         }
6374     }
6375
6376   l = b->commands ? b->commands.get () : NULL;
6377   if (!part_of_multiple && l)
6378     {
6379       annotate_field (9);
6380       ui_out_emit_tuple tuple_emitter (uiout, "script");
6381       print_command_lines (uiout, l, 4);
6382     }
6383
6384   if (is_tracepoint (b))
6385     {
6386       struct tracepoint *t = (struct tracepoint *) b;
6387
6388       if (!part_of_multiple && t->pass_count)
6389         {
6390           annotate_field (10);
6391           uiout->text ("\tpass count ");
6392           uiout->field_int ("pass", t->pass_count);
6393           uiout->text (" \n");
6394         }
6395
6396       /* Don't display it when tracepoint or tracepoint location is
6397          pending.   */
6398       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6399         {
6400           annotate_field (11);
6401
6402           if (uiout->is_mi_like_p ())
6403             uiout->field_string ("installed",
6404                                  loc->inserted ? "y" : "n");
6405           else
6406             {
6407               if (loc->inserted)
6408                 uiout->text ("\t");
6409               else
6410                 uiout->text ("\tnot ");
6411               uiout->text ("installed on target\n");
6412             }
6413         }
6414     }
6415
6416   if (uiout->is_mi_like_p () && !part_of_multiple)
6417     {
6418       if (is_watchpoint (b))
6419         {
6420           struct watchpoint *w = (struct watchpoint *) b;
6421
6422           uiout->field_string ("original-location", w->exp_string);
6423         }
6424       else if (b->location != NULL
6425                && event_location_to_string (b->location.get ()) != NULL)
6426         uiout->field_string ("original-location",
6427                              event_location_to_string (b->location.get ()));
6428     }
6429 }
6430
6431 static void
6432 print_one_breakpoint (struct breakpoint *b,
6433                       struct bp_location **last_loc, 
6434                       int allflag)
6435 {
6436   struct ui_out *uiout = current_uiout;
6437
6438   {
6439     ui_out_emit_tuple tuple_emitter (uiout, "bkpt");
6440
6441     print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6442   }
6443
6444   /* If this breakpoint has custom print function,
6445      it's already printed.  Otherwise, print individual
6446      locations, if any.  */
6447   if (b->ops == NULL || b->ops->print_one == NULL)
6448     {
6449       /* If breakpoint has a single location that is disabled, we
6450          print it as if it had several locations, since otherwise it's
6451          hard to represent "breakpoint enabled, location disabled"
6452          situation.
6453
6454          Note that while hardware watchpoints have several locations
6455          internally, that's not a property exposed to user.  */
6456       if (b->loc 
6457           && !is_hardware_watchpoint (b)
6458           && (b->loc->next || !b->loc->enabled))
6459         {
6460           struct bp_location *loc;
6461           int n = 1;
6462
6463           for (loc = b->loc; loc; loc = loc->next, ++n)
6464             {
6465               ui_out_emit_tuple tuple_emitter (uiout, NULL);
6466               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6467             }
6468         }
6469     }
6470 }
6471
6472 static int
6473 breakpoint_address_bits (struct breakpoint *b)
6474 {
6475   int print_address_bits = 0;
6476   struct bp_location *loc;
6477
6478   /* Software watchpoints that aren't watching memory don't have an
6479      address to print.  */
6480   if (is_no_memory_software_watchpoint (b))
6481     return 0;
6482
6483   for (loc = b->loc; loc; loc = loc->next)
6484     {
6485       int addr_bit;
6486
6487       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6488       if (addr_bit > print_address_bits)
6489         print_address_bits = addr_bit;
6490     }
6491
6492   return print_address_bits;
6493 }
6494
6495 /* See breakpoint.h.  */
6496
6497 void
6498 print_breakpoint (breakpoint *b)
6499 {
6500   struct bp_location *dummy_loc = NULL;
6501   print_one_breakpoint (b, &dummy_loc, 0);
6502 }
6503
6504 /* Return true if this breakpoint was set by the user, false if it is
6505    internal or momentary.  */
6506
6507 int
6508 user_breakpoint_p (struct breakpoint *b)
6509 {
6510   return b->number > 0;
6511 }
6512
6513 /* See breakpoint.h.  */
6514
6515 int
6516 pending_breakpoint_p (struct breakpoint *b)
6517 {
6518   return b->loc == NULL;
6519 }
6520
6521 /* Print information on user settable breakpoint (watchpoint, etc)
6522    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6523    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6524    FILTER is non-NULL, call it on each breakpoint and only include the
6525    ones for which it returns non-zero.  Return the total number of
6526    breakpoints listed.  */
6527
6528 static int
6529 breakpoint_1 (const char *args, int allflag, 
6530               int (*filter) (const struct breakpoint *))
6531 {
6532   struct breakpoint *b;
6533   struct bp_location *last_loc = NULL;
6534   int nr_printable_breakpoints;
6535   struct value_print_options opts;
6536   int print_address_bits = 0;
6537   int print_type_col_width = 14;
6538   struct ui_out *uiout = current_uiout;
6539
6540   get_user_print_options (&opts);
6541
6542   /* Compute the number of rows in the table, as well as the size
6543      required for address fields.  */
6544   nr_printable_breakpoints = 0;
6545   ALL_BREAKPOINTS (b)
6546     {
6547       /* If we have a filter, only list the breakpoints it accepts.  */
6548       if (filter && !filter (b))
6549         continue;
6550
6551       /* If we have an "args" string, it is a list of breakpoints to 
6552          accept.  Skip the others.  */
6553       if (args != NULL && *args != '\0')
6554         {
6555           if (allflag && parse_and_eval_long (args) != b->number)
6556             continue;
6557           if (!allflag && !number_is_in_list (args, b->number))
6558             continue;
6559         }
6560
6561       if (allflag || user_breakpoint_p (b))
6562         {
6563           int addr_bit, type_len;
6564
6565           addr_bit = breakpoint_address_bits (b);
6566           if (addr_bit > print_address_bits)
6567             print_address_bits = addr_bit;
6568
6569           type_len = strlen (bptype_string (b->type));
6570           if (type_len > print_type_col_width)
6571             print_type_col_width = type_len;
6572
6573           nr_printable_breakpoints++;
6574         }
6575     }
6576
6577   {
6578     ui_out_emit_table table_emitter (uiout,
6579                                      opts.addressprint ? 6 : 5,
6580                                      nr_printable_breakpoints,
6581                                      "BreakpointTable");
6582
6583     if (nr_printable_breakpoints > 0)
6584       annotate_breakpoints_headers ();
6585     if (nr_printable_breakpoints > 0)
6586       annotate_field (0);
6587     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6588     if (nr_printable_breakpoints > 0)
6589       annotate_field (1);
6590     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6591     if (nr_printable_breakpoints > 0)
6592       annotate_field (2);
6593     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6594     if (nr_printable_breakpoints > 0)
6595       annotate_field (3);
6596     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6597     if (opts.addressprint)
6598       {
6599         if (nr_printable_breakpoints > 0)
6600           annotate_field (4);
6601         if (print_address_bits <= 32)
6602           uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6603         else
6604           uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6605       }
6606     if (nr_printable_breakpoints > 0)
6607       annotate_field (5);
6608     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6609     uiout->table_body ();
6610     if (nr_printable_breakpoints > 0)
6611       annotate_breakpoints_table ();
6612
6613     ALL_BREAKPOINTS (b)
6614       {
6615         QUIT;
6616         /* If we have a filter, only list the breakpoints it accepts.  */
6617         if (filter && !filter (b))
6618           continue;
6619
6620         /* If we have an "args" string, it is a list of breakpoints to 
6621            accept.  Skip the others.  */
6622
6623         if (args != NULL && *args != '\0')
6624           {
6625             if (allflag)        /* maintenance info breakpoint */
6626               {
6627                 if (parse_and_eval_long (args) != b->number)
6628                   continue;
6629               }
6630             else                /* all others */
6631               {
6632                 if (!number_is_in_list (args, b->number))
6633                   continue;
6634               }
6635           }
6636         /* We only print out user settable breakpoints unless the
6637            allflag is set.  */
6638         if (allflag || user_breakpoint_p (b))
6639           print_one_breakpoint (b, &last_loc, allflag);
6640       }
6641   }
6642
6643   if (nr_printable_breakpoints == 0)
6644     {
6645       /* If there's a filter, let the caller decide how to report
6646          empty list.  */
6647       if (!filter)
6648         {
6649           if (args == NULL || *args == '\0')
6650             uiout->message ("No breakpoints or watchpoints.\n");
6651           else
6652             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6653                             args);
6654         }
6655     }
6656   else
6657     {
6658       if (last_loc && !server_command)
6659         set_next_address (last_loc->gdbarch, last_loc->address);
6660     }
6661
6662   /* FIXME?  Should this be moved up so that it is only called when
6663      there have been breakpoints? */
6664   annotate_breakpoints_table_end ();
6665
6666   return nr_printable_breakpoints;
6667 }
6668
6669 /* Display the value of default-collect in a way that is generally
6670    compatible with the breakpoint list.  */
6671
6672 static void
6673 default_collect_info (void)
6674 {
6675   struct ui_out *uiout = current_uiout;
6676
6677   /* If it has no value (which is frequently the case), say nothing; a
6678      message like "No default-collect." gets in user's face when it's
6679      not wanted.  */
6680   if (!*default_collect)
6681     return;
6682
6683   /* The following phrase lines up nicely with per-tracepoint collect
6684      actions.  */
6685   uiout->text ("default collect ");
6686   uiout->field_string ("default-collect", default_collect);
6687   uiout->text (" \n");
6688 }
6689   
6690 static void
6691 info_breakpoints_command (const char *args, int from_tty)
6692 {
6693   breakpoint_1 (args, 0, NULL);
6694
6695   default_collect_info ();
6696 }
6697
6698 static void
6699 info_watchpoints_command (const char *args, int from_tty)
6700 {
6701   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6702   struct ui_out *uiout = current_uiout;
6703
6704   if (num_printed == 0)
6705     {
6706       if (args == NULL || *args == '\0')
6707         uiout->message ("No watchpoints.\n");
6708       else
6709         uiout->message ("No watchpoint matching '%s'.\n", args);
6710     }
6711 }
6712
6713 static void
6714 maintenance_info_breakpoints (const char *args, int from_tty)
6715 {
6716   breakpoint_1 (args, 1, NULL);
6717
6718   default_collect_info ();
6719 }
6720
6721 static int
6722 breakpoint_has_pc (struct breakpoint *b,
6723                    struct program_space *pspace,
6724                    CORE_ADDR pc, struct obj_section *section)
6725 {
6726   struct bp_location *bl = b->loc;
6727
6728   for (; bl; bl = bl->next)
6729     {
6730       if (bl->pspace == pspace
6731           && bl->address == pc
6732           && (!overlay_debugging || bl->section == section))
6733         return 1;         
6734     }
6735   return 0;
6736 }
6737
6738 /* Print a message describing any user-breakpoints set at PC.  This
6739    concerns with logical breakpoints, so we match program spaces, not
6740    address spaces.  */
6741
6742 static void
6743 describe_other_breakpoints (struct gdbarch *gdbarch,
6744                             struct program_space *pspace, CORE_ADDR pc,
6745                             struct obj_section *section, int thread)
6746 {
6747   int others = 0;
6748   struct breakpoint *b;
6749
6750   ALL_BREAKPOINTS (b)
6751     others += (user_breakpoint_p (b)
6752                && breakpoint_has_pc (b, pspace, pc, section));
6753   if (others > 0)
6754     {
6755       if (others == 1)
6756         printf_filtered (_("Note: breakpoint "));
6757       else /* if (others == ???) */
6758         printf_filtered (_("Note: breakpoints "));
6759       ALL_BREAKPOINTS (b)
6760         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6761           {
6762             others--;
6763             printf_filtered ("%d", b->number);
6764             if (b->thread == -1 && thread != -1)
6765               printf_filtered (" (all threads)");
6766             else if (b->thread != -1)
6767               printf_filtered (" (thread %d)", b->thread);
6768             printf_filtered ("%s%s ",
6769                              ((b->enable_state == bp_disabled
6770                                || b->enable_state == bp_call_disabled)
6771                               ? " (disabled)"
6772                               : ""),
6773                              (others > 1) ? "," 
6774                              : ((others == 1) ? " and" : ""));
6775           }
6776       printf_filtered (_("also set at pc "));
6777       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6778       printf_filtered (".\n");
6779     }
6780 }
6781 \f
6782
6783 /* Return true iff it is meaningful to use the address member of
6784    BPT locations.  For some breakpoint types, the locations' address members
6785    are irrelevant and it makes no sense to attempt to compare them to other
6786    addresses (or use them for any other purpose either).
6787
6788    More specifically, each of the following breakpoint types will
6789    always have a zero valued location address and we don't want to mark
6790    breakpoints of any of these types to be a duplicate of an actual
6791    breakpoint location at address zero:
6792
6793       bp_watchpoint
6794       bp_catchpoint
6795
6796 */
6797
6798 static int
6799 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6800 {
6801   enum bptype type = bpt->type;
6802
6803   return (type != bp_watchpoint && type != bp_catchpoint);
6804 }
6805
6806 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6807    true if LOC1 and LOC2 represent the same watchpoint location.  */
6808
6809 static int
6810 watchpoint_locations_match (struct bp_location *loc1, 
6811                             struct bp_location *loc2)
6812 {
6813   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6814   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6815
6816   /* Both of them must exist.  */
6817   gdb_assert (w1 != NULL);
6818   gdb_assert (w2 != NULL);
6819
6820   /* If the target can evaluate the condition expression in hardware,
6821      then we we need to insert both watchpoints even if they are at
6822      the same place.  Otherwise the watchpoint will only trigger when
6823      the condition of whichever watchpoint was inserted evaluates to
6824      true, not giving a chance for GDB to check the condition of the
6825      other watchpoint.  */
6826   if ((w1->cond_exp
6827        && target_can_accel_watchpoint_condition (loc1->address, 
6828                                                  loc1->length,
6829                                                  loc1->watchpoint_type,
6830                                                  w1->cond_exp.get ()))
6831       || (w2->cond_exp
6832           && target_can_accel_watchpoint_condition (loc2->address, 
6833                                                     loc2->length,
6834                                                     loc2->watchpoint_type,
6835                                                     w2->cond_exp.get ())))
6836     return 0;
6837
6838   /* Note that this checks the owner's type, not the location's.  In
6839      case the target does not support read watchpoints, but does
6840      support access watchpoints, we'll have bp_read_watchpoint
6841      watchpoints with hw_access locations.  Those should be considered
6842      duplicates of hw_read locations.  The hw_read locations will
6843      become hw_access locations later.  */
6844   return (loc1->owner->type == loc2->owner->type
6845           && loc1->pspace->aspace == loc2->pspace->aspace
6846           && loc1->address == loc2->address
6847           && loc1->length == loc2->length);
6848 }
6849
6850 /* See breakpoint.h.  */
6851
6852 int
6853 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
6854                           const address_space *aspace2, CORE_ADDR addr2)
6855 {
6856   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6857            || aspace1 == aspace2)
6858           && addr1 == addr2);
6859 }
6860
6861 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6862    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6863    matches ASPACE2.  On targets that have global breakpoints, the address
6864    space doesn't really matter.  */
6865
6866 static int
6867 breakpoint_address_match_range (const address_space *aspace1,
6868                                 CORE_ADDR addr1,
6869                                 int len1, const address_space *aspace2,
6870                                 CORE_ADDR addr2)
6871 {
6872   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6873            || aspace1 == aspace2)
6874           && addr2 >= addr1 && addr2 < addr1 + len1);
6875 }
6876
6877 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6878    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6879    matches the breakpoint's address space.  On targets that have global
6880    breakpoints, the address space doesn't really matter.  */
6881
6882 static int
6883 breakpoint_location_address_match (struct bp_location *bl,
6884                                    const address_space *aspace,
6885                                    CORE_ADDR addr)
6886 {
6887   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6888                                     aspace, addr)
6889           || (bl->length
6890               && breakpoint_address_match_range (bl->pspace->aspace,
6891                                                  bl->address, bl->length,
6892                                                  aspace, addr)));
6893 }
6894
6895 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
6896    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
6897    match happens only if ASPACE matches the breakpoint's address
6898    space.  On targets that have global breakpoints, the address space
6899    doesn't really matter.  */
6900
6901 static int
6902 breakpoint_location_address_range_overlap (struct bp_location *bl,
6903                                            const address_space *aspace,
6904                                            CORE_ADDR addr, int len)
6905 {
6906   if (gdbarch_has_global_breakpoints (target_gdbarch ())
6907       || bl->pspace->aspace == aspace)
6908     {
6909       int bl_len = bl->length != 0 ? bl->length : 1;
6910
6911       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
6912         return 1;
6913     }
6914   return 0;
6915 }
6916
6917 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6918    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6919    true, otherwise returns false.  */
6920
6921 static int
6922 tracepoint_locations_match (struct bp_location *loc1,
6923                             struct bp_location *loc2)
6924 {
6925   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6926     /* Since tracepoint locations are never duplicated with others', tracepoint
6927        locations at the same address of different tracepoints are regarded as
6928        different locations.  */
6929     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6930   else
6931     return 0;
6932 }
6933
6934 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6935    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6936    represent the same location.  */
6937
6938 static int
6939 breakpoint_locations_match (struct bp_location *loc1, 
6940                             struct bp_location *loc2)
6941 {
6942   int hw_point1, hw_point2;
6943
6944   /* Both of them must not be in moribund_locations.  */
6945   gdb_assert (loc1->owner != NULL);
6946   gdb_assert (loc2->owner != NULL);
6947
6948   hw_point1 = is_hardware_watchpoint (loc1->owner);
6949   hw_point2 = is_hardware_watchpoint (loc2->owner);
6950
6951   if (hw_point1 != hw_point2)
6952     return 0;
6953   else if (hw_point1)
6954     return watchpoint_locations_match (loc1, loc2);
6955   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6956     return tracepoint_locations_match (loc1, loc2);
6957   else
6958     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6959     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6960                                      loc2->pspace->aspace, loc2->address)
6961             && loc1->length == loc2->length);
6962 }
6963
6964 static void
6965 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6966                                int bnum, int have_bnum)
6967 {
6968   /* The longest string possibly returned by hex_string_custom
6969      is 50 chars.  These must be at least that big for safety.  */
6970   char astr1[64];
6971   char astr2[64];
6972
6973   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6974   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6975   if (have_bnum)
6976     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6977              bnum, astr1, astr2);
6978   else
6979     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6980 }
6981
6982 /* Adjust a breakpoint's address to account for architectural
6983    constraints on breakpoint placement.  Return the adjusted address.
6984    Note: Very few targets require this kind of adjustment.  For most
6985    targets, this function is simply the identity function.  */
6986
6987 static CORE_ADDR
6988 adjust_breakpoint_address (struct gdbarch *gdbarch,
6989                            CORE_ADDR bpaddr, enum bptype bptype)
6990 {
6991   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6992     {
6993       /* Very few targets need any kind of breakpoint adjustment.  */
6994       return bpaddr;
6995     }
6996   else if (bptype == bp_watchpoint
6997            || bptype == bp_hardware_watchpoint
6998            || bptype == bp_read_watchpoint
6999            || bptype == bp_access_watchpoint
7000            || bptype == bp_catchpoint)
7001     {
7002       /* Watchpoints and the various bp_catch_* eventpoints should not
7003          have their addresses modified.  */
7004       return bpaddr;
7005     }
7006   else if (bptype == bp_single_step)
7007     {
7008       /* Single-step breakpoints should not have their addresses
7009          modified.  If there's any architectural constrain that
7010          applies to this address, then it should have already been
7011          taken into account when the breakpoint was created in the
7012          first place.  If we didn't do this, stepping through e.g.,
7013          Thumb-2 IT blocks would break.  */
7014       return bpaddr;
7015     }
7016   else
7017     {
7018       CORE_ADDR adjusted_bpaddr;
7019
7020       /* Some targets have architectural constraints on the placement
7021          of breakpoint instructions.  Obtain the adjusted address.  */
7022       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7023
7024       /* An adjusted breakpoint address can significantly alter
7025          a user's expectations.  Print a warning if an adjustment
7026          is required.  */
7027       if (adjusted_bpaddr != bpaddr)
7028         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7029
7030       return adjusted_bpaddr;
7031     }
7032 }
7033
7034 bp_location::bp_location (const bp_location_ops *ops, breakpoint *owner)
7035 {
7036   bp_location *loc = this;
7037
7038   gdb_assert (ops != NULL);
7039
7040   loc->ops = ops;
7041   loc->owner = owner;
7042   loc->cond_bytecode = NULL;
7043   loc->shlib_disabled = 0;
7044   loc->enabled = 1;
7045
7046   switch (owner->type)
7047     {
7048     case bp_breakpoint:
7049     case bp_single_step:
7050     case bp_until:
7051     case bp_finish:
7052     case bp_longjmp:
7053     case bp_longjmp_resume:
7054     case bp_longjmp_call_dummy:
7055     case bp_exception:
7056     case bp_exception_resume:
7057     case bp_step_resume:
7058     case bp_hp_step_resume:
7059     case bp_watchpoint_scope:
7060     case bp_call_dummy:
7061     case bp_std_terminate:
7062     case bp_shlib_event:
7063     case bp_thread_event:
7064     case bp_overlay_event:
7065     case bp_jit_event:
7066     case bp_longjmp_master:
7067     case bp_std_terminate_master:
7068     case bp_exception_master:
7069     case bp_gnu_ifunc_resolver:
7070     case bp_gnu_ifunc_resolver_return:
7071     case bp_dprintf:
7072       loc->loc_type = bp_loc_software_breakpoint;
7073       mark_breakpoint_location_modified (loc);
7074       break;
7075     case bp_hardware_breakpoint:
7076       loc->loc_type = bp_loc_hardware_breakpoint;
7077       mark_breakpoint_location_modified (loc);
7078       break;
7079     case bp_hardware_watchpoint:
7080     case bp_read_watchpoint:
7081     case bp_access_watchpoint:
7082       loc->loc_type = bp_loc_hardware_watchpoint;
7083       break;
7084     case bp_watchpoint:
7085     case bp_catchpoint:
7086     case bp_tracepoint:
7087     case bp_fast_tracepoint:
7088     case bp_static_tracepoint:
7089       loc->loc_type = bp_loc_other;
7090       break;
7091     default:
7092       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7093     }
7094
7095   loc->refc = 1;
7096 }
7097
7098 /* Allocate a struct bp_location.  */
7099
7100 static struct bp_location *
7101 allocate_bp_location (struct breakpoint *bpt)
7102 {
7103   return bpt->ops->allocate_location (bpt);
7104 }
7105
7106 static void
7107 free_bp_location (struct bp_location *loc)
7108 {
7109   loc->ops->dtor (loc);
7110   delete loc;
7111 }
7112
7113 /* Increment reference count.  */
7114
7115 static void
7116 incref_bp_location (struct bp_location *bl)
7117 {
7118   ++bl->refc;
7119 }
7120
7121 /* Decrement reference count.  If the reference count reaches 0,
7122    destroy the bp_location.  Sets *BLP to NULL.  */
7123
7124 static void
7125 decref_bp_location (struct bp_location **blp)
7126 {
7127   gdb_assert ((*blp)->refc > 0);
7128
7129   if (--(*blp)->refc == 0)
7130     free_bp_location (*blp);
7131   *blp = NULL;
7132 }
7133
7134 /* Add breakpoint B at the end of the global breakpoint chain.  */
7135
7136 static breakpoint *
7137 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7138 {
7139   struct breakpoint *b1;
7140   struct breakpoint *result = b.get ();
7141
7142   /* Add this breakpoint to the end of the chain so that a list of
7143      breakpoints will come out in order of increasing numbers.  */
7144
7145   b1 = breakpoint_chain;
7146   if (b1 == 0)
7147     breakpoint_chain = b.release ();
7148   else
7149     {
7150       while (b1->next)
7151         b1 = b1->next;
7152       b1->next = b.release ();
7153     }
7154
7155   return result;
7156 }
7157
7158 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7159
7160 static void
7161 init_raw_breakpoint_without_location (struct breakpoint *b,
7162                                       struct gdbarch *gdbarch,
7163                                       enum bptype bptype,
7164                                       const struct breakpoint_ops *ops)
7165 {
7166   gdb_assert (ops != NULL);
7167
7168   b->ops = ops;
7169   b->type = bptype;
7170   b->gdbarch = gdbarch;
7171   b->language = current_language->la_language;
7172   b->input_radix = input_radix;
7173   b->related_breakpoint = b;
7174 }
7175
7176 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7177    that has type BPTYPE and has no locations as yet.  */
7178
7179 static struct breakpoint *
7180 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7181                                      enum bptype bptype,
7182                                      const struct breakpoint_ops *ops)
7183 {
7184   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7185
7186   init_raw_breakpoint_without_location (b.get (), gdbarch, bptype, ops);
7187   return add_to_breakpoint_chain (std::move (b));
7188 }
7189
7190 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7191    resolutions should be made as the user specified the location explicitly
7192    enough.  */
7193
7194 static void
7195 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7196 {
7197   gdb_assert (loc->owner != NULL);
7198
7199   if (loc->owner->type == bp_breakpoint
7200       || loc->owner->type == bp_hardware_breakpoint
7201       || is_tracepoint (loc->owner))
7202     {
7203       int is_gnu_ifunc;
7204       const char *function_name;
7205       CORE_ADDR func_addr;
7206
7207       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7208                                           &func_addr, NULL, &is_gnu_ifunc);
7209
7210       if (is_gnu_ifunc && !explicit_loc)
7211         {
7212           struct breakpoint *b = loc->owner;
7213
7214           gdb_assert (loc->pspace == current_program_space);
7215           if (gnu_ifunc_resolve_name (function_name,
7216                                       &loc->requested_address))
7217             {
7218               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7219               loc->address = adjust_breakpoint_address (loc->gdbarch,
7220                                                         loc->requested_address,
7221                                                         b->type);
7222             }
7223           else if (b->type == bp_breakpoint && b->loc == loc
7224                    && loc->next == NULL && b->related_breakpoint == b)
7225             {
7226               /* Create only the whole new breakpoint of this type but do not
7227                  mess more complicated breakpoints with multiple locations.  */
7228               b->type = bp_gnu_ifunc_resolver;
7229               /* Remember the resolver's address for use by the return
7230                  breakpoint.  */
7231               loc->related_address = func_addr;
7232             }
7233         }
7234
7235       if (function_name)
7236         loc->function_name = xstrdup (function_name);
7237     }
7238 }
7239
7240 /* Attempt to determine architecture of location identified by SAL.  */
7241 struct gdbarch *
7242 get_sal_arch (struct symtab_and_line sal)
7243 {
7244   if (sal.section)
7245     return get_objfile_arch (sal.section->objfile);
7246   if (sal.symtab)
7247     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7248
7249   return NULL;
7250 }
7251
7252 /* Low level routine for partially initializing a breakpoint of type
7253    BPTYPE.  The newly created breakpoint's address, section, source
7254    file name, and line number are provided by SAL.
7255
7256    It is expected that the caller will complete the initialization of
7257    the newly created breakpoint struct as well as output any status
7258    information regarding the creation of a new breakpoint.  */
7259
7260 static void
7261 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7262                      struct symtab_and_line sal, enum bptype bptype,
7263                      const struct breakpoint_ops *ops)
7264 {
7265   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7266
7267   add_location_to_breakpoint (b, &sal);
7268
7269   if (bptype != bp_catchpoint)
7270     gdb_assert (sal.pspace != NULL);
7271
7272   /* Store the program space that was used to set the breakpoint,
7273      except for ordinary breakpoints, which are independent of the
7274      program space.  */
7275   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7276     b->pspace = sal.pspace;
7277 }
7278
7279 /* set_raw_breakpoint is a low level routine for allocating and
7280    partially initializing a breakpoint of type BPTYPE.  The newly
7281    created breakpoint's address, section, source file name, and line
7282    number are provided by SAL.  The newly created and partially
7283    initialized breakpoint is added to the breakpoint chain and
7284    is also returned as the value of this function.
7285
7286    It is expected that the caller will complete the initialization of
7287    the newly created breakpoint struct as well as output any status
7288    information regarding the creation of a new breakpoint.  In
7289    particular, set_raw_breakpoint does NOT set the breakpoint
7290    number!  Care should be taken to not allow an error to occur
7291    prior to completing the initialization of the breakpoint.  If this
7292    should happen, a bogus breakpoint will be left on the chain.  */
7293
7294 struct breakpoint *
7295 set_raw_breakpoint (struct gdbarch *gdbarch,
7296                     struct symtab_and_line sal, enum bptype bptype,
7297                     const struct breakpoint_ops *ops)
7298 {
7299   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7300
7301   init_raw_breakpoint (b.get (), gdbarch, sal, bptype, ops);
7302   return add_to_breakpoint_chain (std::move (b));
7303 }
7304
7305 /* Call this routine when stepping and nexting to enable a breakpoint
7306    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7307    initiated the operation.  */
7308
7309 void
7310 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7311 {
7312   struct breakpoint *b, *b_tmp;
7313   int thread = tp->global_num;
7314
7315   /* To avoid having to rescan all objfile symbols at every step,
7316      we maintain a list of continually-inserted but always disabled
7317      longjmp "master" breakpoints.  Here, we simply create momentary
7318      clones of those and enable them for the requested thread.  */
7319   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7320     if (b->pspace == current_program_space
7321         && (b->type == bp_longjmp_master
7322             || b->type == bp_exception_master))
7323       {
7324         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7325         struct breakpoint *clone;
7326
7327         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7328            after their removal.  */
7329         clone = momentary_breakpoint_from_master (b, type,
7330                                                   &momentary_breakpoint_ops, 1);
7331         clone->thread = thread;
7332       }
7333
7334   tp->initiating_frame = frame;
7335 }
7336
7337 /* Delete all longjmp breakpoints from THREAD.  */
7338 void
7339 delete_longjmp_breakpoint (int thread)
7340 {
7341   struct breakpoint *b, *b_tmp;
7342
7343   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7344     if (b->type == bp_longjmp || b->type == bp_exception)
7345       {
7346         if (b->thread == thread)
7347           delete_breakpoint (b);
7348       }
7349 }
7350
7351 void
7352 delete_longjmp_breakpoint_at_next_stop (int thread)
7353 {
7354   struct breakpoint *b, *b_tmp;
7355
7356   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7357     if (b->type == bp_longjmp || b->type == bp_exception)
7358       {
7359         if (b->thread == thread)
7360           b->disposition = disp_del_at_next_stop;
7361       }
7362 }
7363
7364 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7365    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7366    pointer to any of them.  Return NULL if this system cannot place longjmp
7367    breakpoints.  */
7368
7369 struct breakpoint *
7370 set_longjmp_breakpoint_for_call_dummy (void)
7371 {
7372   struct breakpoint *b, *retval = NULL;
7373
7374   ALL_BREAKPOINTS (b)
7375     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7376       {
7377         struct breakpoint *new_b;
7378
7379         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7380                                                   &momentary_breakpoint_ops,
7381                                                   1);
7382         new_b->thread = ptid_to_global_thread_id (inferior_ptid);
7383
7384         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7385
7386         gdb_assert (new_b->related_breakpoint == new_b);
7387         if (retval == NULL)
7388           retval = new_b;
7389         new_b->related_breakpoint = retval;
7390         while (retval->related_breakpoint != new_b->related_breakpoint)
7391           retval = retval->related_breakpoint;
7392         retval->related_breakpoint = new_b;
7393       }
7394
7395   return retval;
7396 }
7397
7398 /* Verify all existing dummy frames and their associated breakpoints for
7399    TP.  Remove those which can no longer be found in the current frame
7400    stack.
7401
7402    You should call this function only at places where it is safe to currently
7403    unwind the whole stack.  Failed stack unwind would discard live dummy
7404    frames.  */
7405
7406 void
7407 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7408 {
7409   struct breakpoint *b, *b_tmp;
7410
7411   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7412     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7413       {
7414         struct breakpoint *dummy_b = b->related_breakpoint;
7415
7416         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7417           dummy_b = dummy_b->related_breakpoint;
7418         if (dummy_b->type != bp_call_dummy
7419             || frame_find_by_id (dummy_b->frame_id) != NULL)
7420           continue;
7421         
7422         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7423
7424         while (b->related_breakpoint != b)
7425           {
7426             if (b_tmp == b->related_breakpoint)
7427               b_tmp = b->related_breakpoint->next;
7428             delete_breakpoint (b->related_breakpoint);
7429           }
7430         delete_breakpoint (b);
7431       }
7432 }
7433
7434 void
7435 enable_overlay_breakpoints (void)
7436 {
7437   struct breakpoint *b;
7438
7439   ALL_BREAKPOINTS (b)
7440     if (b->type == bp_overlay_event)
7441     {
7442       b->enable_state = bp_enabled;
7443       update_global_location_list (UGLL_MAY_INSERT);
7444       overlay_events_enabled = 1;
7445     }
7446 }
7447
7448 void
7449 disable_overlay_breakpoints (void)
7450 {
7451   struct breakpoint *b;
7452
7453   ALL_BREAKPOINTS (b)
7454     if (b->type == bp_overlay_event)
7455     {
7456       b->enable_state = bp_disabled;
7457       update_global_location_list (UGLL_DONT_INSERT);
7458       overlay_events_enabled = 0;
7459     }
7460 }
7461
7462 /* Set an active std::terminate breakpoint for each std::terminate
7463    master breakpoint.  */
7464 void
7465 set_std_terminate_breakpoint (void)
7466 {
7467   struct breakpoint *b, *b_tmp;
7468
7469   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7470     if (b->pspace == current_program_space
7471         && b->type == bp_std_terminate_master)
7472       {
7473         momentary_breakpoint_from_master (b, bp_std_terminate,
7474                                           &momentary_breakpoint_ops, 1);
7475       }
7476 }
7477
7478 /* Delete all the std::terminate breakpoints.  */
7479 void
7480 delete_std_terminate_breakpoint (void)
7481 {
7482   struct breakpoint *b, *b_tmp;
7483
7484   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7485     if (b->type == bp_std_terminate)
7486       delete_breakpoint (b);
7487 }
7488
7489 struct breakpoint *
7490 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7491 {
7492   struct breakpoint *b;
7493
7494   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7495                                   &internal_breakpoint_ops);
7496
7497   b->enable_state = bp_enabled;
7498   /* location has to be used or breakpoint_re_set will delete me.  */
7499   b->location = new_address_location (b->loc->address, NULL, 0);
7500
7501   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7502
7503   return b;
7504 }
7505
7506 struct lang_and_radix
7507   {
7508     enum language lang;
7509     int radix;
7510   };
7511
7512 /* Create a breakpoint for JIT code registration and unregistration.  */
7513
7514 struct breakpoint *
7515 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7516 {
7517   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7518                                      &internal_breakpoint_ops);
7519 }
7520
7521 /* Remove JIT code registration and unregistration breakpoint(s).  */
7522
7523 void
7524 remove_jit_event_breakpoints (void)
7525 {
7526   struct breakpoint *b, *b_tmp;
7527
7528   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7529     if (b->type == bp_jit_event
7530         && b->loc->pspace == current_program_space)
7531       delete_breakpoint (b);
7532 }
7533
7534 void
7535 remove_solib_event_breakpoints (void)
7536 {
7537   struct breakpoint *b, *b_tmp;
7538
7539   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7540     if (b->type == bp_shlib_event
7541         && b->loc->pspace == current_program_space)
7542       delete_breakpoint (b);
7543 }
7544
7545 /* See breakpoint.h.  */
7546
7547 void
7548 remove_solib_event_breakpoints_at_next_stop (void)
7549 {
7550   struct breakpoint *b, *b_tmp;
7551
7552   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7553     if (b->type == bp_shlib_event
7554         && b->loc->pspace == current_program_space)
7555       b->disposition = disp_del_at_next_stop;
7556 }
7557
7558 /* Helper for create_solib_event_breakpoint /
7559    create_and_insert_solib_event_breakpoint.  Allows specifying which
7560    INSERT_MODE to pass through to update_global_location_list.  */
7561
7562 static struct breakpoint *
7563 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7564                                  enum ugll_insert_mode insert_mode)
7565 {
7566   struct breakpoint *b;
7567
7568   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7569                                   &internal_breakpoint_ops);
7570   update_global_location_list_nothrow (insert_mode);
7571   return b;
7572 }
7573
7574 struct breakpoint *
7575 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7576 {
7577   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7578 }
7579
7580 /* See breakpoint.h.  */
7581
7582 struct breakpoint *
7583 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7584 {
7585   struct breakpoint *b;
7586
7587   /* Explicitly tell update_global_location_list to insert
7588      locations.  */
7589   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7590   if (!b->loc->inserted)
7591     {
7592       delete_breakpoint (b);
7593       return NULL;
7594     }
7595   return b;
7596 }
7597
7598 /* Disable any breakpoints that are on code in shared libraries.  Only
7599    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7600
7601 void
7602 disable_breakpoints_in_shlibs (void)
7603 {
7604   struct bp_location *loc, **locp_tmp;
7605
7606   ALL_BP_LOCATIONS (loc, locp_tmp)
7607   {
7608     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7609     struct breakpoint *b = loc->owner;
7610
7611     /* We apply the check to all breakpoints, including disabled for
7612        those with loc->duplicate set.  This is so that when breakpoint
7613        becomes enabled, or the duplicate is removed, gdb will try to
7614        insert all breakpoints.  If we don't set shlib_disabled here,
7615        we'll try to insert those breakpoints and fail.  */
7616     if (((b->type == bp_breakpoint)
7617          || (b->type == bp_jit_event)
7618          || (b->type == bp_hardware_breakpoint)
7619          || (is_tracepoint (b)))
7620         && loc->pspace == current_program_space
7621         && !loc->shlib_disabled
7622         && solib_name_from_address (loc->pspace, loc->address)
7623         )
7624       {
7625         loc->shlib_disabled = 1;
7626       }
7627   }
7628 }
7629
7630 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7631    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7632    disabled ones can just stay disabled.  */
7633
7634 static void
7635 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7636 {
7637   struct bp_location *loc, **locp_tmp;
7638   int disabled_shlib_breaks = 0;
7639
7640   ALL_BP_LOCATIONS (loc, locp_tmp)
7641   {
7642     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7643     struct breakpoint *b = loc->owner;
7644
7645     if (solib->pspace == loc->pspace
7646         && !loc->shlib_disabled
7647         && (((b->type == bp_breakpoint
7648               || b->type == bp_jit_event
7649               || b->type == bp_hardware_breakpoint)
7650              && (loc->loc_type == bp_loc_hardware_breakpoint
7651                  || loc->loc_type == bp_loc_software_breakpoint))
7652             || is_tracepoint (b))
7653         && solib_contains_address_p (solib, loc->address))
7654       {
7655         loc->shlib_disabled = 1;
7656         /* At this point, we cannot rely on remove_breakpoint
7657            succeeding so we must mark the breakpoint as not inserted
7658            to prevent future errors occurring in remove_breakpoints.  */
7659         loc->inserted = 0;
7660
7661         /* This may cause duplicate notifications for the same breakpoint.  */
7662         observer_notify_breakpoint_modified (b);
7663
7664         if (!disabled_shlib_breaks)
7665           {
7666             target_terminal::ours_for_output ();
7667             warning (_("Temporarily disabling breakpoints "
7668                        "for unloaded shared library \"%s\""),
7669                      solib->so_name);
7670           }
7671         disabled_shlib_breaks = 1;
7672       }
7673   }
7674 }
7675
7676 /* Disable any breakpoints and tracepoints in OBJFILE upon
7677    notification of free_objfile.  Only apply to enabled breakpoints,
7678    disabled ones can just stay disabled.  */
7679
7680 static void
7681 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7682 {
7683   struct breakpoint *b;
7684
7685   if (objfile == NULL)
7686     return;
7687
7688   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7689      managed by the user with add-symbol-file/remove-symbol-file.
7690      Similarly to how breakpoints in shared libraries are handled in
7691      response to "nosharedlibrary", mark breakpoints in such modules
7692      shlib_disabled so they end up uninserted on the next global
7693      location list update.  Shared libraries not loaded by the user
7694      aren't handled here -- they're already handled in
7695      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7696      solib_unloaded observer.  We skip objfiles that are not
7697      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7698      main objfile).  */
7699   if ((objfile->flags & OBJF_SHARED) == 0
7700       || (objfile->flags & OBJF_USERLOADED) == 0)
7701     return;
7702
7703   ALL_BREAKPOINTS (b)
7704     {
7705       struct bp_location *loc;
7706       int bp_modified = 0;
7707
7708       if (!is_breakpoint (b) && !is_tracepoint (b))
7709         continue;
7710
7711       for (loc = b->loc; loc != NULL; loc = loc->next)
7712         {
7713           CORE_ADDR loc_addr = loc->address;
7714
7715           if (loc->loc_type != bp_loc_hardware_breakpoint
7716               && loc->loc_type != bp_loc_software_breakpoint)
7717             continue;
7718
7719           if (loc->shlib_disabled != 0)
7720             continue;
7721
7722           if (objfile->pspace != loc->pspace)
7723             continue;
7724
7725           if (loc->loc_type != bp_loc_hardware_breakpoint
7726               && loc->loc_type != bp_loc_software_breakpoint)
7727             continue;
7728
7729           if (is_addr_in_objfile (loc_addr, objfile))
7730             {
7731               loc->shlib_disabled = 1;
7732               /* At this point, we don't know whether the object was
7733                  unmapped from the inferior or not, so leave the
7734                  inserted flag alone.  We'll handle failure to
7735                  uninsert quietly, in case the object was indeed
7736                  unmapped.  */
7737
7738               mark_breakpoint_location_modified (loc);
7739
7740               bp_modified = 1;
7741             }
7742         }
7743
7744       if (bp_modified)
7745         observer_notify_breakpoint_modified (b);
7746     }
7747 }
7748
7749 /* FORK & VFORK catchpoints.  */
7750
7751 /* An instance of this type is used to represent a fork or vfork
7752    catchpoint.  A breakpoint is really of this type iff its ops pointer points
7753    to CATCH_FORK_BREAKPOINT_OPS.  */
7754
7755 struct fork_catchpoint : public breakpoint
7756 {
7757   /* Process id of a child process whose forking triggered this
7758      catchpoint.  This field is only valid immediately after this
7759      catchpoint has triggered.  */
7760   ptid_t forked_inferior_pid;
7761 };
7762
7763 /* Implement the "insert" breakpoint_ops method for fork
7764    catchpoints.  */
7765
7766 static int
7767 insert_catch_fork (struct bp_location *bl)
7768 {
7769   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7770 }
7771
7772 /* Implement the "remove" breakpoint_ops method for fork
7773    catchpoints.  */
7774
7775 static int
7776 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
7777 {
7778   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7779 }
7780
7781 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7782    catchpoints.  */
7783
7784 static int
7785 breakpoint_hit_catch_fork (const struct bp_location *bl,
7786                            const address_space *aspace, CORE_ADDR bp_addr,
7787                            const struct target_waitstatus *ws)
7788 {
7789   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7790
7791   if (ws->kind != TARGET_WAITKIND_FORKED)
7792     return 0;
7793
7794   c->forked_inferior_pid = ws->value.related_pid;
7795   return 1;
7796 }
7797
7798 /* Implement the "print_it" breakpoint_ops method for fork
7799    catchpoints.  */
7800
7801 static enum print_stop_action
7802 print_it_catch_fork (bpstat bs)
7803 {
7804   struct ui_out *uiout = current_uiout;
7805   struct breakpoint *b = bs->breakpoint_at;
7806   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7807
7808   annotate_catchpoint (b->number);
7809   maybe_print_thread_hit_breakpoint (uiout);
7810   if (b->disposition == disp_del)
7811     uiout->text ("Temporary catchpoint ");
7812   else
7813     uiout->text ("Catchpoint ");
7814   if (uiout->is_mi_like_p ())
7815     {
7816       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
7817       uiout->field_string ("disp", bpdisp_text (b->disposition));
7818     }
7819   uiout->field_int ("bkptno", b->number);
7820   uiout->text (" (forked process ");
7821   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
7822   uiout->text ("), ");
7823   return PRINT_SRC_AND_LOC;
7824 }
7825
7826 /* Implement the "print_one" breakpoint_ops method for fork
7827    catchpoints.  */
7828
7829 static void
7830 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7831 {
7832   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7833   struct value_print_options opts;
7834   struct ui_out *uiout = current_uiout;
7835
7836   get_user_print_options (&opts);
7837
7838   /* Field 4, the address, is omitted (which makes the columns not
7839      line up too nicely with the headers, but the effect is relatively
7840      readable).  */
7841   if (opts.addressprint)
7842     uiout->field_skip ("addr");
7843   annotate_field (5);
7844   uiout->text ("fork");
7845   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7846     {
7847       uiout->text (", process ");
7848       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
7849       uiout->spaces (1);
7850     }
7851
7852   if (uiout->is_mi_like_p ())
7853     uiout->field_string ("catch-type", "fork");
7854 }
7855
7856 /* Implement the "print_mention" breakpoint_ops method for fork
7857    catchpoints.  */
7858
7859 static void
7860 print_mention_catch_fork (struct breakpoint *b)
7861 {
7862   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7863 }
7864
7865 /* Implement the "print_recreate" breakpoint_ops method for fork
7866    catchpoints.  */
7867
7868 static void
7869 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7870 {
7871   fprintf_unfiltered (fp, "catch fork");
7872   print_recreate_thread (b, fp);
7873 }
7874
7875 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7876
7877 static struct breakpoint_ops catch_fork_breakpoint_ops;
7878
7879 /* Implement the "insert" breakpoint_ops method for vfork
7880    catchpoints.  */
7881
7882 static int
7883 insert_catch_vfork (struct bp_location *bl)
7884 {
7885   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7886 }
7887
7888 /* Implement the "remove" breakpoint_ops method for vfork
7889    catchpoints.  */
7890
7891 static int
7892 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
7893 {
7894   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7895 }
7896
7897 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7898    catchpoints.  */
7899
7900 static int
7901 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7902                             const address_space *aspace, CORE_ADDR bp_addr,
7903                             const struct target_waitstatus *ws)
7904 {
7905   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7906
7907   if (ws->kind != TARGET_WAITKIND_VFORKED)
7908     return 0;
7909
7910   c->forked_inferior_pid = ws->value.related_pid;
7911   return 1;
7912 }
7913
7914 /* Implement the "print_it" breakpoint_ops method for vfork
7915    catchpoints.  */
7916
7917 static enum print_stop_action
7918 print_it_catch_vfork (bpstat bs)
7919 {
7920   struct ui_out *uiout = current_uiout;
7921   struct breakpoint *b = bs->breakpoint_at;
7922   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7923
7924   annotate_catchpoint (b->number);
7925   maybe_print_thread_hit_breakpoint (uiout);
7926   if (b->disposition == disp_del)
7927     uiout->text ("Temporary catchpoint ");
7928   else
7929     uiout->text ("Catchpoint ");
7930   if (uiout->is_mi_like_p ())
7931     {
7932       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
7933       uiout->field_string ("disp", bpdisp_text (b->disposition));
7934     }
7935   uiout->field_int ("bkptno", b->number);
7936   uiout->text (" (vforked process ");
7937   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
7938   uiout->text ("), ");
7939   return PRINT_SRC_AND_LOC;
7940 }
7941
7942 /* Implement the "print_one" breakpoint_ops method for vfork
7943    catchpoints.  */
7944
7945 static void
7946 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7947 {
7948   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7949   struct value_print_options opts;
7950   struct ui_out *uiout = current_uiout;
7951
7952   get_user_print_options (&opts);
7953   /* Field 4, the address, is omitted (which makes the columns not
7954      line up too nicely with the headers, but the effect is relatively
7955      readable).  */
7956   if (opts.addressprint)
7957     uiout->field_skip ("addr");
7958   annotate_field (5);
7959   uiout->text ("vfork");
7960   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7961     {
7962       uiout->text (", process ");
7963       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
7964       uiout->spaces (1);
7965     }
7966
7967   if (uiout->is_mi_like_p ())
7968     uiout->field_string ("catch-type", "vfork");
7969 }
7970
7971 /* Implement the "print_mention" breakpoint_ops method for vfork
7972    catchpoints.  */
7973
7974 static void
7975 print_mention_catch_vfork (struct breakpoint *b)
7976 {
7977   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7978 }
7979
7980 /* Implement the "print_recreate" breakpoint_ops method for vfork
7981    catchpoints.  */
7982
7983 static void
7984 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7985 {
7986   fprintf_unfiltered (fp, "catch vfork");
7987   print_recreate_thread (b, fp);
7988 }
7989
7990 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7991
7992 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7993
7994 /* An instance of this type is used to represent an solib catchpoint.
7995    A breakpoint is really of this type iff its ops pointer points to
7996    CATCH_SOLIB_BREAKPOINT_OPS.  */
7997
7998 struct solib_catchpoint : public breakpoint
7999 {
8000   ~solib_catchpoint () override;
8001
8002   /* True for "catch load", false for "catch unload".  */
8003   unsigned char is_load;
8004
8005   /* Regular expression to match, if any.  COMPILED is only valid when
8006      REGEX is non-NULL.  */
8007   char *regex;
8008   std::unique_ptr<compiled_regex> compiled;
8009 };
8010
8011 solib_catchpoint::~solib_catchpoint ()
8012 {
8013   xfree (this->regex);
8014 }
8015
8016 static int
8017 insert_catch_solib (struct bp_location *ignore)
8018 {
8019   return 0;
8020 }
8021
8022 static int
8023 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
8024 {
8025   return 0;
8026 }
8027
8028 static int
8029 breakpoint_hit_catch_solib (const struct bp_location *bl,
8030                             const address_space *aspace,
8031                             CORE_ADDR bp_addr,
8032                             const struct target_waitstatus *ws)
8033 {
8034   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8035   struct breakpoint *other;
8036
8037   if (ws->kind == TARGET_WAITKIND_LOADED)
8038     return 1;
8039
8040   ALL_BREAKPOINTS (other)
8041   {
8042     struct bp_location *other_bl;
8043
8044     if (other == bl->owner)
8045       continue;
8046
8047     if (other->type != bp_shlib_event)
8048       continue;
8049
8050     if (self->pspace != NULL && other->pspace != self->pspace)
8051       continue;
8052
8053     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8054       {
8055         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8056           return 1;
8057       }
8058   }
8059
8060   return 0;
8061 }
8062
8063 static void
8064 check_status_catch_solib (struct bpstats *bs)
8065 {
8066   struct solib_catchpoint *self
8067     = (struct solib_catchpoint *) bs->breakpoint_at;
8068   int ix;
8069
8070   if (self->is_load)
8071     {
8072       struct so_list *iter;
8073
8074       for (ix = 0;
8075            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8076                         ix, iter);
8077            ++ix)
8078         {
8079           if (!self->regex
8080               || self->compiled->exec (iter->so_name, 0, NULL, 0) == 0)
8081             return;
8082         }
8083     }
8084   else
8085     {
8086       char *iter;
8087
8088       for (ix = 0;
8089            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8090                         ix, iter);
8091            ++ix)
8092         {
8093           if (!self->regex
8094               || self->compiled->exec (iter, 0, NULL, 0) == 0)
8095             return;
8096         }
8097     }
8098
8099   bs->stop = 0;
8100   bs->print_it = print_it_noop;
8101 }
8102
8103 static enum print_stop_action
8104 print_it_catch_solib (bpstat bs)
8105 {
8106   struct breakpoint *b = bs->breakpoint_at;
8107   struct ui_out *uiout = current_uiout;
8108
8109   annotate_catchpoint (b->number);
8110   maybe_print_thread_hit_breakpoint (uiout);
8111   if (b->disposition == disp_del)
8112     uiout->text ("Temporary catchpoint ");
8113   else
8114     uiout->text ("Catchpoint ");
8115   uiout->field_int ("bkptno", b->number);
8116   uiout->text ("\n");
8117   if (uiout->is_mi_like_p ())
8118     uiout->field_string ("disp", bpdisp_text (b->disposition));
8119   print_solib_event (1);
8120   return PRINT_SRC_AND_LOC;
8121 }
8122
8123 static void
8124 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8125 {
8126   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8127   struct value_print_options opts;
8128   struct ui_out *uiout = current_uiout;
8129   char *msg;
8130
8131   get_user_print_options (&opts);
8132   /* Field 4, the address, is omitted (which makes the columns not
8133      line up too nicely with the headers, but the effect is relatively
8134      readable).  */
8135   if (opts.addressprint)
8136     {
8137       annotate_field (4);
8138       uiout->field_skip ("addr");
8139     }
8140
8141   annotate_field (5);
8142   if (self->is_load)
8143     {
8144       if (self->regex)
8145         msg = xstrprintf (_("load of library matching %s"), self->regex);
8146       else
8147         msg = xstrdup (_("load of library"));
8148     }
8149   else
8150     {
8151       if (self->regex)
8152         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8153       else
8154         msg = xstrdup (_("unload of library"));
8155     }
8156   uiout->field_string ("what", msg);
8157   xfree (msg);
8158
8159   if (uiout->is_mi_like_p ())
8160     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8161 }
8162
8163 static void
8164 print_mention_catch_solib (struct breakpoint *b)
8165 {
8166   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8167
8168   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8169                    self->is_load ? "load" : "unload");
8170 }
8171
8172 static void
8173 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8174 {
8175   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8176
8177   fprintf_unfiltered (fp, "%s %s",
8178                       b->disposition == disp_del ? "tcatch" : "catch",
8179                       self->is_load ? "load" : "unload");
8180   if (self->regex)
8181     fprintf_unfiltered (fp, " %s", self->regex);
8182   fprintf_unfiltered (fp, "\n");
8183 }
8184
8185 static struct breakpoint_ops catch_solib_breakpoint_ops;
8186
8187 /* Shared helper function (MI and CLI) for creating and installing
8188    a shared object event catchpoint.  If IS_LOAD is non-zero then
8189    the events to be caught are load events, otherwise they are
8190    unload events.  If IS_TEMP is non-zero the catchpoint is a
8191    temporary one.  If ENABLED is non-zero the catchpoint is
8192    created in an enabled state.  */
8193
8194 void
8195 add_solib_catchpoint (const char *arg, int is_load, int is_temp, int enabled)
8196 {
8197   struct gdbarch *gdbarch = get_current_arch ();
8198
8199   if (!arg)
8200     arg = "";
8201   arg = skip_spaces (arg);
8202
8203   std::unique_ptr<solib_catchpoint> c (new solib_catchpoint ());
8204
8205   if (*arg != '\0')
8206     {
8207       c->compiled.reset (new compiled_regex (arg, REG_NOSUB,
8208                                              _("Invalid regexp")));
8209       c->regex = xstrdup (arg);
8210     }
8211
8212   c->is_load = is_load;
8213   init_catchpoint (c.get (), gdbarch, is_temp, NULL,
8214                    &catch_solib_breakpoint_ops);
8215
8216   c->enable_state = enabled ? bp_enabled : bp_disabled;
8217
8218   install_breakpoint (0, std::move (c), 1);
8219 }
8220
8221 /* A helper function that does all the work for "catch load" and
8222    "catch unload".  */
8223
8224 static void
8225 catch_load_or_unload (const char *arg, int from_tty, int is_load,
8226                       struct cmd_list_element *command)
8227 {
8228   int tempflag;
8229   const int enabled = 1;
8230
8231   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8232
8233   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8234 }
8235
8236 static void
8237 catch_load_command_1 (const char *arg, int from_tty,
8238                       struct cmd_list_element *command)
8239 {
8240   catch_load_or_unload (arg, from_tty, 1, command);
8241 }
8242
8243 static void
8244 catch_unload_command_1 (const char *arg, int from_tty,
8245                         struct cmd_list_element *command)
8246 {
8247   catch_load_or_unload (arg, from_tty, 0, command);
8248 }
8249
8250 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8251    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8252    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8253    the breakpoint_ops structure associated to the catchpoint.  */
8254
8255 void
8256 init_catchpoint (struct breakpoint *b,
8257                  struct gdbarch *gdbarch, int tempflag,
8258                  const char *cond_string,
8259                  const struct breakpoint_ops *ops)
8260 {
8261   symtab_and_line sal;
8262   sal.pspace = current_program_space;
8263
8264   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8265
8266   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8267   b->disposition = tempflag ? disp_del : disp_donttouch;
8268 }
8269
8270 void
8271 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8272 {
8273   breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8274   set_breakpoint_number (internal, b);
8275   if (is_tracepoint (b))
8276     set_tracepoint_count (breakpoint_count);
8277   if (!internal)
8278     mention (b);
8279   observer_notify_breakpoint_created (b);
8280
8281   if (update_gll)
8282     update_global_location_list (UGLL_MAY_INSERT);
8283 }
8284
8285 static void
8286 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8287                                     int tempflag, const char *cond_string,
8288                                     const struct breakpoint_ops *ops)
8289 {
8290   std::unique_ptr<fork_catchpoint> c (new fork_catchpoint ());
8291
8292   init_catchpoint (c.get (), gdbarch, tempflag, cond_string, ops);
8293
8294   c->forked_inferior_pid = null_ptid;
8295
8296   install_breakpoint (0, std::move (c), 1);
8297 }
8298
8299 /* Exec catchpoints.  */
8300
8301 /* An instance of this type is used to represent an exec catchpoint.
8302    A breakpoint is really of this type iff its ops pointer points to
8303    CATCH_EXEC_BREAKPOINT_OPS.  */
8304
8305 struct exec_catchpoint : public breakpoint
8306 {
8307   ~exec_catchpoint () override;
8308
8309   /* Filename of a program whose exec triggered this catchpoint.
8310      This field is only valid immediately after this catchpoint has
8311      triggered.  */
8312   char *exec_pathname;
8313 };
8314
8315 /* Exec catchpoint destructor.  */
8316
8317 exec_catchpoint::~exec_catchpoint ()
8318 {
8319   xfree (this->exec_pathname);
8320 }
8321
8322 static int
8323 insert_catch_exec (struct bp_location *bl)
8324 {
8325   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8326 }
8327
8328 static int
8329 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8330 {
8331   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8332 }
8333
8334 static int
8335 breakpoint_hit_catch_exec (const struct bp_location *bl,
8336                            const address_space *aspace, CORE_ADDR bp_addr,
8337                            const struct target_waitstatus *ws)
8338 {
8339   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8340
8341   if (ws->kind != TARGET_WAITKIND_EXECD)
8342     return 0;
8343
8344   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8345   return 1;
8346 }
8347
8348 static enum print_stop_action
8349 print_it_catch_exec (bpstat bs)
8350 {
8351   struct ui_out *uiout = current_uiout;
8352   struct breakpoint *b = bs->breakpoint_at;
8353   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8354
8355   annotate_catchpoint (b->number);
8356   maybe_print_thread_hit_breakpoint (uiout);
8357   if (b->disposition == disp_del)
8358     uiout->text ("Temporary catchpoint ");
8359   else
8360     uiout->text ("Catchpoint ");
8361   if (uiout->is_mi_like_p ())
8362     {
8363       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8364       uiout->field_string ("disp", bpdisp_text (b->disposition));
8365     }
8366   uiout->field_int ("bkptno", b->number);
8367   uiout->text (" (exec'd ");
8368   uiout->field_string ("new-exec", c->exec_pathname);
8369   uiout->text ("), ");
8370
8371   return PRINT_SRC_AND_LOC;
8372 }
8373
8374 static void
8375 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8376 {
8377   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8378   struct value_print_options opts;
8379   struct ui_out *uiout = current_uiout;
8380
8381   get_user_print_options (&opts);
8382
8383   /* Field 4, the address, is omitted (which makes the columns
8384      not line up too nicely with the headers, but the effect
8385      is relatively readable).  */
8386   if (opts.addressprint)
8387     uiout->field_skip ("addr");
8388   annotate_field (5);
8389   uiout->text ("exec");
8390   if (c->exec_pathname != NULL)
8391     {
8392       uiout->text (", program \"");
8393       uiout->field_string ("what", c->exec_pathname);
8394       uiout->text ("\" ");
8395     }
8396
8397   if (uiout->is_mi_like_p ())
8398     uiout->field_string ("catch-type", "exec");
8399 }
8400
8401 static void
8402 print_mention_catch_exec (struct breakpoint *b)
8403 {
8404   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8405 }
8406
8407 /* Implement the "print_recreate" breakpoint_ops method for exec
8408    catchpoints.  */
8409
8410 static void
8411 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8412 {
8413   fprintf_unfiltered (fp, "catch exec");
8414   print_recreate_thread (b, fp);
8415 }
8416
8417 static struct breakpoint_ops catch_exec_breakpoint_ops;
8418
8419 static int
8420 hw_breakpoint_used_count (void)
8421 {
8422   int i = 0;
8423   struct breakpoint *b;
8424   struct bp_location *bl;
8425
8426   ALL_BREAKPOINTS (b)
8427   {
8428     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8429       for (bl = b->loc; bl; bl = bl->next)
8430         {
8431           /* Special types of hardware breakpoints may use more than
8432              one register.  */
8433           i += b->ops->resources_needed (bl);
8434         }
8435   }
8436
8437   return i;
8438 }
8439
8440 /* Returns the resources B would use if it were a hardware
8441    watchpoint.  */
8442
8443 static int
8444 hw_watchpoint_use_count (struct breakpoint *b)
8445 {
8446   int i = 0;
8447   struct bp_location *bl;
8448
8449   if (!breakpoint_enabled (b))
8450     return 0;
8451
8452   for (bl = b->loc; bl; bl = bl->next)
8453     {
8454       /* Special types of hardware watchpoints may use more than
8455          one register.  */
8456       i += b->ops->resources_needed (bl);
8457     }
8458
8459   return i;
8460 }
8461
8462 /* Returns the sum the used resources of all hardware watchpoints of
8463    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8464    the sum of the used resources of all hardware watchpoints of other
8465    types _not_ TYPE.  */
8466
8467 static int
8468 hw_watchpoint_used_count_others (struct breakpoint *except,
8469                                  enum bptype type, int *other_type_used)
8470 {
8471   int i = 0;
8472   struct breakpoint *b;
8473
8474   *other_type_used = 0;
8475   ALL_BREAKPOINTS (b)
8476     {
8477       if (b == except)
8478         continue;
8479       if (!breakpoint_enabled (b))
8480         continue;
8481
8482       if (b->type == type)
8483         i += hw_watchpoint_use_count (b);
8484       else if (is_hardware_watchpoint (b))
8485         *other_type_used = 1;
8486     }
8487
8488   return i;
8489 }
8490
8491 void
8492 disable_watchpoints_before_interactive_call_start (void)
8493 {
8494   struct breakpoint *b;
8495
8496   ALL_BREAKPOINTS (b)
8497   {
8498     if (is_watchpoint (b) && breakpoint_enabled (b))
8499       {
8500         b->enable_state = bp_call_disabled;
8501         update_global_location_list (UGLL_DONT_INSERT);
8502       }
8503   }
8504 }
8505
8506 void
8507 enable_watchpoints_after_interactive_call_stop (void)
8508 {
8509   struct breakpoint *b;
8510
8511   ALL_BREAKPOINTS (b)
8512   {
8513     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8514       {
8515         b->enable_state = bp_enabled;
8516         update_global_location_list (UGLL_MAY_INSERT);
8517       }
8518   }
8519 }
8520
8521 void
8522 disable_breakpoints_before_startup (void)
8523 {
8524   current_program_space->executing_startup = 1;
8525   update_global_location_list (UGLL_DONT_INSERT);
8526 }
8527
8528 void
8529 enable_breakpoints_after_startup (void)
8530 {
8531   current_program_space->executing_startup = 0;
8532   breakpoint_re_set ();
8533 }
8534
8535 /* Create a new single-step breakpoint for thread THREAD, with no
8536    locations.  */
8537
8538 static struct breakpoint *
8539 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8540 {
8541   std::unique_ptr<breakpoint> b (new breakpoint ());
8542
8543   init_raw_breakpoint_without_location (b.get (), gdbarch, bp_single_step,
8544                                         &momentary_breakpoint_ops);
8545
8546   b->disposition = disp_donttouch;
8547   b->frame_id = null_frame_id;
8548
8549   b->thread = thread;
8550   gdb_assert (b->thread != 0);
8551
8552   return add_to_breakpoint_chain (std::move (b));
8553 }
8554
8555 /* Set a momentary breakpoint of type TYPE at address specified by
8556    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8557    frame.  */
8558
8559 breakpoint_up
8560 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8561                           struct frame_id frame_id, enum bptype type)
8562 {
8563   struct breakpoint *b;
8564
8565   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8566      tail-called one.  */
8567   gdb_assert (!frame_id_artificial_p (frame_id));
8568
8569   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8570   b->enable_state = bp_enabled;
8571   b->disposition = disp_donttouch;
8572   b->frame_id = frame_id;
8573
8574   /* If we're debugging a multi-threaded program, then we want
8575      momentary breakpoints to be active in only a single thread of
8576      control.  */
8577   if (in_thread_list (inferior_ptid))
8578     b->thread = ptid_to_global_thread_id (inferior_ptid);
8579
8580   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8581
8582   return breakpoint_up (b);
8583 }
8584
8585 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8586    The new breakpoint will have type TYPE, use OPS as its
8587    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8588
8589 static struct breakpoint *
8590 momentary_breakpoint_from_master (struct breakpoint *orig,
8591                                   enum bptype type,
8592                                   const struct breakpoint_ops *ops,
8593                                   int loc_enabled)
8594 {
8595   struct breakpoint *copy;
8596
8597   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8598   copy->loc = allocate_bp_location (copy);
8599   set_breakpoint_location_function (copy->loc, 1);
8600
8601   copy->loc->gdbarch = orig->loc->gdbarch;
8602   copy->loc->requested_address = orig->loc->requested_address;
8603   copy->loc->address = orig->loc->address;
8604   copy->loc->section = orig->loc->section;
8605   copy->loc->pspace = orig->loc->pspace;
8606   copy->loc->probe = orig->loc->probe;
8607   copy->loc->line_number = orig->loc->line_number;
8608   copy->loc->symtab = orig->loc->symtab;
8609   copy->loc->enabled = loc_enabled;
8610   copy->frame_id = orig->frame_id;
8611   copy->thread = orig->thread;
8612   copy->pspace = orig->pspace;
8613
8614   copy->enable_state = bp_enabled;
8615   copy->disposition = disp_donttouch;
8616   copy->number = internal_breakpoint_number--;
8617
8618   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8619   return copy;
8620 }
8621
8622 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8623    ORIG is NULL.  */
8624
8625 struct breakpoint *
8626 clone_momentary_breakpoint (struct breakpoint *orig)
8627 {
8628   /* If there's nothing to clone, then return nothing.  */
8629   if (orig == NULL)
8630     return NULL;
8631
8632   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8633 }
8634
8635 breakpoint_up
8636 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8637                                 enum bptype type)
8638 {
8639   struct symtab_and_line sal;
8640
8641   sal = find_pc_line (pc, 0);
8642   sal.pc = pc;
8643   sal.section = find_pc_overlay (pc);
8644   sal.explicit_pc = 1;
8645
8646   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8647 }
8648 \f
8649
8650 /* Tell the user we have just set a breakpoint B.  */
8651
8652 static void
8653 mention (struct breakpoint *b)
8654 {
8655   b->ops->print_mention (b);
8656   if (current_uiout->is_mi_like_p ())
8657     return;
8658   printf_filtered ("\n");
8659 }
8660 \f
8661
8662 static int bp_loc_is_permanent (struct bp_location *loc);
8663
8664 static struct bp_location *
8665 add_location_to_breakpoint (struct breakpoint *b,
8666                             const struct symtab_and_line *sal)
8667 {
8668   struct bp_location *loc, **tmp;
8669   CORE_ADDR adjusted_address;
8670   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8671
8672   if (loc_gdbarch == NULL)
8673     loc_gdbarch = b->gdbarch;
8674
8675   /* Adjust the breakpoint's address prior to allocating a location.
8676      Once we call allocate_bp_location(), that mostly uninitialized
8677      location will be placed on the location chain.  Adjustment of the
8678      breakpoint may cause target_read_memory() to be called and we do
8679      not want its scan of the location chain to find a breakpoint and
8680      location that's only been partially initialized.  */
8681   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8682                                                 sal->pc, b->type);
8683
8684   /* Sort the locations by their ADDRESS.  */
8685   loc = allocate_bp_location (b);
8686   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8687        tmp = &((*tmp)->next))
8688     ;
8689   loc->next = *tmp;
8690   *tmp = loc;
8691
8692   loc->requested_address = sal->pc;
8693   loc->address = adjusted_address;
8694   loc->pspace = sal->pspace;
8695   loc->probe.prob = sal->prob;
8696   loc->probe.objfile = sal->objfile;
8697   gdb_assert (loc->pspace != NULL);
8698   loc->section = sal->section;
8699   loc->gdbarch = loc_gdbarch;
8700   loc->line_number = sal->line;
8701   loc->symtab = sal->symtab;
8702   loc->symbol = sal->symbol;
8703
8704   set_breakpoint_location_function (loc,
8705                                     sal->explicit_pc || sal->explicit_line);
8706
8707   /* While by definition, permanent breakpoints are already present in the
8708      code, we don't mark the location as inserted.  Normally one would expect
8709      that GDB could rely on that breakpoint instruction to stop the program,
8710      thus removing the need to insert its own breakpoint, except that executing
8711      the breakpoint instruction can kill the target instead of reporting a
8712      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8713      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8714      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8715      breakpoint be inserted normally results in QEMU knowing about the GDB
8716      breakpoint, and thus trap before the breakpoint instruction is executed.
8717      (If GDB later needs to continue execution past the permanent breakpoint,
8718      it manually increments the PC, thus avoiding executing the breakpoint
8719      instruction.)  */
8720   if (bp_loc_is_permanent (loc))
8721     loc->permanent = 1;
8722
8723   return loc;
8724 }
8725 \f
8726
8727 /* See breakpoint.h.  */
8728
8729 int
8730 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
8731 {
8732   int len;
8733   CORE_ADDR addr;
8734   const gdb_byte *bpoint;
8735   gdb_byte *target_mem;
8736
8737   addr = address;
8738   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
8739
8740   /* Software breakpoints unsupported?  */
8741   if (bpoint == NULL)
8742     return 0;
8743
8744   target_mem = (gdb_byte *) alloca (len);
8745
8746   /* Enable the automatic memory restoration from breakpoints while
8747      we read the memory.  Otherwise we could say about our temporary
8748      breakpoints they are permanent.  */
8749   scoped_restore restore_memory
8750     = make_scoped_restore_show_memory_breakpoints (0);
8751
8752   if (target_read_memory (address, target_mem, len) == 0
8753       && memcmp (target_mem, bpoint, len) == 0)
8754     return 1;
8755
8756   return 0;
8757 }
8758
8759 /* Return 1 if LOC is pointing to a permanent breakpoint,
8760    return 0 otherwise.  */
8761
8762 static int
8763 bp_loc_is_permanent (struct bp_location *loc)
8764 {
8765   gdb_assert (loc != NULL);
8766
8767   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
8768      attempt to read from the addresses the locations of these breakpoint types
8769      point to.  program_breakpoint_here_p, below, will attempt to read
8770      memory.  */
8771   if (!breakpoint_address_is_meaningful (loc->owner))
8772     return 0;
8773
8774   scoped_restore_current_pspace_and_thread restore_pspace_thread;
8775   switch_to_program_space_and_thread (loc->pspace);
8776   return program_breakpoint_here_p (loc->gdbarch, loc->address);
8777 }
8778
8779 /* Build a command list for the dprintf corresponding to the current
8780    settings of the dprintf style options.  */
8781
8782 static void
8783 update_dprintf_command_list (struct breakpoint *b)
8784 {
8785   char *dprintf_args = b->extra_string;
8786   char *printf_line = NULL;
8787
8788   if (!dprintf_args)
8789     return;
8790
8791   dprintf_args = skip_spaces (dprintf_args);
8792
8793   /* Allow a comma, as it may have terminated a location, but don't
8794      insist on it.  */
8795   if (*dprintf_args == ',')
8796     ++dprintf_args;
8797   dprintf_args = skip_spaces (dprintf_args);
8798
8799   if (*dprintf_args != '"')
8800     error (_("Bad format string, missing '\"'."));
8801
8802   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8803     printf_line = xstrprintf ("printf %s", dprintf_args);
8804   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8805     {
8806       if (!dprintf_function)
8807         error (_("No function supplied for dprintf call"));
8808
8809       if (dprintf_channel && strlen (dprintf_channel) > 0)
8810         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8811                                   dprintf_function,
8812                                   dprintf_channel,
8813                                   dprintf_args);
8814       else
8815         printf_line = xstrprintf ("call (void) %s (%s)",
8816                                   dprintf_function,
8817                                   dprintf_args);
8818     }
8819   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8820     {
8821       if (target_can_run_breakpoint_commands ())
8822         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8823       else
8824         {
8825           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8826           printf_line = xstrprintf ("printf %s", dprintf_args);
8827         }
8828     }
8829   else
8830     internal_error (__FILE__, __LINE__,
8831                     _("Invalid dprintf style."));
8832
8833   gdb_assert (printf_line != NULL);
8834   /* Manufacture a printf sequence.  */
8835   {
8836     struct command_line *printf_cmd_line = XNEW (struct command_line);
8837
8838     printf_cmd_line->control_type = simple_control;
8839     printf_cmd_line->body_count = 0;
8840     printf_cmd_line->body_list = NULL;
8841     printf_cmd_line->next = NULL;
8842     printf_cmd_line->line = printf_line;
8843
8844     breakpoint_set_commands (b, command_line_up (printf_cmd_line));
8845   }
8846 }
8847
8848 /* Update all dprintf commands, making their command lists reflect
8849    current style settings.  */
8850
8851 static void
8852 update_dprintf_commands (const char *args, int from_tty,
8853                          struct cmd_list_element *c)
8854 {
8855   struct breakpoint *b;
8856
8857   ALL_BREAKPOINTS (b)
8858     {
8859       if (b->type == bp_dprintf)
8860         update_dprintf_command_list (b);
8861     }
8862 }
8863
8864 /* Create a breakpoint with SAL as location.  Use LOCATION
8865    as a description of the location, and COND_STRING
8866    as condition expression.  If LOCATION is NULL then create an
8867    "address location" from the address in the SAL.  */
8868
8869 static void
8870 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8871                      gdb::array_view<const symtab_and_line> sals,
8872                      event_location_up &&location,
8873                      gdb::unique_xmalloc_ptr<char> filter,
8874                      gdb::unique_xmalloc_ptr<char> cond_string,
8875                      gdb::unique_xmalloc_ptr<char> extra_string,
8876                      enum bptype type, enum bpdisp disposition,
8877                      int thread, int task, int ignore_count,
8878                      const struct breakpoint_ops *ops, int from_tty,
8879                      int enabled, int internal, unsigned flags,
8880                      int display_canonical)
8881 {
8882   int i;
8883
8884   if (type == bp_hardware_breakpoint)
8885     {
8886       int target_resources_ok;
8887
8888       i = hw_breakpoint_used_count ();
8889       target_resources_ok =
8890         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8891                                             i + 1, 0);
8892       if (target_resources_ok == 0)
8893         error (_("No hardware breakpoint support in the target."));
8894       else if (target_resources_ok < 0)
8895         error (_("Hardware breakpoints used exceeds limit."));
8896     }
8897
8898   gdb_assert (!sals.empty ());
8899
8900   for (const auto &sal : sals)
8901     {
8902       struct bp_location *loc;
8903
8904       if (from_tty)
8905         {
8906           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8907           if (!loc_gdbarch)
8908             loc_gdbarch = gdbarch;
8909
8910           describe_other_breakpoints (loc_gdbarch,
8911                                       sal.pspace, sal.pc, sal.section, thread);
8912         }
8913
8914       if (&sal == &sals[0])
8915         {
8916           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8917           b->thread = thread;
8918           b->task = task;
8919
8920           b->cond_string = cond_string.release ();
8921           b->extra_string = extra_string.release ();
8922           b->ignore_count = ignore_count;
8923           b->enable_state = enabled ? bp_enabled : bp_disabled;
8924           b->disposition = disposition;
8925
8926           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8927             b->loc->inserted = 1;
8928
8929           if (type == bp_static_tracepoint)
8930             {
8931               struct tracepoint *t = (struct tracepoint *) b;
8932               struct static_tracepoint_marker marker;
8933
8934               if (strace_marker_p (b))
8935                 {
8936                   /* We already know the marker exists, otherwise, we
8937                      wouldn't see a sal for it.  */
8938                   const char *p
8939                     = &event_location_to_string (b->location.get ())[3];
8940                   const char *endp;
8941                   char *marker_str;
8942
8943                   p = skip_spaces (p);
8944
8945                   endp = skip_to_space (p);
8946
8947                   marker_str = savestring (p, endp - p);
8948                   t->static_trace_marker_id = marker_str;
8949
8950                   printf_filtered (_("Probed static tracepoint "
8951                                      "marker \"%s\"\n"),
8952                                    t->static_trace_marker_id);
8953                 }
8954               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8955                 {
8956                   t->static_trace_marker_id = xstrdup (marker.str_id);
8957                   release_static_tracepoint_marker (&marker);
8958
8959                   printf_filtered (_("Probed static tracepoint "
8960                                      "marker \"%s\"\n"),
8961                                    t->static_trace_marker_id);
8962                 }
8963               else
8964                 warning (_("Couldn't determine the static "
8965                            "tracepoint marker to probe"));
8966             }
8967
8968           loc = b->loc;
8969         }
8970       else
8971         {
8972           loc = add_location_to_breakpoint (b, &sal);
8973           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8974             loc->inserted = 1;
8975         }
8976
8977       if (b->cond_string)
8978         {
8979           const char *arg = b->cond_string;
8980
8981           loc->cond = parse_exp_1 (&arg, loc->address,
8982                                    block_for_pc (loc->address), 0);
8983           if (*arg)
8984               error (_("Garbage '%s' follows condition"), arg);
8985         }
8986
8987       /* Dynamic printf requires and uses additional arguments on the
8988          command line, otherwise it's an error.  */
8989       if (type == bp_dprintf)
8990         {
8991           if (b->extra_string)
8992             update_dprintf_command_list (b);
8993           else
8994             error (_("Format string required"));
8995         }
8996       else if (b->extra_string)
8997         error (_("Garbage '%s' at end of command"), b->extra_string);
8998     }
8999
9000   b->display_canonical = display_canonical;
9001   if (location != NULL)
9002     b->location = std::move (location);
9003   else
9004     b->location = new_address_location (b->loc->address, NULL, 0);
9005   b->filter = filter.release ();
9006 }
9007
9008 static void
9009 create_breakpoint_sal (struct gdbarch *gdbarch,
9010                        gdb::array_view<const symtab_and_line> sals,
9011                        event_location_up &&location,
9012                        gdb::unique_xmalloc_ptr<char> filter,
9013                        gdb::unique_xmalloc_ptr<char> cond_string,
9014                        gdb::unique_xmalloc_ptr<char> extra_string,
9015                        enum bptype type, enum bpdisp disposition,
9016                        int thread, int task, int ignore_count,
9017                        const struct breakpoint_ops *ops, int from_tty,
9018                        int enabled, int internal, unsigned flags,
9019                        int display_canonical)
9020 {
9021   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (type);
9022
9023   init_breakpoint_sal (b.get (), gdbarch,
9024                        sals, std::move (location),
9025                        std::move (filter),
9026                        std::move (cond_string),
9027                        std::move (extra_string),
9028                        type, disposition,
9029                        thread, task, ignore_count,
9030                        ops, from_tty,
9031                        enabled, internal, flags,
9032                        display_canonical);
9033
9034   install_breakpoint (internal, std::move (b), 0);
9035 }
9036
9037 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9038    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9039    value.  COND_STRING, if not NULL, specified the condition to be
9040    used for all breakpoints.  Essentially the only case where
9041    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9042    function.  In that case, it's still not possible to specify
9043    separate conditions for different overloaded functions, so
9044    we take just a single condition string.
9045    
9046    NOTE: If the function succeeds, the caller is expected to cleanup
9047    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9048    array contents).  If the function fails (error() is called), the
9049    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9050    COND and SALS arrays and each of those arrays contents.  */
9051
9052 static void
9053 create_breakpoints_sal (struct gdbarch *gdbarch,
9054                         struct linespec_result *canonical,
9055                         gdb::unique_xmalloc_ptr<char> cond_string,
9056                         gdb::unique_xmalloc_ptr<char> extra_string,
9057                         enum bptype type, enum bpdisp disposition,
9058                         int thread, int task, int ignore_count,
9059                         const struct breakpoint_ops *ops, int from_tty,
9060                         int enabled, int internal, unsigned flags)
9061 {
9062   if (canonical->pre_expanded)
9063     gdb_assert (canonical->lsals.size () == 1);
9064
9065   for (const auto &lsal : canonical->lsals)
9066     {
9067       /* Note that 'location' can be NULL in the case of a plain
9068          'break', without arguments.  */
9069       event_location_up location
9070         = (canonical->location != NULL
9071            ? copy_event_location (canonical->location.get ()) : NULL);
9072       gdb::unique_xmalloc_ptr<char> filter_string
9073         (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
9074
9075       create_breakpoint_sal (gdbarch, lsal.sals,
9076                              std::move (location),
9077                              std::move (filter_string),
9078                              std::move (cond_string),
9079                              std::move (extra_string),
9080                              type, disposition,
9081                              thread, task, ignore_count, ops,
9082                              from_tty, enabled, internal, flags,
9083                              canonical->special_display);
9084     }
9085 }
9086
9087 /* Parse LOCATION which is assumed to be a SAL specification possibly
9088    followed by conditionals.  On return, SALS contains an array of SAL
9089    addresses found.  LOCATION points to the end of the SAL (for
9090    linespec locations).
9091
9092    The array and the line spec strings are allocated on the heap, it is
9093    the caller's responsibility to free them.  */
9094
9095 static void
9096 parse_breakpoint_sals (const struct event_location *location,
9097                        struct linespec_result *canonical)
9098 {
9099   struct symtab_and_line cursal;
9100
9101   if (event_location_type (location) == LINESPEC_LOCATION)
9102     {
9103       const char *address = get_linespec_location (location);
9104
9105       if (address == NULL)
9106         {
9107           /* The last displayed codepoint, if it's valid, is our default
9108              breakpoint address.  */
9109           if (last_displayed_sal_is_valid ())
9110             {
9111               /* Set sal's pspace, pc, symtab, and line to the values
9112                  corresponding to the last call to print_frame_info.
9113                  Be sure to reinitialize LINE with NOTCURRENT == 0
9114                  as the breakpoint line number is inappropriate otherwise.
9115                  find_pc_line would adjust PC, re-set it back.  */
9116               symtab_and_line sal = get_last_displayed_sal ();
9117               CORE_ADDR pc = sal.pc;
9118
9119               sal = find_pc_line (pc, 0);
9120
9121               /* "break" without arguments is equivalent to "break *PC"
9122                  where PC is the last displayed codepoint's address.  So
9123                  make sure to set sal.explicit_pc to prevent GDB from
9124                  trying to expand the list of sals to include all other
9125                  instances with the same symtab and line.  */
9126               sal.pc = pc;
9127               sal.explicit_pc = 1;
9128
9129               struct linespec_sals lsal;
9130               lsal.sals = {sal};
9131               lsal.canonical = NULL;
9132
9133               canonical->lsals.push_back (std::move (lsal));
9134               return;
9135             }
9136           else
9137             error (_("No default breakpoint address now."));
9138         }
9139     }
9140
9141   /* Force almost all breakpoints to be in terms of the
9142      current_source_symtab (which is decode_line_1's default).
9143      This should produce the results we want almost all of the
9144      time while leaving default_breakpoint_* alone.
9145
9146      ObjC: However, don't match an Objective-C method name which
9147      may have a '+' or '-' succeeded by a '['.  */
9148   cursal = get_current_source_symtab_and_line ();
9149   if (last_displayed_sal_is_valid ())
9150     {
9151       const char *address = NULL;
9152
9153       if (event_location_type (location) == LINESPEC_LOCATION)
9154         address = get_linespec_location (location);
9155
9156       if (!cursal.symtab
9157           || (address != NULL
9158               && strchr ("+-", address[0]) != NULL
9159               && address[1] != '['))
9160         {
9161           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9162                             get_last_displayed_symtab (),
9163                             get_last_displayed_line (),
9164                             canonical, NULL, NULL);
9165           return;
9166         }
9167     }
9168
9169   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9170                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9171 }
9172
9173
9174 /* Convert each SAL into a real PC.  Verify that the PC can be
9175    inserted as a breakpoint.  If it can't throw an error.  */
9176
9177 static void
9178 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
9179 {    
9180   for (auto &sal : sals)
9181     resolve_sal_pc (&sal);
9182 }
9183
9184 /* Fast tracepoints may have restrictions on valid locations.  For
9185    instance, a fast tracepoint using a jump instead of a trap will
9186    likely have to overwrite more bytes than a trap would, and so can
9187    only be placed where the instruction is longer than the jump, or a
9188    multi-instruction sequence does not have a jump into the middle of
9189    it, etc.  */
9190
9191 static void
9192 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9193                             gdb::array_view<const symtab_and_line> sals)
9194 {
9195   int rslt;
9196   char *msg;
9197   struct cleanup *old_chain;
9198
9199   for (const auto &sal : sals)
9200     {
9201       struct gdbarch *sarch;
9202
9203       sarch = get_sal_arch (sal);
9204       /* We fall back to GDBARCH if there is no architecture
9205          associated with SAL.  */
9206       if (sarch == NULL)
9207         sarch = gdbarch;
9208       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg);
9209       old_chain = make_cleanup (xfree, msg);
9210
9211       if (!rslt)
9212         error (_("May not have a fast tracepoint at %s%s"),
9213                paddress (sarch, sal.pc), (msg ? msg : ""));
9214
9215       do_cleanups (old_chain);
9216     }
9217 }
9218
9219 /* Given TOK, a string specification of condition and thread, as
9220    accepted by the 'break' command, extract the condition
9221    string and thread number and set *COND_STRING and *THREAD.
9222    PC identifies the context at which the condition should be parsed.
9223    If no condition is found, *COND_STRING is set to NULL.
9224    If no thread is found, *THREAD is set to -1.  */
9225
9226 static void
9227 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9228                            char **cond_string, int *thread, int *task,
9229                            char **rest)
9230 {
9231   *cond_string = NULL;
9232   *thread = -1;
9233   *task = 0;
9234   *rest = NULL;
9235
9236   while (tok && *tok)
9237     {
9238       const char *end_tok;
9239       int toklen;
9240       const char *cond_start = NULL;
9241       const char *cond_end = NULL;
9242
9243       tok = skip_spaces (tok);
9244
9245       if ((*tok == '"' || *tok == ',') && rest)
9246         {
9247           *rest = savestring (tok, strlen (tok));
9248           return;
9249         }
9250
9251       end_tok = skip_to_space (tok);
9252
9253       toklen = end_tok - tok;
9254
9255       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9256         {
9257           tok = cond_start = end_tok + 1;
9258           parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9259           cond_end = tok;
9260           *cond_string = savestring (cond_start, cond_end - cond_start);
9261         }
9262       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9263         {
9264           const char *tmptok;
9265           struct thread_info *thr;
9266
9267           tok = end_tok + 1;
9268           thr = parse_thread_id (tok, &tmptok);
9269           if (tok == tmptok)
9270             error (_("Junk after thread keyword."));
9271           *thread = thr->global_num;
9272           tok = tmptok;
9273         }
9274       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9275         {
9276           char *tmptok;
9277
9278           tok = end_tok + 1;
9279           *task = strtol (tok, &tmptok, 0);
9280           if (tok == tmptok)
9281             error (_("Junk after task keyword."));
9282           if (!valid_task_id (*task))
9283             error (_("Unknown task %d."), *task);
9284           tok = tmptok;
9285         }
9286       else if (rest)
9287         {
9288           *rest = savestring (tok, strlen (tok));
9289           return;
9290         }
9291       else
9292         error (_("Junk at end of arguments."));
9293     }
9294 }
9295
9296 /* Decode a static tracepoint marker spec.  */
9297
9298 static std::vector<symtab_and_line>
9299 decode_static_tracepoint_spec (const char **arg_p)
9300 {
9301   VEC(static_tracepoint_marker_p) *markers = NULL;
9302   const char *p = &(*arg_p)[3];
9303   const char *endp;
9304   int i;
9305
9306   p = skip_spaces (p);
9307
9308   endp = skip_to_space (p);
9309
9310   std::string marker_str (p, endp - p);
9311
9312   markers = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
9313   if (VEC_empty(static_tracepoint_marker_p, markers))
9314     error (_("No known static tracepoint marker named %s"),
9315            marker_str.c_str ());
9316
9317   std::vector<symtab_and_line> sals;
9318   sals.reserve (VEC_length(static_tracepoint_marker_p, markers));
9319
9320   for (i = 0; i < VEC_length(static_tracepoint_marker_p, markers); i++)
9321     {
9322       struct static_tracepoint_marker *marker;
9323
9324       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9325
9326       symtab_and_line sal = find_pc_line (marker->address, 0);
9327       sal.pc = marker->address;
9328       sals.push_back (sal);
9329
9330       release_static_tracepoint_marker (marker);
9331     }
9332
9333   *arg_p = endp;
9334   return sals;
9335 }
9336
9337 /* See breakpoint.h.  */
9338
9339 int
9340 create_breakpoint (struct gdbarch *gdbarch,
9341                    const struct event_location *location,
9342                    const char *cond_string,
9343                    int thread, const char *extra_string,
9344                    int parse_extra,
9345                    int tempflag, enum bptype type_wanted,
9346                    int ignore_count,
9347                    enum auto_boolean pending_break_support,
9348                    const struct breakpoint_ops *ops,
9349                    int from_tty, int enabled, int internal,
9350                    unsigned flags)
9351 {
9352   struct linespec_result canonical;
9353   struct cleanup *bkpt_chain = NULL;
9354   int pending = 0;
9355   int task = 0;
9356   int prev_bkpt_count = breakpoint_count;
9357
9358   gdb_assert (ops != NULL);
9359
9360   /* If extra_string isn't useful, set it to NULL.  */
9361   if (extra_string != NULL && *extra_string == '\0')
9362     extra_string = NULL;
9363
9364   TRY
9365     {
9366       ops->create_sals_from_location (location, &canonical, type_wanted);
9367     }
9368   CATCH (e, RETURN_MASK_ERROR)
9369     {
9370       /* If caller is interested in rc value from parse, set
9371          value.  */
9372       if (e.error == NOT_FOUND_ERROR)
9373         {
9374           /* If pending breakpoint support is turned off, throw
9375              error.  */
9376
9377           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9378             throw_exception (e);
9379
9380           exception_print (gdb_stderr, e);
9381
9382           /* If pending breakpoint support is auto query and the user
9383              selects no, then simply return the error code.  */
9384           if (pending_break_support == AUTO_BOOLEAN_AUTO
9385               && !nquery (_("Make %s pending on future shared library load? "),
9386                           bptype_string (type_wanted)))
9387             return 0;
9388
9389           /* At this point, either the user was queried about setting
9390              a pending breakpoint and selected yes, or pending
9391              breakpoint behavior is on and thus a pending breakpoint
9392              is defaulted on behalf of the user.  */
9393           pending = 1;
9394         }
9395       else
9396         throw_exception (e);
9397     }
9398   END_CATCH
9399
9400   if (!pending && canonical.lsals.empty ())
9401     return 0;
9402
9403   /* ----------------------------- SNIP -----------------------------
9404      Anything added to the cleanup chain beyond this point is assumed
9405      to be part of a breakpoint.  If the breakpoint create succeeds
9406      then the memory is not reclaimed.  */
9407   bkpt_chain = make_cleanup (null_cleanup, 0);
9408
9409   /* Resolve all line numbers to PC's and verify that the addresses
9410      are ok for the target.  */
9411   if (!pending)
9412     {
9413       for (auto &lsal : canonical.lsals)
9414         breakpoint_sals_to_pc (lsal.sals);
9415     }
9416
9417   /* Fast tracepoints may have additional restrictions on location.  */
9418   if (!pending && type_wanted == bp_fast_tracepoint)
9419     {
9420       for (const auto &lsal : canonical.lsals)
9421         check_fast_tracepoint_sals (gdbarch, lsal.sals);
9422     }
9423
9424   /* Verify that condition can be parsed, before setting any
9425      breakpoints.  Allocate a separate condition expression for each
9426      breakpoint.  */
9427   if (!pending)
9428     {
9429       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9430       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9431
9432       if (parse_extra)
9433         {
9434           char *rest;
9435           char *cond;
9436
9437           const linespec_sals &lsal = canonical.lsals[0];
9438
9439           /* Here we only parse 'arg' to separate condition
9440              from thread number, so parsing in context of first
9441              sal is OK.  When setting the breakpoint we'll
9442              re-parse it in context of each sal.  */
9443
9444           find_condition_and_thread (extra_string, lsal.sals[0].pc,
9445                                      &cond, &thread, &task, &rest);
9446           cond_string_copy.reset (cond);
9447           extra_string_copy.reset (rest);
9448         }
9449       else
9450         {
9451           if (type_wanted != bp_dprintf
9452               && extra_string != NULL && *extra_string != '\0')
9453                 error (_("Garbage '%s' at end of location"), extra_string);
9454
9455           /* Create a private copy of condition string.  */
9456           if (cond_string)
9457             cond_string_copy.reset (xstrdup (cond_string));
9458           /* Create a private copy of any extra string.  */
9459           if (extra_string)
9460             extra_string_copy.reset (xstrdup (extra_string));
9461         }
9462
9463       ops->create_breakpoints_sal (gdbarch, &canonical,
9464                                    std::move (cond_string_copy),
9465                                    std::move (extra_string_copy),
9466                                    type_wanted,
9467                                    tempflag ? disp_del : disp_donttouch,
9468                                    thread, task, ignore_count, ops,
9469                                    from_tty, enabled, internal, flags);
9470     }
9471   else
9472     {
9473       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (type_wanted);
9474
9475       init_raw_breakpoint_without_location (b.get (), gdbarch, type_wanted, ops);
9476       b->location = copy_event_location (location);
9477
9478       if (parse_extra)
9479         b->cond_string = NULL;
9480       else
9481         {
9482           /* Create a private copy of condition string.  */
9483           b->cond_string = cond_string != NULL ? xstrdup (cond_string) : NULL;
9484           b->thread = thread;
9485         }
9486
9487       /* Create a private copy of any extra string.  */
9488       b->extra_string = extra_string != NULL ? xstrdup (extra_string) : NULL;
9489       b->ignore_count = ignore_count;
9490       b->disposition = tempflag ? disp_del : disp_donttouch;
9491       b->condition_not_parsed = 1;
9492       b->enable_state = enabled ? bp_enabled : bp_disabled;
9493       if ((type_wanted != bp_breakpoint
9494            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9495         b->pspace = current_program_space;
9496
9497       install_breakpoint (internal, std::move (b), 0);
9498     }
9499   
9500   if (canonical.lsals.size () > 1)
9501     {
9502       warning (_("Multiple breakpoints were set.\nUse the "
9503                  "\"delete\" command to delete unwanted breakpoints."));
9504       prev_breakpoint_count = prev_bkpt_count;
9505     }
9506
9507   /* That's it.  Discard the cleanups for data inserted into the
9508      breakpoint.  */
9509   discard_cleanups (bkpt_chain);
9510
9511   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9512   update_global_location_list (UGLL_MAY_INSERT);
9513
9514   return 1;
9515 }
9516
9517 /* Set a breakpoint.
9518    ARG is a string describing breakpoint address,
9519    condition, and thread.
9520    FLAG specifies if a breakpoint is hardware on,
9521    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9522    and BP_TEMPFLAG.  */
9523
9524 static void
9525 break_command_1 (const char *arg, int flag, int from_tty)
9526 {
9527   int tempflag = flag & BP_TEMPFLAG;
9528   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9529                              ? bp_hardware_breakpoint
9530                              : bp_breakpoint);
9531   struct breakpoint_ops *ops;
9532
9533   event_location_up location = string_to_event_location (&arg, current_language);
9534
9535   /* Matching breakpoints on probes.  */
9536   if (location != NULL
9537       && event_location_type (location.get ()) == PROBE_LOCATION)
9538     ops = &bkpt_probe_breakpoint_ops;
9539   else
9540     ops = &bkpt_breakpoint_ops;
9541
9542   create_breakpoint (get_current_arch (),
9543                      location.get (),
9544                      NULL, 0, arg, 1 /* parse arg */,
9545                      tempflag, type_wanted,
9546                      0 /* Ignore count */,
9547                      pending_break_support,
9548                      ops,
9549                      from_tty,
9550                      1 /* enabled */,
9551                      0 /* internal */,
9552                      0);
9553 }
9554
9555 /* Helper function for break_command_1 and disassemble_command.  */
9556
9557 void
9558 resolve_sal_pc (struct symtab_and_line *sal)
9559 {
9560   CORE_ADDR pc;
9561
9562   if (sal->pc == 0 && sal->symtab != NULL)
9563     {
9564       if (!find_line_pc (sal->symtab, sal->line, &pc))
9565         error (_("No line %d in file \"%s\"."),
9566                sal->line, symtab_to_filename_for_display (sal->symtab));
9567       sal->pc = pc;
9568
9569       /* If this SAL corresponds to a breakpoint inserted using a line
9570          number, then skip the function prologue if necessary.  */
9571       if (sal->explicit_line)
9572         skip_prologue_sal (sal);
9573     }
9574
9575   if (sal->section == 0 && sal->symtab != NULL)
9576     {
9577       const struct blockvector *bv;
9578       const struct block *b;
9579       struct symbol *sym;
9580
9581       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9582                                     SYMTAB_COMPUNIT (sal->symtab));
9583       if (bv != NULL)
9584         {
9585           sym = block_linkage_function (b);
9586           if (sym != NULL)
9587             {
9588               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9589               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9590                                                  sym);
9591             }
9592           else
9593             {
9594               /* It really is worthwhile to have the section, so we'll
9595                  just have to look harder. This case can be executed
9596                  if we have line numbers but no functions (as can
9597                  happen in assembly source).  */
9598
9599               scoped_restore_current_pspace_and_thread restore_pspace_thread;
9600               switch_to_program_space_and_thread (sal->pspace);
9601
9602               bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9603               if (msym.minsym)
9604                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9605             }
9606         }
9607     }
9608 }
9609
9610 void
9611 break_command (const char *arg, int from_tty)
9612 {
9613   break_command_1 (arg, 0, from_tty);
9614 }
9615
9616 void
9617 tbreak_command (const char *arg, int from_tty)
9618 {
9619   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9620 }
9621
9622 static void
9623 hbreak_command (const char *arg, int from_tty)
9624 {
9625   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9626 }
9627
9628 static void
9629 thbreak_command (const char *arg, int from_tty)
9630 {
9631   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9632 }
9633
9634 static void
9635 stop_command (const char *arg, int from_tty)
9636 {
9637   printf_filtered (_("Specify the type of breakpoint to set.\n\
9638 Usage: stop in <function | address>\n\
9639        stop at <line>\n"));
9640 }
9641
9642 static void
9643 stopin_command (const char *arg, int from_tty)
9644 {
9645   int badInput = 0;
9646
9647   if (arg == (char *) NULL)
9648     badInput = 1;
9649   else if (*arg != '*')
9650     {
9651       const char *argptr = arg;
9652       int hasColon = 0;
9653
9654       /* Look for a ':'.  If this is a line number specification, then
9655          say it is bad, otherwise, it should be an address or
9656          function/method name.  */
9657       while (*argptr && !hasColon)
9658         {
9659           hasColon = (*argptr == ':');
9660           argptr++;
9661         }
9662
9663       if (hasColon)
9664         badInput = (*argptr != ':');    /* Not a class::method */
9665       else
9666         badInput = isdigit (*arg);      /* a simple line number */
9667     }
9668
9669   if (badInput)
9670     printf_filtered (_("Usage: stop in <function | address>\n"));
9671   else
9672     break_command_1 (arg, 0, from_tty);
9673 }
9674
9675 static void
9676 stopat_command (const char *arg, int from_tty)
9677 {
9678   int badInput = 0;
9679
9680   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9681     badInput = 1;
9682   else
9683     {
9684       const char *argptr = arg;
9685       int hasColon = 0;
9686
9687       /* Look for a ':'.  If there is a '::' then get out, otherwise
9688          it is probably a line number.  */
9689       while (*argptr && !hasColon)
9690         {
9691           hasColon = (*argptr == ':');
9692           argptr++;
9693         }
9694
9695       if (hasColon)
9696         badInput = (*argptr == ':');    /* we have class::method */
9697       else
9698         badInput = !isdigit (*arg);     /* not a line number */
9699     }
9700
9701   if (badInput)
9702     printf_filtered (_("Usage: stop at <line>\n"));
9703   else
9704     break_command_1 (arg, 0, from_tty);
9705 }
9706
9707 /* The dynamic printf command is mostly like a regular breakpoint, but
9708    with a prewired command list consisting of a single output command,
9709    built from extra arguments supplied on the dprintf command
9710    line.  */
9711
9712 static void
9713 dprintf_command (const char *arg, int from_tty)
9714 {
9715   event_location_up location = string_to_event_location (&arg, current_language);
9716
9717   /* If non-NULL, ARG should have been advanced past the location;
9718      the next character must be ','.  */
9719   if (arg != NULL)
9720     {
9721       if (arg[0] != ',' || arg[1] == '\0')
9722         error (_("Format string required"));
9723       else
9724         {
9725           /* Skip the comma.  */
9726           ++arg;
9727         }
9728     }
9729
9730   create_breakpoint (get_current_arch (),
9731                      location.get (),
9732                      NULL, 0, arg, 1 /* parse arg */,
9733                      0, bp_dprintf,
9734                      0 /* Ignore count */,
9735                      pending_break_support,
9736                      &dprintf_breakpoint_ops,
9737                      from_tty,
9738                      1 /* enabled */,
9739                      0 /* internal */,
9740                      0);
9741 }
9742
9743 static void
9744 agent_printf_command (const char *arg, int from_tty)
9745 {
9746   error (_("May only run agent-printf on the target"));
9747 }
9748
9749 /* Implement the "breakpoint_hit" breakpoint_ops method for
9750    ranged breakpoints.  */
9751
9752 static int
9753 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9754                                   const address_space *aspace,
9755                                   CORE_ADDR bp_addr,
9756                                   const struct target_waitstatus *ws)
9757 {
9758   if (ws->kind != TARGET_WAITKIND_STOPPED
9759       || ws->value.sig != GDB_SIGNAL_TRAP)
9760     return 0;
9761
9762   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9763                                          bl->length, aspace, bp_addr);
9764 }
9765
9766 /* Implement the "resources_needed" breakpoint_ops method for
9767    ranged breakpoints.  */
9768
9769 static int
9770 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9771 {
9772   return target_ranged_break_num_registers ();
9773 }
9774
9775 /* Implement the "print_it" breakpoint_ops method for
9776    ranged breakpoints.  */
9777
9778 static enum print_stop_action
9779 print_it_ranged_breakpoint (bpstat bs)
9780 {
9781   struct breakpoint *b = bs->breakpoint_at;
9782   struct bp_location *bl = b->loc;
9783   struct ui_out *uiout = current_uiout;
9784
9785   gdb_assert (b->type == bp_hardware_breakpoint);
9786
9787   /* Ranged breakpoints have only one location.  */
9788   gdb_assert (bl && bl->next == NULL);
9789
9790   annotate_breakpoint (b->number);
9791
9792   maybe_print_thread_hit_breakpoint (uiout);
9793
9794   if (b->disposition == disp_del)
9795     uiout->text ("Temporary ranged breakpoint ");
9796   else
9797     uiout->text ("Ranged breakpoint ");
9798   if (uiout->is_mi_like_p ())
9799     {
9800       uiout->field_string ("reason",
9801                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9802       uiout->field_string ("disp", bpdisp_text (b->disposition));
9803     }
9804   uiout->field_int ("bkptno", b->number);
9805   uiout->text (", ");
9806
9807   return PRINT_SRC_AND_LOC;
9808 }
9809
9810 /* Implement the "print_one" breakpoint_ops method for
9811    ranged breakpoints.  */
9812
9813 static void
9814 print_one_ranged_breakpoint (struct breakpoint *b,
9815                              struct bp_location **last_loc)
9816 {
9817   struct bp_location *bl = b->loc;
9818   struct value_print_options opts;
9819   struct ui_out *uiout = current_uiout;
9820
9821   /* Ranged breakpoints have only one location.  */
9822   gdb_assert (bl && bl->next == NULL);
9823
9824   get_user_print_options (&opts);
9825
9826   if (opts.addressprint)
9827     /* We don't print the address range here, it will be printed later
9828        by print_one_detail_ranged_breakpoint.  */
9829     uiout->field_skip ("addr");
9830   annotate_field (5);
9831   print_breakpoint_location (b, bl);
9832   *last_loc = bl;
9833 }
9834
9835 /* Implement the "print_one_detail" breakpoint_ops method for
9836    ranged breakpoints.  */
9837
9838 static void
9839 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9840                                     struct ui_out *uiout)
9841 {
9842   CORE_ADDR address_start, address_end;
9843   struct bp_location *bl = b->loc;
9844   string_file stb;
9845
9846   gdb_assert (bl);
9847
9848   address_start = bl->address;
9849   address_end = address_start + bl->length - 1;
9850
9851   uiout->text ("\taddress range: ");
9852   stb.printf ("[%s, %s]",
9853               print_core_address (bl->gdbarch, address_start),
9854               print_core_address (bl->gdbarch, address_end));
9855   uiout->field_stream ("addr", stb);
9856   uiout->text ("\n");
9857 }
9858
9859 /* Implement the "print_mention" breakpoint_ops method for
9860    ranged breakpoints.  */
9861
9862 static void
9863 print_mention_ranged_breakpoint (struct breakpoint *b)
9864 {
9865   struct bp_location *bl = b->loc;
9866   struct ui_out *uiout = current_uiout;
9867
9868   gdb_assert (bl);
9869   gdb_assert (b->type == bp_hardware_breakpoint);
9870
9871   if (uiout->is_mi_like_p ())
9872     return;
9873
9874   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9875                    b->number, paddress (bl->gdbarch, bl->address),
9876                    paddress (bl->gdbarch, bl->address + bl->length - 1));
9877 }
9878
9879 /* Implement the "print_recreate" breakpoint_ops method for
9880    ranged breakpoints.  */
9881
9882 static void
9883 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9884 {
9885   fprintf_unfiltered (fp, "break-range %s, %s",
9886                       event_location_to_string (b->location.get ()),
9887                       event_location_to_string (b->location_range_end.get ()));
9888   print_recreate_thread (b, fp);
9889 }
9890
9891 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9892
9893 static struct breakpoint_ops ranged_breakpoint_ops;
9894
9895 /* Find the address where the end of the breakpoint range should be
9896    placed, given the SAL of the end of the range.  This is so that if
9897    the user provides a line number, the end of the range is set to the
9898    last instruction of the given line.  */
9899
9900 static CORE_ADDR
9901 find_breakpoint_range_end (struct symtab_and_line sal)
9902 {
9903   CORE_ADDR end;
9904
9905   /* If the user provided a PC value, use it.  Otherwise,
9906      find the address of the end of the given location.  */
9907   if (sal.explicit_pc)
9908     end = sal.pc;
9909   else
9910     {
9911       int ret;
9912       CORE_ADDR start;
9913
9914       ret = find_line_pc_range (sal, &start, &end);
9915       if (!ret)
9916         error (_("Could not find location of the end of the range."));
9917
9918       /* find_line_pc_range returns the start of the next line.  */
9919       end--;
9920     }
9921
9922   return end;
9923 }
9924
9925 /* Implement the "break-range" CLI command.  */
9926
9927 static void
9928 break_range_command (const char *arg, int from_tty)
9929 {
9930   const char *arg_start;
9931   struct linespec_result canonical_start, canonical_end;
9932   int bp_count, can_use_bp, length;
9933   CORE_ADDR end;
9934   struct breakpoint *b;
9935
9936   /* We don't support software ranged breakpoints.  */
9937   if (target_ranged_break_num_registers () < 0)
9938     error (_("This target does not support hardware ranged breakpoints."));
9939
9940   bp_count = hw_breakpoint_used_count ();
9941   bp_count += target_ranged_break_num_registers ();
9942   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9943                                                    bp_count, 0);
9944   if (can_use_bp < 0)
9945     error (_("Hardware breakpoints used exceeds limit."));
9946
9947   arg = skip_spaces (arg);
9948   if (arg == NULL || arg[0] == '\0')
9949     error(_("No address range specified."));
9950
9951   arg_start = arg;
9952   event_location_up start_location = string_to_event_location (&arg,
9953                                                                current_language);
9954   parse_breakpoint_sals (start_location.get (), &canonical_start);
9955
9956   if (arg[0] != ',')
9957     error (_("Too few arguments."));
9958   else if (canonical_start.lsals.empty ())
9959     error (_("Could not find location of the beginning of the range."));
9960
9961   const linespec_sals &lsal_start = canonical_start.lsals[0];
9962
9963   if (canonical_start.lsals.size () > 1
9964       || lsal_start.sals.size () != 1)
9965     error (_("Cannot create a ranged breakpoint with multiple locations."));
9966
9967   const symtab_and_line &sal_start = lsal_start.sals[0];
9968   std::string addr_string_start (arg_start, arg - arg_start);
9969
9970   arg++;        /* Skip the comma.  */
9971   arg = skip_spaces (arg);
9972
9973   /* Parse the end location.  */
9974
9975   arg_start = arg;
9976
9977   /* We call decode_line_full directly here instead of using
9978      parse_breakpoint_sals because we need to specify the start location's
9979      symtab and line as the default symtab and line for the end of the
9980      range.  This makes it possible to have ranges like "foo.c:27, +14",
9981      where +14 means 14 lines from the start location.  */
9982   event_location_up end_location = string_to_event_location (&arg,
9983                                                              current_language);
9984   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
9985                     sal_start.symtab, sal_start.line,
9986                     &canonical_end, NULL, NULL);
9987
9988   if (canonical_end.lsals.empty ())
9989     error (_("Could not find location of the end of the range."));
9990
9991   const linespec_sals &lsal_end = canonical_end.lsals[0];
9992   if (canonical_end.lsals.size () > 1
9993       || lsal_end.sals.size () != 1)
9994     error (_("Cannot create a ranged breakpoint with multiple locations."));
9995
9996   const symtab_and_line &sal_end = lsal_end.sals[0];
9997
9998   end = find_breakpoint_range_end (sal_end);
9999   if (sal_start.pc > end)
10000     error (_("Invalid address range, end precedes start."));
10001
10002   length = end - sal_start.pc + 1;
10003   if (length < 0)
10004     /* Length overflowed.  */
10005     error (_("Address range too large."));
10006   else if (length == 1)
10007     {
10008       /* This range is simple enough to be handled by
10009          the `hbreak' command.  */
10010       hbreak_command (&addr_string_start[0], 1);
10011
10012       return;
10013     }
10014
10015   /* Now set up the breakpoint.  */
10016   b = set_raw_breakpoint (get_current_arch (), sal_start,
10017                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10018   set_breakpoint_count (breakpoint_count + 1);
10019   b->number = breakpoint_count;
10020   b->disposition = disp_donttouch;
10021   b->location = std::move (start_location);
10022   b->location_range_end = std::move (end_location);
10023   b->loc->length = length;
10024
10025   mention (b);
10026   observer_notify_breakpoint_created (b);
10027   update_global_location_list (UGLL_MAY_INSERT);
10028 }
10029
10030 /*  Return non-zero if EXP is verified as constant.  Returned zero
10031     means EXP is variable.  Also the constant detection may fail for
10032     some constant expressions and in such case still falsely return
10033     zero.  */
10034
10035 static int
10036 watchpoint_exp_is_const (const struct expression *exp)
10037 {
10038   int i = exp->nelts;
10039
10040   while (i > 0)
10041     {
10042       int oplenp, argsp;
10043
10044       /* We are only interested in the descriptor of each element.  */
10045       operator_length (exp, i, &oplenp, &argsp);
10046       i -= oplenp;
10047
10048       switch (exp->elts[i].opcode)
10049         {
10050         case BINOP_ADD:
10051         case BINOP_SUB:
10052         case BINOP_MUL:
10053         case BINOP_DIV:
10054         case BINOP_REM:
10055         case BINOP_MOD:
10056         case BINOP_LSH:
10057         case BINOP_RSH:
10058         case BINOP_LOGICAL_AND:
10059         case BINOP_LOGICAL_OR:
10060         case BINOP_BITWISE_AND:
10061         case BINOP_BITWISE_IOR:
10062         case BINOP_BITWISE_XOR:
10063         case BINOP_EQUAL:
10064         case BINOP_NOTEQUAL:
10065         case BINOP_LESS:
10066         case BINOP_GTR:
10067         case BINOP_LEQ:
10068         case BINOP_GEQ:
10069         case BINOP_REPEAT:
10070         case BINOP_COMMA:
10071         case BINOP_EXP:
10072         case BINOP_MIN:
10073         case BINOP_MAX:
10074         case BINOP_INTDIV:
10075         case BINOP_CONCAT:
10076         case TERNOP_COND:
10077         case TERNOP_SLICE:
10078
10079         case OP_LONG:
10080         case OP_FLOAT:
10081         case OP_LAST:
10082         case OP_COMPLEX:
10083         case OP_STRING:
10084         case OP_ARRAY:
10085         case OP_TYPE:
10086         case OP_TYPEOF:
10087         case OP_DECLTYPE:
10088         case OP_TYPEID:
10089         case OP_NAME:
10090         case OP_OBJC_NSSTRING:
10091
10092         case UNOP_NEG:
10093         case UNOP_LOGICAL_NOT:
10094         case UNOP_COMPLEMENT:
10095         case UNOP_ADDR:
10096         case UNOP_HIGH:
10097         case UNOP_CAST:
10098
10099         case UNOP_CAST_TYPE:
10100         case UNOP_REINTERPRET_CAST:
10101         case UNOP_DYNAMIC_CAST:
10102           /* Unary, binary and ternary operators: We have to check
10103              their operands.  If they are constant, then so is the
10104              result of that operation.  For instance, if A and B are
10105              determined to be constants, then so is "A + B".
10106
10107              UNOP_IND is one exception to the rule above, because the
10108              value of *ADDR is not necessarily a constant, even when
10109              ADDR is.  */
10110           break;
10111
10112         case OP_VAR_VALUE:
10113           /* Check whether the associated symbol is a constant.
10114
10115              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10116              possible that a buggy compiler could mark a variable as
10117              constant even when it is not, and TYPE_CONST would return
10118              true in this case, while SYMBOL_CLASS wouldn't.
10119
10120              We also have to check for function symbols because they
10121              are always constant.  */
10122           {
10123             struct symbol *s = exp->elts[i + 2].symbol;
10124
10125             if (SYMBOL_CLASS (s) != LOC_BLOCK
10126                 && SYMBOL_CLASS (s) != LOC_CONST
10127                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10128               return 0;
10129             break;
10130           }
10131
10132         /* The default action is to return 0 because we are using
10133            the optimistic approach here: If we don't know something,
10134            then it is not a constant.  */
10135         default:
10136           return 0;
10137         }
10138     }
10139
10140   return 1;
10141 }
10142
10143 /* Watchpoint destructor.  */
10144
10145 watchpoint::~watchpoint ()
10146 {
10147   xfree (this->exp_string);
10148   xfree (this->exp_string_reparse);
10149   value_free (this->val);
10150 }
10151
10152 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10153
10154 static void
10155 re_set_watchpoint (struct breakpoint *b)
10156 {
10157   struct watchpoint *w = (struct watchpoint *) b;
10158
10159   /* Watchpoint can be either on expression using entirely global
10160      variables, or it can be on local variables.
10161
10162      Watchpoints of the first kind are never auto-deleted, and even
10163      persist across program restarts.  Since they can use variables
10164      from shared libraries, we need to reparse expression as libraries
10165      are loaded and unloaded.
10166
10167      Watchpoints on local variables can also change meaning as result
10168      of solib event.  For example, if a watchpoint uses both a local
10169      and a global variables in expression, it's a local watchpoint,
10170      but unloading of a shared library will make the expression
10171      invalid.  This is not a very common use case, but we still
10172      re-evaluate expression, to avoid surprises to the user.
10173
10174      Note that for local watchpoints, we re-evaluate it only if
10175      watchpoints frame id is still valid.  If it's not, it means the
10176      watchpoint is out of scope and will be deleted soon.  In fact,
10177      I'm not sure we'll ever be called in this case.
10178
10179      If a local watchpoint's frame id is still valid, then
10180      w->exp_valid_block is likewise valid, and we can safely use it.
10181
10182      Don't do anything about disabled watchpoints, since they will be
10183      reevaluated again when enabled.  */
10184   update_watchpoint (w, 1 /* reparse */);
10185 }
10186
10187 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10188
10189 static int
10190 insert_watchpoint (struct bp_location *bl)
10191 {
10192   struct watchpoint *w = (struct watchpoint *) bl->owner;
10193   int length = w->exact ? 1 : bl->length;
10194
10195   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10196                                    w->cond_exp.get ());
10197 }
10198
10199 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10200
10201 static int
10202 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10203 {
10204   struct watchpoint *w = (struct watchpoint *) bl->owner;
10205   int length = w->exact ? 1 : bl->length;
10206
10207   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10208                                    w->cond_exp.get ());
10209 }
10210
10211 static int
10212 breakpoint_hit_watchpoint (const struct bp_location *bl,
10213                            const address_space *aspace, CORE_ADDR bp_addr,
10214                            const struct target_waitstatus *ws)
10215 {
10216   struct breakpoint *b = bl->owner;
10217   struct watchpoint *w = (struct watchpoint *) b;
10218
10219   /* Continuable hardware watchpoints are treated as non-existent if the
10220      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10221      some data address).  Otherwise gdb won't stop on a break instruction
10222      in the code (not from a breakpoint) when a hardware watchpoint has
10223      been defined.  Also skip watchpoints which we know did not trigger
10224      (did not match the data address).  */
10225   if (is_hardware_watchpoint (b)
10226       && w->watchpoint_triggered == watch_triggered_no)
10227     return 0;
10228
10229   return 1;
10230 }
10231
10232 static void
10233 check_status_watchpoint (bpstat bs)
10234 {
10235   gdb_assert (is_watchpoint (bs->breakpoint_at));
10236
10237   bpstat_check_watchpoint (bs);
10238 }
10239
10240 /* Implement the "resources_needed" breakpoint_ops method for
10241    hardware watchpoints.  */
10242
10243 static int
10244 resources_needed_watchpoint (const struct bp_location *bl)
10245 {
10246   struct watchpoint *w = (struct watchpoint *) bl->owner;
10247   int length = w->exact? 1 : bl->length;
10248
10249   return target_region_ok_for_hw_watchpoint (bl->address, length);
10250 }
10251
10252 /* Implement the "works_in_software_mode" breakpoint_ops method for
10253    hardware watchpoints.  */
10254
10255 static int
10256 works_in_software_mode_watchpoint (const struct breakpoint *b)
10257 {
10258   /* Read and access watchpoints only work with hardware support.  */
10259   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10260 }
10261
10262 static enum print_stop_action
10263 print_it_watchpoint (bpstat bs)
10264 {
10265   struct breakpoint *b;
10266   enum print_stop_action result;
10267   struct watchpoint *w;
10268   struct ui_out *uiout = current_uiout;
10269
10270   gdb_assert (bs->bp_location_at != NULL);
10271
10272   b = bs->breakpoint_at;
10273   w = (struct watchpoint *) b;
10274
10275   annotate_watchpoint (b->number);
10276   maybe_print_thread_hit_breakpoint (uiout);
10277
10278   string_file stb;
10279
10280   gdb::optional<ui_out_emit_tuple> tuple_emitter;
10281   switch (b->type)
10282     {
10283     case bp_watchpoint:
10284     case bp_hardware_watchpoint:
10285       if (uiout->is_mi_like_p ())
10286         uiout->field_string
10287           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10288       mention (b);
10289       tuple_emitter.emplace (uiout, "value");
10290       uiout->text ("\nOld value = ");
10291       watchpoint_value_print (bs->old_val, &stb);
10292       uiout->field_stream ("old", stb);
10293       uiout->text ("\nNew value = ");
10294       watchpoint_value_print (w->val, &stb);
10295       uiout->field_stream ("new", stb);
10296       uiout->text ("\n");
10297       /* More than one watchpoint may have been triggered.  */
10298       result = PRINT_UNKNOWN;
10299       break;
10300
10301     case bp_read_watchpoint:
10302       if (uiout->is_mi_like_p ())
10303         uiout->field_string
10304           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10305       mention (b);
10306       tuple_emitter.emplace (uiout, "value");
10307       uiout->text ("\nValue = ");
10308       watchpoint_value_print (w->val, &stb);
10309       uiout->field_stream ("value", stb);
10310       uiout->text ("\n");
10311       result = PRINT_UNKNOWN;
10312       break;
10313
10314     case bp_access_watchpoint:
10315       if (bs->old_val != NULL)
10316         {
10317           if (uiout->is_mi_like_p ())
10318             uiout->field_string
10319               ("reason",
10320                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10321           mention (b);
10322           tuple_emitter.emplace (uiout, "value");
10323           uiout->text ("\nOld value = ");
10324           watchpoint_value_print (bs->old_val, &stb);
10325           uiout->field_stream ("old", stb);
10326           uiout->text ("\nNew value = ");
10327         }
10328       else
10329         {
10330           mention (b);
10331           if (uiout->is_mi_like_p ())
10332             uiout->field_string
10333               ("reason",
10334                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10335           tuple_emitter.emplace (uiout, "value");
10336           uiout->text ("\nValue = ");
10337         }
10338       watchpoint_value_print (w->val, &stb);
10339       uiout->field_stream ("new", stb);
10340       uiout->text ("\n");
10341       result = PRINT_UNKNOWN;
10342       break;
10343     default:
10344       result = PRINT_UNKNOWN;
10345     }
10346
10347   return result;
10348 }
10349
10350 /* Implement the "print_mention" breakpoint_ops method for hardware
10351    watchpoints.  */
10352
10353 static void
10354 print_mention_watchpoint (struct breakpoint *b)
10355 {
10356   struct watchpoint *w = (struct watchpoint *) b;
10357   struct ui_out *uiout = current_uiout;
10358   const char *tuple_name;
10359
10360   switch (b->type)
10361     {
10362     case bp_watchpoint:
10363       uiout->text ("Watchpoint ");
10364       tuple_name = "wpt";
10365       break;
10366     case bp_hardware_watchpoint:
10367       uiout->text ("Hardware watchpoint ");
10368       tuple_name = "wpt";
10369       break;
10370     case bp_read_watchpoint:
10371       uiout->text ("Hardware read watchpoint ");
10372       tuple_name = "hw-rwpt";
10373       break;
10374     case bp_access_watchpoint:
10375       uiout->text ("Hardware access (read/write) watchpoint ");
10376       tuple_name = "hw-awpt";
10377       break;
10378     default:
10379       internal_error (__FILE__, __LINE__,
10380                       _("Invalid hardware watchpoint type."));
10381     }
10382
10383   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10384   uiout->field_int ("number", b->number);
10385   uiout->text (": ");
10386   uiout->field_string ("exp", w->exp_string);
10387 }
10388
10389 /* Implement the "print_recreate" breakpoint_ops method for
10390    watchpoints.  */
10391
10392 static void
10393 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10394 {
10395   struct watchpoint *w = (struct watchpoint *) b;
10396
10397   switch (b->type)
10398     {
10399     case bp_watchpoint:
10400     case bp_hardware_watchpoint:
10401       fprintf_unfiltered (fp, "watch");
10402       break;
10403     case bp_read_watchpoint:
10404       fprintf_unfiltered (fp, "rwatch");
10405       break;
10406     case bp_access_watchpoint:
10407       fprintf_unfiltered (fp, "awatch");
10408       break;
10409     default:
10410       internal_error (__FILE__, __LINE__,
10411                       _("Invalid watchpoint type."));
10412     }
10413
10414   fprintf_unfiltered (fp, " %s", w->exp_string);
10415   print_recreate_thread (b, fp);
10416 }
10417
10418 /* Implement the "explains_signal" breakpoint_ops method for
10419    watchpoints.  */
10420
10421 static int
10422 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10423 {
10424   /* A software watchpoint cannot cause a signal other than
10425      GDB_SIGNAL_TRAP.  */
10426   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10427     return 0;
10428
10429   return 1;
10430 }
10431
10432 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10433
10434 static struct breakpoint_ops watchpoint_breakpoint_ops;
10435
10436 /* Implement the "insert" breakpoint_ops method for
10437    masked hardware watchpoints.  */
10438
10439 static int
10440 insert_masked_watchpoint (struct bp_location *bl)
10441 {
10442   struct watchpoint *w = (struct watchpoint *) bl->owner;
10443
10444   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10445                                         bl->watchpoint_type);
10446 }
10447
10448 /* Implement the "remove" breakpoint_ops method for
10449    masked hardware watchpoints.  */
10450
10451 static int
10452 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10453 {
10454   struct watchpoint *w = (struct watchpoint *) bl->owner;
10455
10456   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10457                                         bl->watchpoint_type);
10458 }
10459
10460 /* Implement the "resources_needed" breakpoint_ops method for
10461    masked hardware watchpoints.  */
10462
10463 static int
10464 resources_needed_masked_watchpoint (const struct bp_location *bl)
10465 {
10466   struct watchpoint *w = (struct watchpoint *) bl->owner;
10467
10468   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10469 }
10470
10471 /* Implement the "works_in_software_mode" breakpoint_ops method for
10472    masked hardware watchpoints.  */
10473
10474 static int
10475 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10476 {
10477   return 0;
10478 }
10479
10480 /* Implement the "print_it" breakpoint_ops method for
10481    masked hardware watchpoints.  */
10482
10483 static enum print_stop_action
10484 print_it_masked_watchpoint (bpstat bs)
10485 {
10486   struct breakpoint *b = bs->breakpoint_at;
10487   struct ui_out *uiout = current_uiout;
10488
10489   /* Masked watchpoints have only one location.  */
10490   gdb_assert (b->loc && b->loc->next == NULL);
10491
10492   annotate_watchpoint (b->number);
10493   maybe_print_thread_hit_breakpoint (uiout);
10494
10495   switch (b->type)
10496     {
10497     case bp_hardware_watchpoint:
10498       if (uiout->is_mi_like_p ())
10499         uiout->field_string
10500           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10501       break;
10502
10503     case bp_read_watchpoint:
10504       if (uiout->is_mi_like_p ())
10505         uiout->field_string
10506           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10507       break;
10508
10509     case bp_access_watchpoint:
10510       if (uiout->is_mi_like_p ())
10511         uiout->field_string
10512           ("reason",
10513            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10514       break;
10515     default:
10516       internal_error (__FILE__, __LINE__,
10517                       _("Invalid hardware watchpoint type."));
10518     }
10519
10520   mention (b);
10521   uiout->text (_("\n\
10522 Check the underlying instruction at PC for the memory\n\
10523 address and value which triggered this watchpoint.\n"));
10524   uiout->text ("\n");
10525
10526   /* More than one watchpoint may have been triggered.  */
10527   return PRINT_UNKNOWN;
10528 }
10529
10530 /* Implement the "print_one_detail" breakpoint_ops method for
10531    masked hardware watchpoints.  */
10532
10533 static void
10534 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10535                                     struct ui_out *uiout)
10536 {
10537   struct watchpoint *w = (struct watchpoint *) b;
10538
10539   /* Masked watchpoints have only one location.  */
10540   gdb_assert (b->loc && b->loc->next == NULL);
10541
10542   uiout->text ("\tmask ");
10543   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10544   uiout->text ("\n");
10545 }
10546
10547 /* Implement the "print_mention" breakpoint_ops method for
10548    masked hardware watchpoints.  */
10549
10550 static void
10551 print_mention_masked_watchpoint (struct breakpoint *b)
10552 {
10553   struct watchpoint *w = (struct watchpoint *) b;
10554   struct ui_out *uiout = current_uiout;
10555   const char *tuple_name;
10556
10557   switch (b->type)
10558     {
10559     case bp_hardware_watchpoint:
10560       uiout->text ("Masked hardware watchpoint ");
10561       tuple_name = "wpt";
10562       break;
10563     case bp_read_watchpoint:
10564       uiout->text ("Masked hardware read watchpoint ");
10565       tuple_name = "hw-rwpt";
10566       break;
10567     case bp_access_watchpoint:
10568       uiout->text ("Masked hardware access (read/write) watchpoint ");
10569       tuple_name = "hw-awpt";
10570       break;
10571     default:
10572       internal_error (__FILE__, __LINE__,
10573                       _("Invalid hardware watchpoint type."));
10574     }
10575
10576   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10577   uiout->field_int ("number", b->number);
10578   uiout->text (": ");
10579   uiout->field_string ("exp", w->exp_string);
10580 }
10581
10582 /* Implement the "print_recreate" breakpoint_ops method for
10583    masked hardware watchpoints.  */
10584
10585 static void
10586 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10587 {
10588   struct watchpoint *w = (struct watchpoint *) b;
10589   char tmp[40];
10590
10591   switch (b->type)
10592     {
10593     case bp_hardware_watchpoint:
10594       fprintf_unfiltered (fp, "watch");
10595       break;
10596     case bp_read_watchpoint:
10597       fprintf_unfiltered (fp, "rwatch");
10598       break;
10599     case bp_access_watchpoint:
10600       fprintf_unfiltered (fp, "awatch");
10601       break;
10602     default:
10603       internal_error (__FILE__, __LINE__,
10604                       _("Invalid hardware watchpoint type."));
10605     }
10606
10607   sprintf_vma (tmp, w->hw_wp_mask);
10608   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10609   print_recreate_thread (b, fp);
10610 }
10611
10612 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10613
10614 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10615
10616 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10617
10618 static int
10619 is_masked_watchpoint (const struct breakpoint *b)
10620 {
10621   return b->ops == &masked_watchpoint_breakpoint_ops;
10622 }
10623
10624 /* accessflag:  hw_write:  watch write, 
10625                 hw_read:   watch read, 
10626                 hw_access: watch access (read or write) */
10627 static void
10628 watch_command_1 (const char *arg, int accessflag, int from_tty,
10629                  int just_location, int internal)
10630 {
10631   struct breakpoint *scope_breakpoint = NULL;
10632   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10633   struct value *val, *mark, *result;
10634   int saved_bitpos = 0, saved_bitsize = 0;
10635   const char *exp_start = NULL;
10636   const char *exp_end = NULL;
10637   const char *tok, *end_tok;
10638   int toklen = -1;
10639   const char *cond_start = NULL;
10640   const char *cond_end = NULL;
10641   enum bptype bp_type;
10642   int thread = -1;
10643   int pc = 0;
10644   /* Flag to indicate whether we are going to use masks for
10645      the hardware watchpoint.  */
10646   int use_mask = 0;
10647   CORE_ADDR mask = 0;
10648
10649   /* Make sure that we actually have parameters to parse.  */
10650   if (arg != NULL && arg[0] != '\0')
10651     {
10652       const char *value_start;
10653
10654       exp_end = arg + strlen (arg);
10655
10656       /* Look for "parameter value" pairs at the end
10657          of the arguments string.  */
10658       for (tok = exp_end - 1; tok > arg; tok--)
10659         {
10660           /* Skip whitespace at the end of the argument list.  */
10661           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10662             tok--;
10663
10664           /* Find the beginning of the last token.
10665              This is the value of the parameter.  */
10666           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10667             tok--;
10668           value_start = tok + 1;
10669
10670           /* Skip whitespace.  */
10671           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10672             tok--;
10673
10674           end_tok = tok;
10675
10676           /* Find the beginning of the second to last token.
10677              This is the parameter itself.  */
10678           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10679             tok--;
10680           tok++;
10681           toklen = end_tok - tok + 1;
10682
10683           if (toklen == 6 && startswith (tok, "thread"))
10684             {
10685               struct thread_info *thr;
10686               /* At this point we've found a "thread" token, which means
10687                  the user is trying to set a watchpoint that triggers
10688                  only in a specific thread.  */
10689               const char *endp;
10690
10691               if (thread != -1)
10692                 error(_("You can specify only one thread."));
10693
10694               /* Extract the thread ID from the next token.  */
10695               thr = parse_thread_id (value_start, &endp);
10696
10697               /* Check if the user provided a valid thread ID.  */
10698               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10699                 invalid_thread_id_error (value_start);
10700
10701               thread = thr->global_num;
10702             }
10703           else if (toklen == 4 && startswith (tok, "mask"))
10704             {
10705               /* We've found a "mask" token, which means the user wants to
10706                  create a hardware watchpoint that is going to have the mask
10707                  facility.  */
10708               struct value *mask_value, *mark;
10709
10710               if (use_mask)
10711                 error(_("You can specify only one mask."));
10712
10713               use_mask = just_location = 1;
10714
10715               mark = value_mark ();
10716               mask_value = parse_to_comma_and_eval (&value_start);
10717               mask = value_as_address (mask_value);
10718               value_free_to_mark (mark);
10719             }
10720           else
10721             /* We didn't recognize what we found.  We should stop here.  */
10722             break;
10723
10724           /* Truncate the string and get rid of the "parameter value" pair before
10725              the arguments string is parsed by the parse_exp_1 function.  */
10726           exp_end = tok;
10727         }
10728     }
10729   else
10730     exp_end = arg;
10731
10732   /* Parse the rest of the arguments.  From here on out, everything
10733      is in terms of a newly allocated string instead of the original
10734      ARG.  */
10735   innermost_block = NULL;
10736   std::string expression (arg, exp_end - arg);
10737   exp_start = arg = expression.c_str ();
10738   expression_up exp = parse_exp_1 (&arg, 0, 0, 0);
10739   exp_end = arg;
10740   /* Remove trailing whitespace from the expression before saving it.
10741      This makes the eventual display of the expression string a bit
10742      prettier.  */
10743   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10744     --exp_end;
10745
10746   /* Checking if the expression is not constant.  */
10747   if (watchpoint_exp_is_const (exp.get ()))
10748     {
10749       int len;
10750
10751       len = exp_end - exp_start;
10752       while (len > 0 && isspace (exp_start[len - 1]))
10753         len--;
10754       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10755     }
10756
10757   exp_valid_block = innermost_block;
10758   mark = value_mark ();
10759   fetch_subexp_value (exp.get (), &pc, &val, &result, NULL, just_location);
10760
10761   if (val != NULL && just_location)
10762     {
10763       saved_bitpos = value_bitpos (val);
10764       saved_bitsize = value_bitsize (val);
10765     }
10766
10767   if (just_location)
10768     {
10769       int ret;
10770
10771       exp_valid_block = NULL;
10772       val = value_addr (result);
10773       release_value (val);
10774       value_free_to_mark (mark);
10775
10776       if (use_mask)
10777         {
10778           ret = target_masked_watch_num_registers (value_as_address (val),
10779                                                    mask);
10780           if (ret == -1)
10781             error (_("This target does not support masked watchpoints."));
10782           else if (ret == -2)
10783             error (_("Invalid mask or memory region."));
10784         }
10785     }
10786   else if (val != NULL)
10787     release_value (val);
10788
10789   tok = skip_spaces (arg);
10790   end_tok = skip_to_space (tok);
10791
10792   toklen = end_tok - tok;
10793   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10794     {
10795       innermost_block = NULL;
10796       tok = cond_start = end_tok + 1;
10797       parse_exp_1 (&tok, 0, 0, 0);
10798
10799       /* The watchpoint expression may not be local, but the condition
10800          may still be.  E.g.: `watch global if local > 0'.  */
10801       cond_exp_valid_block = innermost_block;
10802
10803       cond_end = tok;
10804     }
10805   if (*tok)
10806     error (_("Junk at end of command."));
10807
10808   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
10809
10810   /* Save this because create_internal_breakpoint below invalidates
10811      'wp_frame'.  */
10812   frame_id watchpoint_frame = get_frame_id (wp_frame);
10813
10814   /* If the expression is "local", then set up a "watchpoint scope"
10815      breakpoint at the point where we've left the scope of the watchpoint
10816      expression.  Create the scope breakpoint before the watchpoint, so
10817      that we will encounter it first in bpstat_stop_status.  */
10818   if (exp_valid_block != NULL && wp_frame != NULL)
10819     {
10820       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10821
10822       if (frame_id_p (caller_frame_id))
10823         {
10824           gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10825           CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10826
10827           scope_breakpoint
10828             = create_internal_breakpoint (caller_arch, caller_pc,
10829                                           bp_watchpoint_scope,
10830                                           &momentary_breakpoint_ops);
10831
10832           /* create_internal_breakpoint could invalidate WP_FRAME.  */
10833           wp_frame = NULL;
10834
10835           scope_breakpoint->enable_state = bp_enabled;
10836
10837           /* Automatically delete the breakpoint when it hits.  */
10838           scope_breakpoint->disposition = disp_del;
10839
10840           /* Only break in the proper frame (help with recursion).  */
10841           scope_breakpoint->frame_id = caller_frame_id;
10842
10843           /* Set the address at which we will stop.  */
10844           scope_breakpoint->loc->gdbarch = caller_arch;
10845           scope_breakpoint->loc->requested_address = caller_pc;
10846           scope_breakpoint->loc->address
10847             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10848                                          scope_breakpoint->loc->requested_address,
10849                                          scope_breakpoint->type);
10850         }
10851     }
10852
10853   /* Now set up the breakpoint.  We create all watchpoints as hardware
10854      watchpoints here even if hardware watchpoints are turned off, a call
10855      to update_watchpoint later in this function will cause the type to
10856      drop back to bp_watchpoint (software watchpoint) if required.  */
10857
10858   if (accessflag == hw_read)
10859     bp_type = bp_read_watchpoint;
10860   else if (accessflag == hw_access)
10861     bp_type = bp_access_watchpoint;
10862   else
10863     bp_type = bp_hardware_watchpoint;
10864
10865   std::unique_ptr<watchpoint> w (new watchpoint ());
10866
10867   if (use_mask)
10868     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10869                                           &masked_watchpoint_breakpoint_ops);
10870   else
10871     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10872                                           &watchpoint_breakpoint_ops);
10873   w->thread = thread;
10874   w->disposition = disp_donttouch;
10875   w->pspace = current_program_space;
10876   w->exp = std::move (exp);
10877   w->exp_valid_block = exp_valid_block;
10878   w->cond_exp_valid_block = cond_exp_valid_block;
10879   if (just_location)
10880     {
10881       struct type *t = value_type (val);
10882       CORE_ADDR addr = value_as_address (val);
10883
10884       w->exp_string_reparse
10885         = current_language->la_watch_location_expression (t, addr).release ();
10886
10887       w->exp_string = xstrprintf ("-location %.*s",
10888                                   (int) (exp_end - exp_start), exp_start);
10889     }
10890   else
10891     w->exp_string = savestring (exp_start, exp_end - exp_start);
10892
10893   if (use_mask)
10894     {
10895       w->hw_wp_mask = mask;
10896     }
10897   else
10898     {
10899       w->val = val;
10900       w->val_bitpos = saved_bitpos;
10901       w->val_bitsize = saved_bitsize;
10902       w->val_valid = 1;
10903     }
10904
10905   if (cond_start)
10906     w->cond_string = savestring (cond_start, cond_end - cond_start);
10907   else
10908     w->cond_string = 0;
10909
10910   if (frame_id_p (watchpoint_frame))
10911     {
10912       w->watchpoint_frame = watchpoint_frame;
10913       w->watchpoint_thread = inferior_ptid;
10914     }
10915   else
10916     {
10917       w->watchpoint_frame = null_frame_id;
10918       w->watchpoint_thread = null_ptid;
10919     }
10920
10921   if (scope_breakpoint != NULL)
10922     {
10923       /* The scope breakpoint is related to the watchpoint.  We will
10924          need to act on them together.  */
10925       w->related_breakpoint = scope_breakpoint;
10926       scope_breakpoint->related_breakpoint = w.get ();
10927     }
10928
10929   if (!just_location)
10930     value_free_to_mark (mark);
10931
10932   /* Finally update the new watchpoint.  This creates the locations
10933      that should be inserted.  */
10934   update_watchpoint (w.get (), 1);
10935
10936   install_breakpoint (internal, std::move (w), 1);
10937 }
10938
10939 /* Return count of debug registers needed to watch the given expression.
10940    If the watchpoint cannot be handled in hardware return zero.  */
10941
10942 static int
10943 can_use_hardware_watchpoint (struct value *v)
10944 {
10945   int found_memory_cnt = 0;
10946   struct value *head = v;
10947
10948   /* Did the user specifically forbid us to use hardware watchpoints? */
10949   if (!can_use_hw_watchpoints)
10950     return 0;
10951
10952   /* Make sure that the value of the expression depends only upon
10953      memory contents, and values computed from them within GDB.  If we
10954      find any register references or function calls, we can't use a
10955      hardware watchpoint.
10956
10957      The idea here is that evaluating an expression generates a series
10958      of values, one holding the value of every subexpression.  (The
10959      expression a*b+c has five subexpressions: a, b, a*b, c, and
10960      a*b+c.)  GDB's values hold almost enough information to establish
10961      the criteria given above --- they identify memory lvalues,
10962      register lvalues, computed values, etcetera.  So we can evaluate
10963      the expression, and then scan the chain of values that leaves
10964      behind to decide whether we can detect any possible change to the
10965      expression's final value using only hardware watchpoints.
10966
10967      However, I don't think that the values returned by inferior
10968      function calls are special in any way.  So this function may not
10969      notice that an expression involving an inferior function call
10970      can't be watched with hardware watchpoints.  FIXME.  */
10971   for (; v; v = value_next (v))
10972     {
10973       if (VALUE_LVAL (v) == lval_memory)
10974         {
10975           if (v != head && value_lazy (v))
10976             /* A lazy memory lvalue in the chain is one that GDB never
10977                needed to fetch; we either just used its address (e.g.,
10978                `a' in `a.b') or we never needed it at all (e.g., `a'
10979                in `a,b').  This doesn't apply to HEAD; if that is
10980                lazy then it was not readable, but watch it anyway.  */
10981             ;
10982           else
10983             {
10984               /* Ahh, memory we actually used!  Check if we can cover
10985                  it with hardware watchpoints.  */
10986               struct type *vtype = check_typedef (value_type (v));
10987
10988               /* We only watch structs and arrays if user asked for it
10989                  explicitly, never if they just happen to appear in a
10990                  middle of some value chain.  */
10991               if (v == head
10992                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
10993                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
10994                 {
10995                   CORE_ADDR vaddr = value_address (v);
10996                   int len;
10997                   int num_regs;
10998
10999                   len = (target_exact_watchpoints
11000                          && is_scalar_type_recursive (vtype))?
11001                     1 : TYPE_LENGTH (value_type (v));
11002
11003                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11004                   if (!num_regs)
11005                     return 0;
11006                   else
11007                     found_memory_cnt += num_regs;
11008                 }
11009             }
11010         }
11011       else if (VALUE_LVAL (v) != not_lval
11012                && deprecated_value_modifiable (v) == 0)
11013         return 0;       /* These are values from the history (e.g., $1).  */
11014       else if (VALUE_LVAL (v) == lval_register)
11015         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11016     }
11017
11018   /* The expression itself looks suitable for using a hardware
11019      watchpoint, but give the target machine a chance to reject it.  */
11020   return found_memory_cnt;
11021 }
11022
11023 void
11024 watch_command_wrapper (const char *arg, int from_tty, int internal)
11025 {
11026   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11027 }
11028
11029 /* A helper function that looks for the "-location" argument and then
11030    calls watch_command_1.  */
11031
11032 static void
11033 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
11034 {
11035   int just_location = 0;
11036
11037   if (arg
11038       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11039           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11040     {
11041       arg = skip_spaces (arg);
11042       just_location = 1;
11043     }
11044
11045   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11046 }
11047
11048 static void
11049 watch_command (const char *arg, int from_tty)
11050 {
11051   watch_maybe_just_location (arg, hw_write, from_tty);
11052 }
11053
11054 void
11055 rwatch_command_wrapper (const char *arg, int from_tty, int internal)
11056 {
11057   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11058 }
11059
11060 static void
11061 rwatch_command (const char *arg, int from_tty)
11062 {
11063   watch_maybe_just_location (arg, hw_read, from_tty);
11064 }
11065
11066 void
11067 awatch_command_wrapper (const char *arg, int from_tty, int internal)
11068 {
11069   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11070 }
11071
11072 static void
11073 awatch_command (const char *arg, int from_tty)
11074 {
11075   watch_maybe_just_location (arg, hw_access, from_tty);
11076 }
11077 \f
11078
11079 /* Data for the FSM that manages the until(location)/advance commands
11080    in infcmd.c.  Here because it uses the mechanisms of
11081    breakpoints.  */
11082
11083 struct until_break_fsm
11084 {
11085   /* The base class.  */
11086   struct thread_fsm thread_fsm;
11087
11088   /* The thread that as current when the command was executed.  */
11089   int thread;
11090
11091   /* The breakpoint set at the destination location.  */
11092   struct breakpoint *location_breakpoint;
11093
11094   /* Breakpoint set at the return address in the caller frame.  May be
11095      NULL.  */
11096   struct breakpoint *caller_breakpoint;
11097 };
11098
11099 static void until_break_fsm_clean_up (struct thread_fsm *self,
11100                                       struct thread_info *thread);
11101 static int until_break_fsm_should_stop (struct thread_fsm *self,
11102                                         struct thread_info *thread);
11103 static enum async_reply_reason
11104   until_break_fsm_async_reply_reason (struct thread_fsm *self);
11105
11106 /* until_break_fsm's vtable.  */
11107
11108 static struct thread_fsm_ops until_break_fsm_ops =
11109 {
11110   NULL, /* dtor */
11111   until_break_fsm_clean_up,
11112   until_break_fsm_should_stop,
11113   NULL, /* return_value */
11114   until_break_fsm_async_reply_reason,
11115 };
11116
11117 /* Allocate a new until_break_command_fsm.  */
11118
11119 static struct until_break_fsm *
11120 new_until_break_fsm (struct interp *cmd_interp, int thread,
11121                      breakpoint_up &&location_breakpoint,
11122                      breakpoint_up &&caller_breakpoint)
11123 {
11124   struct until_break_fsm *sm;
11125
11126   sm = XCNEW (struct until_break_fsm);
11127   thread_fsm_ctor (&sm->thread_fsm, &until_break_fsm_ops, cmd_interp);
11128
11129   sm->thread = thread;
11130   sm->location_breakpoint = location_breakpoint.release ();
11131   sm->caller_breakpoint = caller_breakpoint.release ();
11132
11133   return sm;
11134 }
11135
11136 /* Implementation of the 'should_stop' FSM method for the
11137    until(location)/advance commands.  */
11138
11139 static int
11140 until_break_fsm_should_stop (struct thread_fsm *self,
11141                              struct thread_info *tp)
11142 {
11143   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11144
11145   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11146                               sm->location_breakpoint) != NULL
11147       || (sm->caller_breakpoint != NULL
11148           && bpstat_find_breakpoint (tp->control.stop_bpstat,
11149                                      sm->caller_breakpoint) != NULL))
11150     thread_fsm_set_finished (self);
11151
11152   return 1;
11153 }
11154
11155 /* Implementation of the 'clean_up' FSM method for the
11156    until(location)/advance commands.  */
11157
11158 static void
11159 until_break_fsm_clean_up (struct thread_fsm *self,
11160                           struct thread_info *thread)
11161 {
11162   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11163
11164   /* Clean up our temporary breakpoints.  */
11165   if (sm->location_breakpoint != NULL)
11166     {
11167       delete_breakpoint (sm->location_breakpoint);
11168       sm->location_breakpoint = NULL;
11169     }
11170   if (sm->caller_breakpoint != NULL)
11171     {
11172       delete_breakpoint (sm->caller_breakpoint);
11173       sm->caller_breakpoint = NULL;
11174     }
11175   delete_longjmp_breakpoint (sm->thread);
11176 }
11177
11178 /* Implementation of the 'async_reply_reason' FSM method for the
11179    until(location)/advance commands.  */
11180
11181 static enum async_reply_reason
11182 until_break_fsm_async_reply_reason (struct thread_fsm *self)
11183 {
11184   return EXEC_ASYNC_LOCATION_REACHED;
11185 }
11186
11187 void
11188 until_break_command (const char *arg, int from_tty, int anywhere)
11189 {
11190   struct frame_info *frame;
11191   struct gdbarch *frame_gdbarch;
11192   struct frame_id stack_frame_id;
11193   struct frame_id caller_frame_id;
11194   struct cleanup *old_chain;
11195   int thread;
11196   struct thread_info *tp;
11197   struct until_break_fsm *sm;
11198
11199   clear_proceed_status (0);
11200
11201   /* Set a breakpoint where the user wants it and at return from
11202      this function.  */
11203
11204   event_location_up location = string_to_event_location (&arg, current_language);
11205
11206   std::vector<symtab_and_line> sals
11207     = (last_displayed_sal_is_valid ()
11208        ? decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
11209                         get_last_displayed_symtab (),
11210                         get_last_displayed_line ())
11211        : decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
11212                         NULL, (struct symtab *) NULL, 0));
11213
11214   if (sals.size () != 1)
11215     error (_("Couldn't get information on specified line."));
11216
11217   symtab_and_line &sal = sals[0];
11218
11219   if (*arg)
11220     error (_("Junk at end of arguments."));
11221
11222   resolve_sal_pc (&sal);
11223
11224   tp = inferior_thread ();
11225   thread = tp->global_num;
11226
11227   old_chain = make_cleanup (null_cleanup, NULL);
11228
11229   /* Note linespec handling above invalidates the frame chain.
11230      Installing a breakpoint also invalidates the frame chain (as it
11231      may need to switch threads), so do any frame handling before
11232      that.  */
11233
11234   frame = get_selected_frame (NULL);
11235   frame_gdbarch = get_frame_arch (frame);
11236   stack_frame_id = get_stack_frame_id (frame);
11237   caller_frame_id = frame_unwind_caller_id (frame);
11238
11239   /* Keep within the current frame, or in frames called by the current
11240      one.  */
11241
11242   breakpoint_up caller_breakpoint;
11243   if (frame_id_p (caller_frame_id))
11244     {
11245       struct symtab_and_line sal2;
11246       struct gdbarch *caller_gdbarch;
11247
11248       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11249       sal2.pc = frame_unwind_caller_pc (frame);
11250       caller_gdbarch = frame_unwind_caller_arch (frame);
11251       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11252                                                     sal2,
11253                                                     caller_frame_id,
11254                                                     bp_until);
11255
11256       set_longjmp_breakpoint (tp, caller_frame_id);
11257       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11258     }
11259
11260   /* set_momentary_breakpoint could invalidate FRAME.  */
11261   frame = NULL;
11262
11263   breakpoint_up location_breakpoint;
11264   if (anywhere)
11265     /* If the user told us to continue until a specified location,
11266        we don't specify a frame at which we need to stop.  */
11267     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11268                                                     null_frame_id, bp_until);
11269   else
11270     /* Otherwise, specify the selected frame, because we want to stop
11271        only at the very same frame.  */
11272     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11273                                                     stack_frame_id, bp_until);
11274
11275   sm = new_until_break_fsm (command_interp (), tp->global_num,
11276                             std::move (location_breakpoint),
11277                             std::move (caller_breakpoint));
11278   tp->thread_fsm = &sm->thread_fsm;
11279
11280   discard_cleanups (old_chain);
11281
11282   proceed (-1, GDB_SIGNAL_DEFAULT);
11283 }
11284
11285 /* This function attempts to parse an optional "if <cond>" clause
11286    from the arg string.  If one is not found, it returns NULL.
11287
11288    Else, it returns a pointer to the condition string.  (It does not
11289    attempt to evaluate the string against a particular block.)  And,
11290    it updates arg to point to the first character following the parsed
11291    if clause in the arg string.  */
11292
11293 const char *
11294 ep_parse_optional_if_clause (const char **arg)
11295 {
11296   const char *cond_string;
11297
11298   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11299     return NULL;
11300
11301   /* Skip the "if" keyword.  */
11302   (*arg) += 2;
11303
11304   /* Skip any extra leading whitespace, and record the start of the
11305      condition string.  */
11306   *arg = skip_spaces (*arg);
11307   cond_string = *arg;
11308
11309   /* Assume that the condition occupies the remainder of the arg
11310      string.  */
11311   (*arg) += strlen (cond_string);
11312
11313   return cond_string;
11314 }
11315
11316 /* Commands to deal with catching events, such as signals, exceptions,
11317    process start/exit, etc.  */
11318
11319 typedef enum
11320 {
11321   catch_fork_temporary, catch_vfork_temporary,
11322   catch_fork_permanent, catch_vfork_permanent
11323 }
11324 catch_fork_kind;
11325
11326 static void
11327 catch_fork_command_1 (const char *arg, int from_tty,
11328                       struct cmd_list_element *command)
11329 {
11330   struct gdbarch *gdbarch = get_current_arch ();
11331   const char *cond_string = NULL;
11332   catch_fork_kind fork_kind;
11333   int tempflag;
11334
11335   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11336   tempflag = (fork_kind == catch_fork_temporary
11337               || fork_kind == catch_vfork_temporary);
11338
11339   if (!arg)
11340     arg = "";
11341   arg = skip_spaces (arg);
11342
11343   /* The allowed syntax is:
11344      catch [v]fork
11345      catch [v]fork if <cond>
11346
11347      First, check if there's an if clause.  */
11348   cond_string = ep_parse_optional_if_clause (&arg);
11349
11350   if ((*arg != '\0') && !isspace (*arg))
11351     error (_("Junk at end of arguments."));
11352
11353   /* If this target supports it, create a fork or vfork catchpoint
11354      and enable reporting of such events.  */
11355   switch (fork_kind)
11356     {
11357     case catch_fork_temporary:
11358     case catch_fork_permanent:
11359       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11360                                           &catch_fork_breakpoint_ops);
11361       break;
11362     case catch_vfork_temporary:
11363     case catch_vfork_permanent:
11364       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11365                                           &catch_vfork_breakpoint_ops);
11366       break;
11367     default:
11368       error (_("unsupported or unknown fork kind; cannot catch it"));
11369       break;
11370     }
11371 }
11372
11373 static void
11374 catch_exec_command_1 (const char *arg, int from_tty,
11375                       struct cmd_list_element *command)
11376 {
11377   struct gdbarch *gdbarch = get_current_arch ();
11378   int tempflag;
11379   const char *cond_string = NULL;
11380
11381   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11382
11383   if (!arg)
11384     arg = "";
11385   arg = skip_spaces (arg);
11386
11387   /* The allowed syntax is:
11388      catch exec
11389      catch exec if <cond>
11390
11391      First, check if there's an if clause.  */
11392   cond_string = ep_parse_optional_if_clause (&arg);
11393
11394   if ((*arg != '\0') && !isspace (*arg))
11395     error (_("Junk at end of arguments."));
11396
11397   std::unique_ptr<exec_catchpoint> c (new exec_catchpoint ());
11398   init_catchpoint (c.get (), gdbarch, tempflag, cond_string,
11399                    &catch_exec_breakpoint_ops);
11400   c->exec_pathname = NULL;
11401
11402   install_breakpoint (0, std::move (c), 1);
11403 }
11404
11405 void
11406 init_ada_exception_breakpoint (struct breakpoint *b,
11407                                struct gdbarch *gdbarch,
11408                                struct symtab_and_line sal,
11409                                const char *addr_string,
11410                                const struct breakpoint_ops *ops,
11411                                int tempflag,
11412                                int enabled,
11413                                int from_tty)
11414 {
11415   if (from_tty)
11416     {
11417       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11418       if (!loc_gdbarch)
11419         loc_gdbarch = gdbarch;
11420
11421       describe_other_breakpoints (loc_gdbarch,
11422                                   sal.pspace, sal.pc, sal.section, -1);
11423       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11424          version for exception catchpoints, because two catchpoints
11425          used for different exception names will use the same address.
11426          In this case, a "breakpoint ... also set at..." warning is
11427          unproductive.  Besides, the warning phrasing is also a bit
11428          inappropriate, we should use the word catchpoint, and tell
11429          the user what type of catchpoint it is.  The above is good
11430          enough for now, though.  */
11431     }
11432
11433   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11434
11435   b->enable_state = enabled ? bp_enabled : bp_disabled;
11436   b->disposition = tempflag ? disp_del : disp_donttouch;
11437   b->location = string_to_event_location (&addr_string,
11438                                           language_def (language_ada));
11439   b->language = language_ada;
11440 }
11441
11442 static void
11443 catch_command (const char *arg, int from_tty)
11444 {
11445   error (_("Catch requires an event name."));
11446 }
11447 \f
11448
11449 static void
11450 tcatch_command (const char *arg, int from_tty)
11451 {
11452   error (_("Catch requires an event name."));
11453 }
11454
11455 /* Compare two breakpoints and return a strcmp-like result.  */
11456
11457 static int
11458 compare_breakpoints (const breakpoint *a, const breakpoint *b)
11459 {
11460   uintptr_t ua = (uintptr_t) a;
11461   uintptr_t ub = (uintptr_t) b;
11462
11463   if (a->number < b->number)
11464     return -1;
11465   else if (a->number > b->number)
11466     return 1;
11467
11468   /* Now sort by address, in case we see, e..g, two breakpoints with
11469      the number 0.  */
11470   if (ua < ub)
11471     return -1;
11472   return ua > ub ? 1 : 0;
11473 }
11474
11475 /* Delete breakpoints by address or line.  */
11476
11477 static void
11478 clear_command (const char *arg, int from_tty)
11479 {
11480   struct breakpoint *b;
11481   int default_match;
11482   int i;
11483
11484   std::vector<symtab_and_line> decoded_sals;
11485   symtab_and_line last_sal;
11486   gdb::array_view<symtab_and_line> sals;
11487   if (arg)
11488     {
11489       decoded_sals
11490         = decode_line_with_current_source (arg,
11491                                            (DECODE_LINE_FUNFIRSTLINE
11492                                             | DECODE_LINE_LIST_MODE));
11493       default_match = 0;
11494       sals = decoded_sals;
11495     }
11496   else
11497     {
11498       /* Set sal's line, symtab, pc, and pspace to the values
11499          corresponding to the last call to print_frame_info.  If the
11500          codepoint is not valid, this will set all the fields to 0.  */
11501       last_sal = get_last_displayed_sal ();
11502       if (last_sal.symtab == 0)
11503         error (_("No source file specified."));
11504
11505       default_match = 1;
11506       sals = last_sal;
11507     }
11508
11509   /* We don't call resolve_sal_pc here.  That's not as bad as it
11510      seems, because all existing breakpoints typically have both
11511      file/line and pc set.  So, if clear is given file/line, we can
11512      match this to existing breakpoint without obtaining pc at all.
11513
11514      We only support clearing given the address explicitly 
11515      present in breakpoint table.  Say, we've set breakpoint 
11516      at file:line.  There were several PC values for that file:line,
11517      due to optimization, all in one block.
11518
11519      We've picked one PC value.  If "clear" is issued with another
11520      PC corresponding to the same file:line, the breakpoint won't
11521      be cleared.  We probably can still clear the breakpoint, but 
11522      since the other PC value is never presented to user, user
11523      can only find it by guessing, and it does not seem important
11524      to support that.  */
11525
11526   /* For each line spec given, delete bps which correspond to it.  Do
11527      it in two passes, solely to preserve the current behavior that
11528      from_tty is forced true if we delete more than one
11529      breakpoint.  */
11530
11531   std::vector<struct breakpoint *> found;
11532   for (const auto &sal : sals)
11533     {
11534       const char *sal_fullname;
11535
11536       /* If exact pc given, clear bpts at that pc.
11537          If line given (pc == 0), clear all bpts on specified line.
11538          If defaulting, clear all bpts on default line
11539          or at default pc.
11540
11541          defaulting    sal.pc != 0    tests to do
11542
11543          0              1             pc
11544          1              1             pc _and_ line
11545          0              0             line
11546          1              0             <can't happen> */
11547
11548       sal_fullname = (sal.symtab == NULL
11549                       ? NULL : symtab_to_fullname (sal.symtab));
11550
11551       /* Find all matching breakpoints and add them to 'found'.  */
11552       ALL_BREAKPOINTS (b)
11553         {
11554           int match = 0;
11555           /* Are we going to delete b?  */
11556           if (b->type != bp_none && !is_watchpoint (b))
11557             {
11558               struct bp_location *loc = b->loc;
11559               for (; loc; loc = loc->next)
11560                 {
11561                   /* If the user specified file:line, don't allow a PC
11562                      match.  This matches historical gdb behavior.  */
11563                   int pc_match = (!sal.explicit_line
11564                                   && sal.pc
11565                                   && (loc->pspace == sal.pspace)
11566                                   && (loc->address == sal.pc)
11567                                   && (!section_is_overlay (loc->section)
11568                                       || loc->section == sal.section));
11569                   int line_match = 0;
11570
11571                   if ((default_match || sal.explicit_line)
11572                       && loc->symtab != NULL
11573                       && sal_fullname != NULL
11574                       && sal.pspace == loc->pspace
11575                       && loc->line_number == sal.line
11576                       && filename_cmp (symtab_to_fullname (loc->symtab),
11577                                        sal_fullname) == 0)
11578                     line_match = 1;
11579
11580                   if (pc_match || line_match)
11581                     {
11582                       match = 1;
11583                       break;
11584                     }
11585                 }
11586             }
11587
11588           if (match)
11589             found.push_back (b);
11590         }
11591     }
11592
11593   /* Now go thru the 'found' chain and delete them.  */
11594   if (found.empty ())
11595     {
11596       if (arg)
11597         error (_("No breakpoint at %s."), arg);
11598       else
11599         error (_("No breakpoint at this line."));
11600     }
11601
11602   /* Remove duplicates from the vec.  */
11603   std::sort (found.begin (), found.end (),
11604              [] (const breakpoint *a, const breakpoint *b)
11605              {
11606                return compare_breakpoints (a, b) < 0;
11607              });
11608   found.erase (std::unique (found.begin (), found.end (),
11609                             [] (const breakpoint *a, const breakpoint *b)
11610                             {
11611                               return compare_breakpoints (a, b) == 0;
11612                             }),
11613                found.end ());
11614
11615   if (found.size () > 1)
11616     from_tty = 1;       /* Always report if deleted more than one.  */
11617   if (from_tty)
11618     {
11619       if (found.size () == 1)
11620         printf_unfiltered (_("Deleted breakpoint "));
11621       else
11622         printf_unfiltered (_("Deleted breakpoints "));
11623     }
11624
11625   for (breakpoint *iter : found)
11626     {
11627       if (from_tty)
11628         printf_unfiltered ("%d ", iter->number);
11629       delete_breakpoint (iter);
11630     }
11631   if (from_tty)
11632     putchar_unfiltered ('\n');
11633 }
11634 \f
11635 /* Delete breakpoint in BS if they are `delete' breakpoints and
11636    all breakpoints that are marked for deletion, whether hit or not.
11637    This is called after any breakpoint is hit, or after errors.  */
11638
11639 void
11640 breakpoint_auto_delete (bpstat bs)
11641 {
11642   struct breakpoint *b, *b_tmp;
11643
11644   for (; bs; bs = bs->next)
11645     if (bs->breakpoint_at
11646         && bs->breakpoint_at->disposition == disp_del
11647         && bs->stop)
11648       delete_breakpoint (bs->breakpoint_at);
11649
11650   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11651   {
11652     if (b->disposition == disp_del_at_next_stop)
11653       delete_breakpoint (b);
11654   }
11655 }
11656
11657 /* A comparison function for bp_location AP and BP being interfaced to
11658    qsort.  Sort elements primarily by their ADDRESS (no matter what
11659    does breakpoint_address_is_meaningful say for its OWNER),
11660    secondarily by ordering first permanent elements and
11661    terciarily just ensuring the array is sorted stable way despite
11662    qsort being an unstable algorithm.  */
11663
11664 static int
11665 bp_locations_compare (const void *ap, const void *bp)
11666 {
11667   const struct bp_location *a = *(const struct bp_location **) ap;
11668   const struct bp_location *b = *(const struct bp_location **) bp;
11669
11670   if (a->address != b->address)
11671     return (a->address > b->address) - (a->address < b->address);
11672
11673   /* Sort locations at the same address by their pspace number, keeping
11674      locations of the same inferior (in a multi-inferior environment)
11675      grouped.  */
11676
11677   if (a->pspace->num != b->pspace->num)
11678     return ((a->pspace->num > b->pspace->num)
11679             - (a->pspace->num < b->pspace->num));
11680
11681   /* Sort permanent breakpoints first.  */
11682   if (a->permanent != b->permanent)
11683     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
11684
11685   /* Make the internal GDB representation stable across GDB runs
11686      where A and B memory inside GDB can differ.  Breakpoint locations of
11687      the same type at the same address can be sorted in arbitrary order.  */
11688
11689   if (a->owner->number != b->owner->number)
11690     return ((a->owner->number > b->owner->number)
11691             - (a->owner->number < b->owner->number));
11692
11693   return (a > b) - (a < b);
11694 }
11695
11696 /* Set bp_locations_placed_address_before_address_max and
11697    bp_locations_shadow_len_after_address_max according to the current
11698    content of the bp_locations array.  */
11699
11700 static void
11701 bp_locations_target_extensions_update (void)
11702 {
11703   struct bp_location *bl, **blp_tmp;
11704
11705   bp_locations_placed_address_before_address_max = 0;
11706   bp_locations_shadow_len_after_address_max = 0;
11707
11708   ALL_BP_LOCATIONS (bl, blp_tmp)
11709     {
11710       CORE_ADDR start, end, addr;
11711
11712       if (!bp_location_has_shadow (bl))
11713         continue;
11714
11715       start = bl->target_info.placed_address;
11716       end = start + bl->target_info.shadow_len;
11717
11718       gdb_assert (bl->address >= start);
11719       addr = bl->address - start;
11720       if (addr > bp_locations_placed_address_before_address_max)
11721         bp_locations_placed_address_before_address_max = addr;
11722
11723       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11724
11725       gdb_assert (bl->address < end);
11726       addr = end - bl->address;
11727       if (addr > bp_locations_shadow_len_after_address_max)
11728         bp_locations_shadow_len_after_address_max = addr;
11729     }
11730 }
11731
11732 /* Download tracepoint locations if they haven't been.  */
11733
11734 static void
11735 download_tracepoint_locations (void)
11736 {
11737   struct breakpoint *b;
11738   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11739
11740   scoped_restore_current_pspace_and_thread restore_pspace_thread;
11741
11742   ALL_TRACEPOINTS (b)
11743     {
11744       struct bp_location *bl;
11745       struct tracepoint *t;
11746       int bp_location_downloaded = 0;
11747
11748       if ((b->type == bp_fast_tracepoint
11749            ? !may_insert_fast_tracepoints
11750            : !may_insert_tracepoints))
11751         continue;
11752
11753       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11754         {
11755           if (target_can_download_tracepoint ())
11756             can_download_tracepoint = TRIBOOL_TRUE;
11757           else
11758             can_download_tracepoint = TRIBOOL_FALSE;
11759         }
11760
11761       if (can_download_tracepoint == TRIBOOL_FALSE)
11762         break;
11763
11764       for (bl = b->loc; bl; bl = bl->next)
11765         {
11766           /* In tracepoint, locations are _never_ duplicated, so
11767              should_be_inserted is equivalent to
11768              unduplicated_should_be_inserted.  */
11769           if (!should_be_inserted (bl) || bl->inserted)
11770             continue;
11771
11772           switch_to_program_space_and_thread (bl->pspace);
11773
11774           target_download_tracepoint (bl);
11775
11776           bl->inserted = 1;
11777           bp_location_downloaded = 1;
11778         }
11779       t = (struct tracepoint *) b;
11780       t->number_on_target = b->number;
11781       if (bp_location_downloaded)
11782         observer_notify_breakpoint_modified (b);
11783     }
11784 }
11785
11786 /* Swap the insertion/duplication state between two locations.  */
11787
11788 static void
11789 swap_insertion (struct bp_location *left, struct bp_location *right)
11790 {
11791   const int left_inserted = left->inserted;
11792   const int left_duplicate = left->duplicate;
11793   const int left_needs_update = left->needs_update;
11794   const struct bp_target_info left_target_info = left->target_info;
11795
11796   /* Locations of tracepoints can never be duplicated.  */
11797   if (is_tracepoint (left->owner))
11798     gdb_assert (!left->duplicate);
11799   if (is_tracepoint (right->owner))
11800     gdb_assert (!right->duplicate);
11801
11802   left->inserted = right->inserted;
11803   left->duplicate = right->duplicate;
11804   left->needs_update = right->needs_update;
11805   left->target_info = right->target_info;
11806   right->inserted = left_inserted;
11807   right->duplicate = left_duplicate;
11808   right->needs_update = left_needs_update;
11809   right->target_info = left_target_info;
11810 }
11811
11812 /* Force the re-insertion of the locations at ADDRESS.  This is called
11813    once a new/deleted/modified duplicate location is found and we are evaluating
11814    conditions on the target's side.  Such conditions need to be updated on
11815    the target.  */
11816
11817 static void
11818 force_breakpoint_reinsertion (struct bp_location *bl)
11819 {
11820   struct bp_location **locp = NULL, **loc2p;
11821   struct bp_location *loc;
11822   CORE_ADDR address = 0;
11823   int pspace_num;
11824
11825   address = bl->address;
11826   pspace_num = bl->pspace->num;
11827
11828   /* This is only meaningful if the target is
11829      evaluating conditions and if the user has
11830      opted for condition evaluation on the target's
11831      side.  */
11832   if (gdb_evaluates_breakpoint_condition_p ()
11833       || !target_supports_evaluation_of_breakpoint_conditions ())
11834     return;
11835
11836   /* Flag all breakpoint locations with this address and
11837      the same program space as the location
11838      as "its condition has changed".  We need to
11839      update the conditions on the target's side.  */
11840   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11841     {
11842       loc = *loc2p;
11843
11844       if (!is_breakpoint (loc->owner)
11845           || pspace_num != loc->pspace->num)
11846         continue;
11847
11848       /* Flag the location appropriately.  We use a different state to
11849          let everyone know that we already updated the set of locations
11850          with addr bl->address and program space bl->pspace.  This is so
11851          we don't have to keep calling these functions just to mark locations
11852          that have already been marked.  */
11853       loc->condition_changed = condition_updated;
11854
11855       /* Free the agent expression bytecode as well.  We will compute
11856          it later on.  */
11857       loc->cond_bytecode.reset ();
11858     }
11859 }
11860 /* Called whether new breakpoints are created, or existing breakpoints
11861    deleted, to update the global location list and recompute which
11862    locations are duplicate of which.
11863
11864    The INSERT_MODE flag determines whether locations may not, may, or
11865    shall be inserted now.  See 'enum ugll_insert_mode' for more
11866    info.  */
11867
11868 static void
11869 update_global_location_list (enum ugll_insert_mode insert_mode)
11870 {
11871   struct breakpoint *b;
11872   struct bp_location **locp, *loc;
11873   /* Last breakpoint location address that was marked for update.  */
11874   CORE_ADDR last_addr = 0;
11875   /* Last breakpoint location program space that was marked for update.  */
11876   int last_pspace_num = -1;
11877
11878   /* Used in the duplicates detection below.  When iterating over all
11879      bp_locations, points to the first bp_location of a given address.
11880      Breakpoints and watchpoints of different types are never
11881      duplicates of each other.  Keep one pointer for each type of
11882      breakpoint/watchpoint, so we only need to loop over all locations
11883      once.  */
11884   struct bp_location *bp_loc_first;  /* breakpoint */
11885   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11886   struct bp_location *awp_loc_first; /* access watchpoint */
11887   struct bp_location *rwp_loc_first; /* read watchpoint */
11888
11889   /* Saved former bp_locations array which we compare against the newly
11890      built bp_locations from the current state of ALL_BREAKPOINTS.  */
11891   struct bp_location **old_locp;
11892   unsigned old_locations_count;
11893   gdb::unique_xmalloc_ptr<struct bp_location *> old_locations (bp_locations);
11894
11895   old_locations_count = bp_locations_count;
11896   bp_locations = NULL;
11897   bp_locations_count = 0;
11898
11899   ALL_BREAKPOINTS (b)
11900     for (loc = b->loc; loc; loc = loc->next)
11901       bp_locations_count++;
11902
11903   bp_locations = XNEWVEC (struct bp_location *, bp_locations_count);
11904   locp = bp_locations;
11905   ALL_BREAKPOINTS (b)
11906     for (loc = b->loc; loc; loc = loc->next)
11907       *locp++ = loc;
11908   qsort (bp_locations, bp_locations_count, sizeof (*bp_locations),
11909          bp_locations_compare);
11910
11911   bp_locations_target_extensions_update ();
11912
11913   /* Identify bp_location instances that are no longer present in the
11914      new list, and therefore should be freed.  Note that it's not
11915      necessary that those locations should be removed from inferior --
11916      if there's another location at the same address (previously
11917      marked as duplicate), we don't need to remove/insert the
11918      location.
11919      
11920      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11921      and former bp_location array state respectively.  */
11922
11923   locp = bp_locations;
11924   for (old_locp = old_locations.get ();
11925        old_locp < old_locations.get () + old_locations_count;
11926        old_locp++)
11927     {
11928       struct bp_location *old_loc = *old_locp;
11929       struct bp_location **loc2p;
11930
11931       /* Tells if 'old_loc' is found among the new locations.  If
11932          not, we have to free it.  */
11933       int found_object = 0;
11934       /* Tells if the location should remain inserted in the target.  */
11935       int keep_in_target = 0;
11936       int removed = 0;
11937
11938       /* Skip LOCP entries which will definitely never be needed.
11939          Stop either at or being the one matching OLD_LOC.  */
11940       while (locp < bp_locations + bp_locations_count
11941              && (*locp)->address < old_loc->address)
11942         locp++;
11943
11944       for (loc2p = locp;
11945            (loc2p < bp_locations + bp_locations_count
11946             && (*loc2p)->address == old_loc->address);
11947            loc2p++)
11948         {
11949           /* Check if this is a new/duplicated location or a duplicated
11950              location that had its condition modified.  If so, we want to send
11951              its condition to the target if evaluation of conditions is taking
11952              place there.  */
11953           if ((*loc2p)->condition_changed == condition_modified
11954               && (last_addr != old_loc->address
11955                   || last_pspace_num != old_loc->pspace->num))
11956             {
11957               force_breakpoint_reinsertion (*loc2p);
11958               last_pspace_num = old_loc->pspace->num;
11959             }
11960
11961           if (*loc2p == old_loc)
11962             found_object = 1;
11963         }
11964
11965       /* We have already handled this address, update it so that we don't
11966          have to go through updates again.  */
11967       last_addr = old_loc->address;
11968
11969       /* Target-side condition evaluation: Handle deleted locations.  */
11970       if (!found_object)
11971         force_breakpoint_reinsertion (old_loc);
11972
11973       /* If this location is no longer present, and inserted, look if
11974          there's maybe a new location at the same address.  If so,
11975          mark that one inserted, and don't remove this one.  This is
11976          needed so that we don't have a time window where a breakpoint
11977          at certain location is not inserted.  */
11978
11979       if (old_loc->inserted)
11980         {
11981           /* If the location is inserted now, we might have to remove
11982              it.  */
11983
11984           if (found_object && should_be_inserted (old_loc))
11985             {
11986               /* The location is still present in the location list,
11987                  and still should be inserted.  Don't do anything.  */
11988               keep_in_target = 1;
11989             }
11990           else
11991             {
11992               /* This location still exists, but it won't be kept in the
11993                  target since it may have been disabled.  We proceed to
11994                  remove its target-side condition.  */
11995
11996               /* The location is either no longer present, or got
11997                  disabled.  See if there's another location at the
11998                  same address, in which case we don't need to remove
11999                  this one from the target.  */
12000
12001               /* OLD_LOC comes from existing struct breakpoint.  */
12002               if (breakpoint_address_is_meaningful (old_loc->owner))
12003                 {
12004                   for (loc2p = locp;
12005                        (loc2p < bp_locations + bp_locations_count
12006                         && (*loc2p)->address == old_loc->address);
12007                        loc2p++)
12008                     {
12009                       struct bp_location *loc2 = *loc2p;
12010
12011                       if (breakpoint_locations_match (loc2, old_loc))
12012                         {
12013                           /* Read watchpoint locations are switched to
12014                              access watchpoints, if the former are not
12015                              supported, but the latter are.  */
12016                           if (is_hardware_watchpoint (old_loc->owner))
12017                             {
12018                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12019                               loc2->watchpoint_type = old_loc->watchpoint_type;
12020                             }
12021
12022                           /* loc2 is a duplicated location. We need to check
12023                              if it should be inserted in case it will be
12024                              unduplicated.  */
12025                           if (loc2 != old_loc
12026                               && unduplicated_should_be_inserted (loc2))
12027                             {
12028                               swap_insertion (old_loc, loc2);
12029                               keep_in_target = 1;
12030                               break;
12031                             }
12032                         }
12033                     }
12034                 }
12035             }
12036
12037           if (!keep_in_target)
12038             {
12039               if (remove_breakpoint (old_loc))
12040                 {
12041                   /* This is just about all we can do.  We could keep
12042                      this location on the global list, and try to
12043                      remove it next time, but there's no particular
12044                      reason why we will succeed next time.
12045                      
12046                      Note that at this point, old_loc->owner is still
12047                      valid, as delete_breakpoint frees the breakpoint
12048                      only after calling us.  */
12049                   printf_filtered (_("warning: Error removing "
12050                                      "breakpoint %d\n"), 
12051                                    old_loc->owner->number);
12052                 }
12053               removed = 1;
12054             }
12055         }
12056
12057       if (!found_object)
12058         {
12059           if (removed && target_is_non_stop_p ()
12060               && need_moribund_for_location_type (old_loc))
12061             {
12062               /* This location was removed from the target.  In
12063                  non-stop mode, a race condition is possible where
12064                  we've removed a breakpoint, but stop events for that
12065                  breakpoint are already queued and will arrive later.
12066                  We apply an heuristic to be able to distinguish such
12067                  SIGTRAPs from other random SIGTRAPs: we keep this
12068                  breakpoint location for a bit, and will retire it
12069                  after we see some number of events.  The theory here
12070                  is that reporting of events should, "on the average",
12071                  be fair, so after a while we'll see events from all
12072                  threads that have anything of interest, and no longer
12073                  need to keep this breakpoint location around.  We
12074                  don't hold locations forever so to reduce chances of
12075                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12076                  SIGTRAP.
12077
12078                  The heuristic failing can be disastrous on
12079                  decr_pc_after_break targets.
12080
12081                  On decr_pc_after_break targets, like e.g., x86-linux,
12082                  if we fail to recognize a late breakpoint SIGTRAP,
12083                  because events_till_retirement has reached 0 too
12084                  soon, we'll fail to do the PC adjustment, and report
12085                  a random SIGTRAP to the user.  When the user resumes
12086                  the inferior, it will most likely immediately crash
12087                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12088                  corrupted, because of being resumed e.g., in the
12089                  middle of a multi-byte instruction, or skipped a
12090                  one-byte instruction.  This was actually seen happen
12091                  on native x86-linux, and should be less rare on
12092                  targets that do not support new thread events, like
12093                  remote, due to the heuristic depending on
12094                  thread_count.
12095
12096                  Mistaking a random SIGTRAP for a breakpoint trap
12097                  causes similar symptoms (PC adjustment applied when
12098                  it shouldn't), but then again, playing with SIGTRAPs
12099                  behind the debugger's back is asking for trouble.
12100
12101                  Since hardware watchpoint traps are always
12102                  distinguishable from other traps, so we don't need to
12103                  apply keep hardware watchpoint moribund locations
12104                  around.  We simply always ignore hardware watchpoint
12105                  traps we can no longer explain.  */
12106
12107               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12108               old_loc->owner = NULL;
12109
12110               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12111             }
12112           else
12113             {
12114               old_loc->owner = NULL;
12115               decref_bp_location (&old_loc);
12116             }
12117         }
12118     }
12119
12120   /* Rescan breakpoints at the same address and section, marking the
12121      first one as "first" and any others as "duplicates".  This is so
12122      that the bpt instruction is only inserted once.  If we have a
12123      permanent breakpoint at the same place as BPT, make that one the
12124      official one, and the rest as duplicates.  Permanent breakpoints
12125      are sorted first for the same address.
12126
12127      Do the same for hardware watchpoints, but also considering the
12128      watchpoint's type (regular/access/read) and length.  */
12129
12130   bp_loc_first = NULL;
12131   wp_loc_first = NULL;
12132   awp_loc_first = NULL;
12133   rwp_loc_first = NULL;
12134   ALL_BP_LOCATIONS (loc, locp)
12135     {
12136       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12137          non-NULL.  */
12138       struct bp_location **loc_first_p;
12139       b = loc->owner;
12140
12141       if (!unduplicated_should_be_inserted (loc)
12142           || !breakpoint_address_is_meaningful (b)
12143           /* Don't detect duplicate for tracepoint locations because they are
12144            never duplicated.  See the comments in field `duplicate' of
12145            `struct bp_location'.  */
12146           || is_tracepoint (b))
12147         {
12148           /* Clear the condition modification flag.  */
12149           loc->condition_changed = condition_unchanged;
12150           continue;
12151         }
12152
12153       if (b->type == bp_hardware_watchpoint)
12154         loc_first_p = &wp_loc_first;
12155       else if (b->type == bp_read_watchpoint)
12156         loc_first_p = &rwp_loc_first;
12157       else if (b->type == bp_access_watchpoint)
12158         loc_first_p = &awp_loc_first;
12159       else
12160         loc_first_p = &bp_loc_first;
12161
12162       if (*loc_first_p == NULL
12163           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12164           || !breakpoint_locations_match (loc, *loc_first_p))
12165         {
12166           *loc_first_p = loc;
12167           loc->duplicate = 0;
12168
12169           if (is_breakpoint (loc->owner) && loc->condition_changed)
12170             {
12171               loc->needs_update = 1;
12172               /* Clear the condition modification flag.  */
12173               loc->condition_changed = condition_unchanged;
12174             }
12175           continue;
12176         }
12177
12178
12179       /* This and the above ensure the invariant that the first location
12180          is not duplicated, and is the inserted one.
12181          All following are marked as duplicated, and are not inserted.  */
12182       if (loc->inserted)
12183         swap_insertion (loc, *loc_first_p);
12184       loc->duplicate = 1;
12185
12186       /* Clear the condition modification flag.  */
12187       loc->condition_changed = condition_unchanged;
12188     }
12189
12190   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12191     {
12192       if (insert_mode != UGLL_DONT_INSERT)
12193         insert_breakpoint_locations ();
12194       else
12195         {
12196           /* Even though the caller told us to not insert new
12197              locations, we may still need to update conditions on the
12198              target's side of breakpoints that were already inserted
12199              if the target is evaluating breakpoint conditions.  We
12200              only update conditions for locations that are marked
12201              "needs_update".  */
12202           update_inserted_breakpoint_locations ();
12203         }
12204     }
12205
12206   if (insert_mode != UGLL_DONT_INSERT)
12207     download_tracepoint_locations ();
12208 }
12209
12210 void
12211 breakpoint_retire_moribund (void)
12212 {
12213   struct bp_location *loc;
12214   int ix;
12215
12216   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12217     if (--(loc->events_till_retirement) == 0)
12218       {
12219         decref_bp_location (&loc);
12220         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12221         --ix;
12222       }
12223 }
12224
12225 static void
12226 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12227 {
12228
12229   TRY
12230     {
12231       update_global_location_list (insert_mode);
12232     }
12233   CATCH (e, RETURN_MASK_ERROR)
12234     {
12235     }
12236   END_CATCH
12237 }
12238
12239 /* Clear BKP from a BPS.  */
12240
12241 static void
12242 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12243 {
12244   bpstat bs;
12245
12246   for (bs = bps; bs; bs = bs->next)
12247     if (bs->breakpoint_at == bpt)
12248       {
12249         bs->breakpoint_at = NULL;
12250         bs->old_val = NULL;
12251         /* bs->commands will be freed later.  */
12252       }
12253 }
12254
12255 /* Callback for iterate_over_threads.  */
12256 static int
12257 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12258 {
12259   struct breakpoint *bpt = (struct breakpoint *) data;
12260
12261   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12262   return 0;
12263 }
12264
12265 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12266    callbacks.  */
12267
12268 static void
12269 say_where (struct breakpoint *b)
12270 {
12271   struct value_print_options opts;
12272
12273   get_user_print_options (&opts);
12274
12275   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12276      single string.  */
12277   if (b->loc == NULL)
12278     {
12279       /* For pending locations, the output differs slightly based
12280          on b->extra_string.  If this is non-NULL, it contains either
12281          a condition or dprintf arguments.  */
12282       if (b->extra_string == NULL)
12283         {
12284           printf_filtered (_(" (%s) pending."),
12285                            event_location_to_string (b->location.get ()));
12286         }
12287       else if (b->type == bp_dprintf)
12288         {
12289           printf_filtered (_(" (%s,%s) pending."),
12290                            event_location_to_string (b->location.get ()),
12291                            b->extra_string);
12292         }
12293       else
12294         {
12295           printf_filtered (_(" (%s %s) pending."),
12296                            event_location_to_string (b->location.get ()),
12297                            b->extra_string);
12298         }
12299     }
12300   else
12301     {
12302       if (opts.addressprint || b->loc->symtab == NULL)
12303         {
12304           printf_filtered (" at ");
12305           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12306                           gdb_stdout);
12307         }
12308       if (b->loc->symtab != NULL)
12309         {
12310           /* If there is a single location, we can print the location
12311              more nicely.  */
12312           if (b->loc->next == NULL)
12313             printf_filtered (": file %s, line %d.",
12314                              symtab_to_filename_for_display (b->loc->symtab),
12315                              b->loc->line_number);
12316           else
12317             /* This is not ideal, but each location may have a
12318                different file name, and this at least reflects the
12319                real situation somewhat.  */
12320             printf_filtered (": %s.",
12321                              event_location_to_string (b->location.get ()));
12322         }
12323
12324       if (b->loc->next)
12325         {
12326           struct bp_location *loc = b->loc;
12327           int n = 0;
12328           for (; loc; loc = loc->next)
12329             ++n;
12330           printf_filtered (" (%d locations)", n);
12331         }
12332     }
12333 }
12334
12335 /* Default bp_location_ops methods.  */
12336
12337 static void
12338 bp_location_dtor (struct bp_location *self)
12339 {
12340   xfree (self->function_name);
12341 }
12342
12343 static const struct bp_location_ops bp_location_ops =
12344 {
12345   bp_location_dtor
12346 };
12347
12348 /* Destructor for the breakpoint base class.  */
12349
12350 breakpoint::~breakpoint ()
12351 {
12352   xfree (this->cond_string);
12353   xfree (this->extra_string);
12354   xfree (this->filter);
12355 }
12356
12357 static struct bp_location *
12358 base_breakpoint_allocate_location (struct breakpoint *self)
12359 {
12360   return new bp_location (&bp_location_ops, self);
12361 }
12362
12363 static void
12364 base_breakpoint_re_set (struct breakpoint *b)
12365 {
12366   /* Nothing to re-set. */
12367 }
12368
12369 #define internal_error_pure_virtual_called() \
12370   gdb_assert_not_reached ("pure virtual function called")
12371
12372 static int
12373 base_breakpoint_insert_location (struct bp_location *bl)
12374 {
12375   internal_error_pure_virtual_called ();
12376 }
12377
12378 static int
12379 base_breakpoint_remove_location (struct bp_location *bl,
12380                                  enum remove_bp_reason reason)
12381 {
12382   internal_error_pure_virtual_called ();
12383 }
12384
12385 static int
12386 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12387                                 const address_space *aspace,
12388                                 CORE_ADDR bp_addr,
12389                                 const struct target_waitstatus *ws)
12390 {
12391   internal_error_pure_virtual_called ();
12392 }
12393
12394 static void
12395 base_breakpoint_check_status (bpstat bs)
12396 {
12397   /* Always stop.   */
12398 }
12399
12400 /* A "works_in_software_mode" breakpoint_ops method that just internal
12401    errors.  */
12402
12403 static int
12404 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12405 {
12406   internal_error_pure_virtual_called ();
12407 }
12408
12409 /* A "resources_needed" breakpoint_ops method that just internal
12410    errors.  */
12411
12412 static int
12413 base_breakpoint_resources_needed (const struct bp_location *bl)
12414 {
12415   internal_error_pure_virtual_called ();
12416 }
12417
12418 static enum print_stop_action
12419 base_breakpoint_print_it (bpstat bs)
12420 {
12421   internal_error_pure_virtual_called ();
12422 }
12423
12424 static void
12425 base_breakpoint_print_one_detail (const struct breakpoint *self,
12426                                   struct ui_out *uiout)
12427 {
12428   /* nothing */
12429 }
12430
12431 static void
12432 base_breakpoint_print_mention (struct breakpoint *b)
12433 {
12434   internal_error_pure_virtual_called ();
12435 }
12436
12437 static void
12438 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12439 {
12440   internal_error_pure_virtual_called ();
12441 }
12442
12443 static void
12444 base_breakpoint_create_sals_from_location
12445   (const struct event_location *location,
12446    struct linespec_result *canonical,
12447    enum bptype type_wanted)
12448 {
12449   internal_error_pure_virtual_called ();
12450 }
12451
12452 static void
12453 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12454                                         struct linespec_result *c,
12455                                         gdb::unique_xmalloc_ptr<char> cond_string,
12456                                         gdb::unique_xmalloc_ptr<char> extra_string,
12457                                         enum bptype type_wanted,
12458                                         enum bpdisp disposition,
12459                                         int thread,
12460                                         int task, int ignore_count,
12461                                         const struct breakpoint_ops *o,
12462                                         int from_tty, int enabled,
12463                                         int internal, unsigned flags)
12464 {
12465   internal_error_pure_virtual_called ();
12466 }
12467
12468 static std::vector<symtab_and_line>
12469 base_breakpoint_decode_location (struct breakpoint *b,
12470                                  const struct event_location *location,
12471                                  struct program_space *search_pspace)
12472 {
12473   internal_error_pure_virtual_called ();
12474 }
12475
12476 /* The default 'explains_signal' method.  */
12477
12478 static int
12479 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12480 {
12481   return 1;
12482 }
12483
12484 /* The default "after_condition_true" method.  */
12485
12486 static void
12487 base_breakpoint_after_condition_true (struct bpstats *bs)
12488 {
12489   /* Nothing to do.   */
12490 }
12491
12492 struct breakpoint_ops base_breakpoint_ops =
12493 {
12494   base_breakpoint_allocate_location,
12495   base_breakpoint_re_set,
12496   base_breakpoint_insert_location,
12497   base_breakpoint_remove_location,
12498   base_breakpoint_breakpoint_hit,
12499   base_breakpoint_check_status,
12500   base_breakpoint_resources_needed,
12501   base_breakpoint_works_in_software_mode,
12502   base_breakpoint_print_it,
12503   NULL,
12504   base_breakpoint_print_one_detail,
12505   base_breakpoint_print_mention,
12506   base_breakpoint_print_recreate,
12507   base_breakpoint_create_sals_from_location,
12508   base_breakpoint_create_breakpoints_sal,
12509   base_breakpoint_decode_location,
12510   base_breakpoint_explains_signal,
12511   base_breakpoint_after_condition_true,
12512 };
12513
12514 /* Default breakpoint_ops methods.  */
12515
12516 static void
12517 bkpt_re_set (struct breakpoint *b)
12518 {
12519   /* FIXME: is this still reachable?  */
12520   if (breakpoint_event_location_empty_p (b))
12521     {
12522       /* Anything without a location can't be re-set.  */
12523       delete_breakpoint (b);
12524       return;
12525     }
12526
12527   breakpoint_re_set_default (b);
12528 }
12529
12530 static int
12531 bkpt_insert_location (struct bp_location *bl)
12532 {
12533   CORE_ADDR addr = bl->target_info.reqstd_address;
12534
12535   bl->target_info.kind = breakpoint_kind (bl, &addr);
12536   bl->target_info.placed_address = addr;
12537
12538   if (bl->loc_type == bp_loc_hardware_breakpoint)
12539     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12540   else
12541     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12542 }
12543
12544 static int
12545 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
12546 {
12547   if (bl->loc_type == bp_loc_hardware_breakpoint)
12548     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12549   else
12550     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12551 }
12552
12553 static int
12554 bkpt_breakpoint_hit (const struct bp_location *bl,
12555                      const address_space *aspace, CORE_ADDR bp_addr,
12556                      const struct target_waitstatus *ws)
12557 {
12558   if (ws->kind != TARGET_WAITKIND_STOPPED
12559       || ws->value.sig != GDB_SIGNAL_TRAP)
12560     return 0;
12561
12562   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12563                                  aspace, bp_addr))
12564     return 0;
12565
12566   if (overlay_debugging         /* unmapped overlay section */
12567       && section_is_overlay (bl->section)
12568       && !section_is_mapped (bl->section))
12569     return 0;
12570
12571   return 1;
12572 }
12573
12574 static int
12575 dprintf_breakpoint_hit (const struct bp_location *bl,
12576                         const address_space *aspace, CORE_ADDR bp_addr,
12577                         const struct target_waitstatus *ws)
12578 {
12579   if (dprintf_style == dprintf_style_agent
12580       && target_can_run_breakpoint_commands ())
12581     {
12582       /* An agent-style dprintf never causes a stop.  If we see a trap
12583          for this address it must be for a breakpoint that happens to
12584          be set at the same address.  */
12585       return 0;
12586     }
12587
12588   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12589 }
12590
12591 static int
12592 bkpt_resources_needed (const struct bp_location *bl)
12593 {
12594   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12595
12596   return 1;
12597 }
12598
12599 static enum print_stop_action
12600 bkpt_print_it (bpstat bs)
12601 {
12602   struct breakpoint *b;
12603   const struct bp_location *bl;
12604   int bp_temp;
12605   struct ui_out *uiout = current_uiout;
12606
12607   gdb_assert (bs->bp_location_at != NULL);
12608
12609   bl = bs->bp_location_at;
12610   b = bs->breakpoint_at;
12611
12612   bp_temp = b->disposition == disp_del;
12613   if (bl->address != bl->requested_address)
12614     breakpoint_adjustment_warning (bl->requested_address,
12615                                    bl->address,
12616                                    b->number, 1);
12617   annotate_breakpoint (b->number);
12618   maybe_print_thread_hit_breakpoint (uiout);
12619
12620   if (bp_temp)
12621     uiout->text ("Temporary breakpoint ");
12622   else
12623     uiout->text ("Breakpoint ");
12624   if (uiout->is_mi_like_p ())
12625     {
12626       uiout->field_string ("reason",
12627                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12628       uiout->field_string ("disp", bpdisp_text (b->disposition));
12629     }
12630   uiout->field_int ("bkptno", b->number);
12631   uiout->text (", ");
12632
12633   return PRINT_SRC_AND_LOC;
12634 }
12635
12636 static void
12637 bkpt_print_mention (struct breakpoint *b)
12638 {
12639   if (current_uiout->is_mi_like_p ())
12640     return;
12641
12642   switch (b->type)
12643     {
12644     case bp_breakpoint:
12645     case bp_gnu_ifunc_resolver:
12646       if (b->disposition == disp_del)
12647         printf_filtered (_("Temporary breakpoint"));
12648       else
12649         printf_filtered (_("Breakpoint"));
12650       printf_filtered (_(" %d"), b->number);
12651       if (b->type == bp_gnu_ifunc_resolver)
12652         printf_filtered (_(" at gnu-indirect-function resolver"));
12653       break;
12654     case bp_hardware_breakpoint:
12655       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12656       break;
12657     case bp_dprintf:
12658       printf_filtered (_("Dprintf %d"), b->number);
12659       break;
12660     }
12661
12662   say_where (b);
12663 }
12664
12665 static void
12666 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12667 {
12668   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12669     fprintf_unfiltered (fp, "tbreak");
12670   else if (tp->type == bp_breakpoint)
12671     fprintf_unfiltered (fp, "break");
12672   else if (tp->type == bp_hardware_breakpoint
12673            && tp->disposition == disp_del)
12674     fprintf_unfiltered (fp, "thbreak");
12675   else if (tp->type == bp_hardware_breakpoint)
12676     fprintf_unfiltered (fp, "hbreak");
12677   else
12678     internal_error (__FILE__, __LINE__,
12679                     _("unhandled breakpoint type %d"), (int) tp->type);
12680
12681   fprintf_unfiltered (fp, " %s",
12682                       event_location_to_string (tp->location.get ()));
12683
12684   /* Print out extra_string if this breakpoint is pending.  It might
12685      contain, for example, conditions that were set by the user.  */
12686   if (tp->loc == NULL && tp->extra_string != NULL)
12687     fprintf_unfiltered (fp, " %s", tp->extra_string);
12688
12689   print_recreate_thread (tp, fp);
12690 }
12691
12692 static void
12693 bkpt_create_sals_from_location (const struct event_location *location,
12694                                 struct linespec_result *canonical,
12695                                 enum bptype type_wanted)
12696 {
12697   create_sals_from_location_default (location, canonical, type_wanted);
12698 }
12699
12700 static void
12701 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12702                              struct linespec_result *canonical,
12703                              gdb::unique_xmalloc_ptr<char> cond_string,
12704                              gdb::unique_xmalloc_ptr<char> extra_string,
12705                              enum bptype type_wanted,
12706                              enum bpdisp disposition,
12707                              int thread,
12708                              int task, int ignore_count,
12709                              const struct breakpoint_ops *ops,
12710                              int from_tty, int enabled,
12711                              int internal, unsigned flags)
12712 {
12713   create_breakpoints_sal_default (gdbarch, canonical,
12714                                   std::move (cond_string),
12715                                   std::move (extra_string),
12716                                   type_wanted,
12717                                   disposition, thread, task,
12718                                   ignore_count, ops, from_tty,
12719                                   enabled, internal, flags);
12720 }
12721
12722 static std::vector<symtab_and_line>
12723 bkpt_decode_location (struct breakpoint *b,
12724                       const struct event_location *location,
12725                       struct program_space *search_pspace)
12726 {
12727   return decode_location_default (b, location, search_pspace);
12728 }
12729
12730 /* Virtual table for internal breakpoints.  */
12731
12732 static void
12733 internal_bkpt_re_set (struct breakpoint *b)
12734 {
12735   switch (b->type)
12736     {
12737       /* Delete overlay event and longjmp master breakpoints; they
12738          will be reset later by breakpoint_re_set.  */
12739     case bp_overlay_event:
12740     case bp_longjmp_master:
12741     case bp_std_terminate_master:
12742     case bp_exception_master:
12743       delete_breakpoint (b);
12744       break;
12745
12746       /* This breakpoint is special, it's set up when the inferior
12747          starts and we really don't want to touch it.  */
12748     case bp_shlib_event:
12749
12750       /* Like bp_shlib_event, this breakpoint type is special.  Once
12751          it is set up, we do not want to touch it.  */
12752     case bp_thread_event:
12753       break;
12754     }
12755 }
12756
12757 static void
12758 internal_bkpt_check_status (bpstat bs)
12759 {
12760   if (bs->breakpoint_at->type == bp_shlib_event)
12761     {
12762       /* If requested, stop when the dynamic linker notifies GDB of
12763          events.  This allows the user to get control and place
12764          breakpoints in initializer routines for dynamically loaded
12765          objects (among other things).  */
12766       bs->stop = stop_on_solib_events;
12767       bs->print = stop_on_solib_events;
12768     }
12769   else
12770     bs->stop = 0;
12771 }
12772
12773 static enum print_stop_action
12774 internal_bkpt_print_it (bpstat bs)
12775 {
12776   struct breakpoint *b;
12777
12778   b = bs->breakpoint_at;
12779
12780   switch (b->type)
12781     {
12782     case bp_shlib_event:
12783       /* Did we stop because the user set the stop_on_solib_events
12784          variable?  (If so, we report this as a generic, "Stopped due
12785          to shlib event" message.) */
12786       print_solib_event (0);
12787       break;
12788
12789     case bp_thread_event:
12790       /* Not sure how we will get here.
12791          GDB should not stop for these breakpoints.  */
12792       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12793       break;
12794
12795     case bp_overlay_event:
12796       /* By analogy with the thread event, GDB should not stop for these.  */
12797       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12798       break;
12799
12800     case bp_longjmp_master:
12801       /* These should never be enabled.  */
12802       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12803       break;
12804
12805     case bp_std_terminate_master:
12806       /* These should never be enabled.  */
12807       printf_filtered (_("std::terminate Master Breakpoint: "
12808                          "gdb should not stop!\n"));
12809       break;
12810
12811     case bp_exception_master:
12812       /* These should never be enabled.  */
12813       printf_filtered (_("Exception Master Breakpoint: "
12814                          "gdb should not stop!\n"));
12815       break;
12816     }
12817
12818   return PRINT_NOTHING;
12819 }
12820
12821 static void
12822 internal_bkpt_print_mention (struct breakpoint *b)
12823 {
12824   /* Nothing to mention.  These breakpoints are internal.  */
12825 }
12826
12827 /* Virtual table for momentary breakpoints  */
12828
12829 static void
12830 momentary_bkpt_re_set (struct breakpoint *b)
12831 {
12832   /* Keep temporary breakpoints, which can be encountered when we step
12833      over a dlopen call and solib_add is resetting the breakpoints.
12834      Otherwise these should have been blown away via the cleanup chain
12835      or by breakpoint_init_inferior when we rerun the executable.  */
12836 }
12837
12838 static void
12839 momentary_bkpt_check_status (bpstat bs)
12840 {
12841   /* Nothing.  The point of these breakpoints is causing a stop.  */
12842 }
12843
12844 static enum print_stop_action
12845 momentary_bkpt_print_it (bpstat bs)
12846 {
12847   return PRINT_UNKNOWN;
12848 }
12849
12850 static void
12851 momentary_bkpt_print_mention (struct breakpoint *b)
12852 {
12853   /* Nothing to mention.  These breakpoints are internal.  */
12854 }
12855
12856 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12857
12858    It gets cleared already on the removal of the first one of such placed
12859    breakpoints.  This is OK as they get all removed altogether.  */
12860
12861 longjmp_breakpoint::~longjmp_breakpoint ()
12862 {
12863   thread_info *tp = find_thread_global_id (this->thread);
12864
12865   if (tp != NULL)
12866     tp->initiating_frame = null_frame_id;
12867 }
12868
12869 /* Specific methods for probe breakpoints.  */
12870
12871 static int
12872 bkpt_probe_insert_location (struct bp_location *bl)
12873 {
12874   int v = bkpt_insert_location (bl);
12875
12876   if (v == 0)
12877     {
12878       /* The insertion was successful, now let's set the probe's semaphore
12879          if needed.  */
12880       bl->probe.prob->set_semaphore (bl->probe.objfile, bl->gdbarch);
12881     }
12882
12883   return v;
12884 }
12885
12886 static int
12887 bkpt_probe_remove_location (struct bp_location *bl,
12888                             enum remove_bp_reason reason)
12889 {
12890   /* Let's clear the semaphore before removing the location.  */
12891   bl->probe.prob->clear_semaphore (bl->probe.objfile, bl->gdbarch);
12892
12893   return bkpt_remove_location (bl, reason);
12894 }
12895
12896 static void
12897 bkpt_probe_create_sals_from_location (const struct event_location *location,
12898                                       struct linespec_result *canonical,
12899                                       enum bptype type_wanted)
12900 {
12901   struct linespec_sals lsal;
12902
12903   lsal.sals = parse_probes (location, NULL, canonical);
12904   lsal.canonical
12905     = xstrdup (event_location_to_string (canonical->location.get ()));
12906   canonical->lsals.push_back (std::move (lsal));
12907 }
12908
12909 static std::vector<symtab_and_line>
12910 bkpt_probe_decode_location (struct breakpoint *b,
12911                             const struct event_location *location,
12912                             struct program_space *search_pspace)
12913 {
12914   std::vector<symtab_and_line> sals = parse_probes (location, search_pspace, NULL);
12915   if (sals.empty ())
12916     error (_("probe not found"));
12917   return sals;
12918 }
12919
12920 /* The breakpoint_ops structure to be used in tracepoints.  */
12921
12922 static void
12923 tracepoint_re_set (struct breakpoint *b)
12924 {
12925   breakpoint_re_set_default (b);
12926 }
12927
12928 static int
12929 tracepoint_breakpoint_hit (const struct bp_location *bl,
12930                            const address_space *aspace, CORE_ADDR bp_addr,
12931                            const struct target_waitstatus *ws)
12932 {
12933   /* By definition, the inferior does not report stops at
12934      tracepoints.  */
12935   return 0;
12936 }
12937
12938 static void
12939 tracepoint_print_one_detail (const struct breakpoint *self,
12940                              struct ui_out *uiout)
12941 {
12942   struct tracepoint *tp = (struct tracepoint *) self;
12943   if (tp->static_trace_marker_id)
12944     {
12945       gdb_assert (self->type == bp_static_tracepoint);
12946
12947       uiout->text ("\tmarker id is ");
12948       uiout->field_string ("static-tracepoint-marker-string-id",
12949                            tp->static_trace_marker_id);
12950       uiout->text ("\n");
12951     }
12952 }
12953
12954 static void
12955 tracepoint_print_mention (struct breakpoint *b)
12956 {
12957   if (current_uiout->is_mi_like_p ())
12958     return;
12959
12960   switch (b->type)
12961     {
12962     case bp_tracepoint:
12963       printf_filtered (_("Tracepoint"));
12964       printf_filtered (_(" %d"), b->number);
12965       break;
12966     case bp_fast_tracepoint:
12967       printf_filtered (_("Fast tracepoint"));
12968       printf_filtered (_(" %d"), b->number);
12969       break;
12970     case bp_static_tracepoint:
12971       printf_filtered (_("Static tracepoint"));
12972       printf_filtered (_(" %d"), b->number);
12973       break;
12974     default:
12975       internal_error (__FILE__, __LINE__,
12976                       _("unhandled tracepoint type %d"), (int) b->type);
12977     }
12978
12979   say_where (b);
12980 }
12981
12982 static void
12983 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
12984 {
12985   struct tracepoint *tp = (struct tracepoint *) self;
12986
12987   if (self->type == bp_fast_tracepoint)
12988     fprintf_unfiltered (fp, "ftrace");
12989   else if (self->type == bp_static_tracepoint)
12990     fprintf_unfiltered (fp, "strace");
12991   else if (self->type == bp_tracepoint)
12992     fprintf_unfiltered (fp, "trace");
12993   else
12994     internal_error (__FILE__, __LINE__,
12995                     _("unhandled tracepoint type %d"), (int) self->type);
12996
12997   fprintf_unfiltered (fp, " %s",
12998                       event_location_to_string (self->location.get ()));
12999   print_recreate_thread (self, fp);
13000
13001   if (tp->pass_count)
13002     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13003 }
13004
13005 static void
13006 tracepoint_create_sals_from_location (const struct event_location *location,
13007                                       struct linespec_result *canonical,
13008                                       enum bptype type_wanted)
13009 {
13010   create_sals_from_location_default (location, canonical, type_wanted);
13011 }
13012
13013 static void
13014 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13015                                    struct linespec_result *canonical,
13016                                    gdb::unique_xmalloc_ptr<char> cond_string,
13017                                    gdb::unique_xmalloc_ptr<char> extra_string,
13018                                    enum bptype type_wanted,
13019                                    enum bpdisp disposition,
13020                                    int thread,
13021                                    int task, int ignore_count,
13022                                    const struct breakpoint_ops *ops,
13023                                    int from_tty, int enabled,
13024                                    int internal, unsigned flags)
13025 {
13026   create_breakpoints_sal_default (gdbarch, canonical,
13027                                   std::move (cond_string),
13028                                   std::move (extra_string),
13029                                   type_wanted,
13030                                   disposition, thread, task,
13031                                   ignore_count, ops, from_tty,
13032                                   enabled, internal, flags);
13033 }
13034
13035 static std::vector<symtab_and_line>
13036 tracepoint_decode_location (struct breakpoint *b,
13037                             const struct event_location *location,
13038                             struct program_space *search_pspace)
13039 {
13040   return decode_location_default (b, location, search_pspace);
13041 }
13042
13043 struct breakpoint_ops tracepoint_breakpoint_ops;
13044
13045 /* The breakpoint_ops structure to be use on tracepoints placed in a
13046    static probe.  */
13047
13048 static void
13049 tracepoint_probe_create_sals_from_location
13050   (const struct event_location *location,
13051    struct linespec_result *canonical,
13052    enum bptype type_wanted)
13053 {
13054   /* We use the same method for breakpoint on probes.  */
13055   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
13056 }
13057
13058 static std::vector<symtab_and_line>
13059 tracepoint_probe_decode_location (struct breakpoint *b,
13060                                   const struct event_location *location,
13061                                   struct program_space *search_pspace)
13062 {
13063   /* We use the same method for breakpoint on probes.  */
13064   return bkpt_probe_decode_location (b, location, search_pspace);
13065 }
13066
13067 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13068
13069 /* Dprintf breakpoint_ops methods.  */
13070
13071 static void
13072 dprintf_re_set (struct breakpoint *b)
13073 {
13074   breakpoint_re_set_default (b);
13075
13076   /* extra_string should never be non-NULL for dprintf.  */
13077   gdb_assert (b->extra_string != NULL);
13078
13079   /* 1 - connect to target 1, that can run breakpoint commands.
13080      2 - create a dprintf, which resolves fine.
13081      3 - disconnect from target 1
13082      4 - connect to target 2, that can NOT run breakpoint commands.
13083
13084      After steps #3/#4, you'll want the dprintf command list to
13085      be updated, because target 1 and 2 may well return different
13086      answers for target_can_run_breakpoint_commands().
13087      Given absence of finer grained resetting, we get to do
13088      it all the time.  */
13089   if (b->extra_string != NULL)
13090     update_dprintf_command_list (b);
13091 }
13092
13093 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13094
13095 static void
13096 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13097 {
13098   fprintf_unfiltered (fp, "dprintf %s,%s",
13099                       event_location_to_string (tp->location.get ()),
13100                       tp->extra_string);
13101   print_recreate_thread (tp, fp);
13102 }
13103
13104 /* Implement the "after_condition_true" breakpoint_ops method for
13105    dprintf.
13106
13107    dprintf's are implemented with regular commands in their command
13108    list, but we run the commands here instead of before presenting the
13109    stop to the user, as dprintf's don't actually cause a stop.  This
13110    also makes it so that the commands of multiple dprintfs at the same
13111    address are all handled.  */
13112
13113 static void
13114 dprintf_after_condition_true (struct bpstats *bs)
13115 {
13116   struct bpstats tmp_bs;
13117   struct bpstats *tmp_bs_p = &tmp_bs;
13118
13119   /* dprintf's never cause a stop.  This wasn't set in the
13120      check_status hook instead because that would make the dprintf's
13121      condition not be evaluated.  */
13122   bs->stop = 0;
13123
13124   /* Run the command list here.  Take ownership of it instead of
13125      copying.  We never want these commands to run later in
13126      bpstat_do_actions, if a breakpoint that causes a stop happens to
13127      be set at same address as this dprintf, or even if running the
13128      commands here throws.  */
13129   tmp_bs.commands = bs->commands;
13130   bs->commands = NULL;
13131
13132   bpstat_do_actions_1 (&tmp_bs_p);
13133
13134   /* 'tmp_bs.commands' will usually be NULL by now, but
13135      bpstat_do_actions_1 may return early without processing the whole
13136      list.  */
13137 }
13138
13139 /* The breakpoint_ops structure to be used on static tracepoints with
13140    markers (`-m').  */
13141
13142 static void
13143 strace_marker_create_sals_from_location (const struct event_location *location,
13144                                          struct linespec_result *canonical,
13145                                          enum bptype type_wanted)
13146 {
13147   struct linespec_sals lsal;
13148   const char *arg_start, *arg;
13149
13150   arg = arg_start = get_linespec_location (location);
13151   lsal.sals = decode_static_tracepoint_spec (&arg);
13152
13153   std::string str (arg_start, arg - arg_start);
13154   const char *ptr = str.c_str ();
13155   canonical->location = new_linespec_location (&ptr);
13156
13157   lsal.canonical
13158     = xstrdup (event_location_to_string (canonical->location.get ()));
13159   canonical->lsals.push_back (std::move (lsal));
13160 }
13161
13162 static void
13163 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13164                                       struct linespec_result *canonical,
13165                                       gdb::unique_xmalloc_ptr<char> cond_string,
13166                                       gdb::unique_xmalloc_ptr<char> extra_string,
13167                                       enum bptype type_wanted,
13168                                       enum bpdisp disposition,
13169                                       int thread,
13170                                       int task, int ignore_count,
13171                                       const struct breakpoint_ops *ops,
13172                                       int from_tty, int enabled,
13173                                       int internal, unsigned flags)
13174 {
13175   const linespec_sals &lsal = canonical->lsals[0];
13176
13177   /* If the user is creating a static tracepoint by marker id
13178      (strace -m MARKER_ID), then store the sals index, so that
13179      breakpoint_re_set can try to match up which of the newly
13180      found markers corresponds to this one, and, don't try to
13181      expand multiple locations for each sal, given than SALS
13182      already should contain all sals for MARKER_ID.  */
13183
13184   for (size_t i = 0; i < lsal.sals.size (); i++)
13185     {
13186       event_location_up location
13187         = copy_event_location (canonical->location.get ());
13188
13189       std::unique_ptr<tracepoint> tp (new tracepoint ());
13190       init_breakpoint_sal (tp.get (), gdbarch, lsal.sals[i],
13191                            std::move (location), NULL,
13192                            std::move (cond_string),
13193                            std::move (extra_string),
13194                            type_wanted, disposition,
13195                            thread, task, ignore_count, ops,
13196                            from_tty, enabled, internal, flags,
13197                            canonical->special_display);
13198       /* Given that its possible to have multiple markers with
13199          the same string id, if the user is creating a static
13200          tracepoint by marker id ("strace -m MARKER_ID"), then
13201          store the sals index, so that breakpoint_re_set can
13202          try to match up which of the newly found markers
13203          corresponds to this one  */
13204       tp->static_trace_marker_id_idx = i;
13205
13206       install_breakpoint (internal, std::move (tp), 0);
13207     }
13208 }
13209
13210 static std::vector<symtab_and_line>
13211 strace_marker_decode_location (struct breakpoint *b,
13212                                const struct event_location *location,
13213                                struct program_space *search_pspace)
13214 {
13215   struct tracepoint *tp = (struct tracepoint *) b;
13216   const char *s = get_linespec_location (location);
13217
13218   std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
13219   if (sals.size () > tp->static_trace_marker_id_idx)
13220     {
13221       sals[0] = sals[tp->static_trace_marker_id_idx];
13222       sals.resize (1);
13223       return sals;
13224     }
13225   else
13226     error (_("marker %s not found"), tp->static_trace_marker_id);
13227 }
13228
13229 static struct breakpoint_ops strace_marker_breakpoint_ops;
13230
13231 static int
13232 strace_marker_p (struct breakpoint *b)
13233 {
13234   return b->ops == &strace_marker_breakpoint_ops;
13235 }
13236
13237 /* Delete a breakpoint and clean up all traces of it in the data
13238    structures.  */
13239
13240 void
13241 delete_breakpoint (struct breakpoint *bpt)
13242 {
13243   struct breakpoint *b;
13244
13245   gdb_assert (bpt != NULL);
13246
13247   /* Has this bp already been deleted?  This can happen because
13248      multiple lists can hold pointers to bp's.  bpstat lists are
13249      especial culprits.
13250
13251      One example of this happening is a watchpoint's scope bp.  When
13252      the scope bp triggers, we notice that the watchpoint is out of
13253      scope, and delete it.  We also delete its scope bp.  But the
13254      scope bp is marked "auto-deleting", and is already on a bpstat.
13255      That bpstat is then checked for auto-deleting bp's, which are
13256      deleted.
13257
13258      A real solution to this problem might involve reference counts in
13259      bp's, and/or giving them pointers back to their referencing
13260      bpstat's, and teaching delete_breakpoint to only free a bp's
13261      storage when no more references were extent.  A cheaper bandaid
13262      was chosen.  */
13263   if (bpt->type == bp_none)
13264     return;
13265
13266   /* At least avoid this stale reference until the reference counting
13267      of breakpoints gets resolved.  */
13268   if (bpt->related_breakpoint != bpt)
13269     {
13270       struct breakpoint *related;
13271       struct watchpoint *w;
13272
13273       if (bpt->type == bp_watchpoint_scope)
13274         w = (struct watchpoint *) bpt->related_breakpoint;
13275       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13276         w = (struct watchpoint *) bpt;
13277       else
13278         w = NULL;
13279       if (w != NULL)
13280         watchpoint_del_at_next_stop (w);
13281
13282       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13283       for (related = bpt; related->related_breakpoint != bpt;
13284            related = related->related_breakpoint);
13285       related->related_breakpoint = bpt->related_breakpoint;
13286       bpt->related_breakpoint = bpt;
13287     }
13288
13289   /* watch_command_1 creates a watchpoint but only sets its number if
13290      update_watchpoint succeeds in creating its bp_locations.  If there's
13291      a problem in that process, we'll be asked to delete the half-created
13292      watchpoint.  In that case, don't announce the deletion.  */
13293   if (bpt->number)
13294     observer_notify_breakpoint_deleted (bpt);
13295
13296   if (breakpoint_chain == bpt)
13297     breakpoint_chain = bpt->next;
13298
13299   ALL_BREAKPOINTS (b)
13300     if (b->next == bpt)
13301     {
13302       b->next = bpt->next;
13303       break;
13304     }
13305
13306   /* Be sure no bpstat's are pointing at the breakpoint after it's
13307      been freed.  */
13308   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13309      in all threads for now.  Note that we cannot just remove bpstats
13310      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13311      commands are associated with the bpstat; if we remove it here,
13312      then the later call to bpstat_do_actions (&stop_bpstat); in
13313      event-top.c won't do anything, and temporary breakpoints with
13314      commands won't work.  */
13315
13316   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13317
13318   /* Now that breakpoint is removed from breakpoint list, update the
13319      global location list.  This will remove locations that used to
13320      belong to this breakpoint.  Do this before freeing the breakpoint
13321      itself, since remove_breakpoint looks at location's owner.  It
13322      might be better design to have location completely
13323      self-contained, but it's not the case now.  */
13324   update_global_location_list (UGLL_DONT_INSERT);
13325
13326   /* On the chance that someone will soon try again to delete this
13327      same bp, we mark it as deleted before freeing its storage.  */
13328   bpt->type = bp_none;
13329   delete bpt;
13330 }
13331
13332 /* Iterator function to call a user-provided callback function once
13333    for each of B and its related breakpoints.  */
13334
13335 static void
13336 iterate_over_related_breakpoints (struct breakpoint *b,
13337                                   gdb::function_view<void (breakpoint *)> function)
13338 {
13339   struct breakpoint *related;
13340
13341   related = b;
13342   do
13343     {
13344       struct breakpoint *next;
13345
13346       /* FUNCTION may delete RELATED.  */
13347       next = related->related_breakpoint;
13348
13349       if (next == related)
13350         {
13351           /* RELATED is the last ring entry.  */
13352           function (related);
13353
13354           /* FUNCTION may have deleted it, so we'd never reach back to
13355              B.  There's nothing left to do anyway, so just break
13356              out.  */
13357           break;
13358         }
13359       else
13360         function (related);
13361
13362       related = next;
13363     }
13364   while (related != b);
13365 }
13366
13367 static void
13368 delete_command (const char *arg, int from_tty)
13369 {
13370   struct breakpoint *b, *b_tmp;
13371
13372   dont_repeat ();
13373
13374   if (arg == 0)
13375     {
13376       int breaks_to_delete = 0;
13377
13378       /* Delete all breakpoints if no argument.  Do not delete
13379          internal breakpoints, these have to be deleted with an
13380          explicit breakpoint number argument.  */
13381       ALL_BREAKPOINTS (b)
13382         if (user_breakpoint_p (b))
13383           {
13384             breaks_to_delete = 1;
13385             break;
13386           }
13387
13388       /* Ask user only if there are some breakpoints to delete.  */
13389       if (!from_tty
13390           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13391         {
13392           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13393             if (user_breakpoint_p (b))
13394               delete_breakpoint (b);
13395         }
13396     }
13397   else
13398     map_breakpoint_numbers
13399       (arg, [&] (breakpoint *b)
13400        {
13401          iterate_over_related_breakpoints (b, delete_breakpoint);
13402        });
13403 }
13404
13405 /* Return true if all locations of B bound to PSPACE are pending.  If
13406    PSPACE is NULL, all locations of all program spaces are
13407    considered.  */
13408
13409 static int
13410 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13411 {
13412   struct bp_location *loc;
13413
13414   for (loc = b->loc; loc != NULL; loc = loc->next)
13415     if ((pspace == NULL
13416          || loc->pspace == pspace)
13417         && !loc->shlib_disabled
13418         && !loc->pspace->executing_startup)
13419       return 0;
13420   return 1;
13421 }
13422
13423 /* Subroutine of update_breakpoint_locations to simplify it.
13424    Return non-zero if multiple fns in list LOC have the same name.
13425    Null names are ignored.  */
13426
13427 static int
13428 ambiguous_names_p (struct bp_location *loc)
13429 {
13430   struct bp_location *l;
13431   htab_t htab = htab_create_alloc (13, htab_hash_string,
13432                                    (int (*) (const void *, 
13433                                              const void *)) streq,
13434                                    NULL, xcalloc, xfree);
13435
13436   for (l = loc; l != NULL; l = l->next)
13437     {
13438       const char **slot;
13439       const char *name = l->function_name;
13440
13441       /* Allow for some names to be NULL, ignore them.  */
13442       if (name == NULL)
13443         continue;
13444
13445       slot = (const char **) htab_find_slot (htab, (const void *) name,
13446                                              INSERT);
13447       /* NOTE: We can assume slot != NULL here because xcalloc never
13448          returns NULL.  */
13449       if (*slot != NULL)
13450         {
13451           htab_delete (htab);
13452           return 1;
13453         }
13454       *slot = name;
13455     }
13456
13457   htab_delete (htab);
13458   return 0;
13459 }
13460
13461 /* When symbols change, it probably means the sources changed as well,
13462    and it might mean the static tracepoint markers are no longer at
13463    the same address or line numbers they used to be at last we
13464    checked.  Losing your static tracepoints whenever you rebuild is
13465    undesirable.  This function tries to resync/rematch gdb static
13466    tracepoints with the markers on the target, for static tracepoints
13467    that have not been set by marker id.  Static tracepoint that have
13468    been set by marker id are reset by marker id in breakpoint_re_set.
13469    The heuristic is:
13470
13471    1) For a tracepoint set at a specific address, look for a marker at
13472    the old PC.  If one is found there, assume to be the same marker.
13473    If the name / string id of the marker found is different from the
13474    previous known name, assume that means the user renamed the marker
13475    in the sources, and output a warning.
13476
13477    2) For a tracepoint set at a given line number, look for a marker
13478    at the new address of the old line number.  If one is found there,
13479    assume to be the same marker.  If the name / string id of the
13480    marker found is different from the previous known name, assume that
13481    means the user renamed the marker in the sources, and output a
13482    warning.
13483
13484    3) If a marker is no longer found at the same address or line, it
13485    may mean the marker no longer exists.  But it may also just mean
13486    the code changed a bit.  Maybe the user added a few lines of code
13487    that made the marker move up or down (in line number terms).  Ask
13488    the target for info about the marker with the string id as we knew
13489    it.  If found, update line number and address in the matching
13490    static tracepoint.  This will get confused if there's more than one
13491    marker with the same ID (possible in UST, although unadvised
13492    precisely because it confuses tools).  */
13493
13494 static struct symtab_and_line
13495 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13496 {
13497   struct tracepoint *tp = (struct tracepoint *) b;
13498   struct static_tracepoint_marker marker;
13499   CORE_ADDR pc;
13500
13501   pc = sal.pc;
13502   if (sal.line)
13503     find_line_pc (sal.symtab, sal.line, &pc);
13504
13505   if (target_static_tracepoint_marker_at (pc, &marker))
13506     {
13507       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13508         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13509                  b->number,
13510                  tp->static_trace_marker_id, marker.str_id);
13511
13512       xfree (tp->static_trace_marker_id);
13513       tp->static_trace_marker_id = xstrdup (marker.str_id);
13514       release_static_tracepoint_marker (&marker);
13515
13516       return sal;
13517     }
13518
13519   /* Old marker wasn't found on target at lineno.  Try looking it up
13520      by string ID.  */
13521   if (!sal.explicit_pc
13522       && sal.line != 0
13523       && sal.symtab != NULL
13524       && tp->static_trace_marker_id != NULL)
13525     {
13526       VEC(static_tracepoint_marker_p) *markers;
13527
13528       markers
13529         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13530
13531       if (!VEC_empty(static_tracepoint_marker_p, markers))
13532         {
13533           struct symbol *sym;
13534           struct static_tracepoint_marker *tpmarker;
13535           struct ui_out *uiout = current_uiout;
13536           struct explicit_location explicit_loc;
13537
13538           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13539
13540           xfree (tp->static_trace_marker_id);
13541           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13542
13543           warning (_("marker for static tracepoint %d (%s) not "
13544                      "found at previous line number"),
13545                    b->number, tp->static_trace_marker_id);
13546
13547           symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
13548           sym = find_pc_sect_function (tpmarker->address, NULL);
13549           uiout->text ("Now in ");
13550           if (sym)
13551             {
13552               uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
13553               uiout->text (" at ");
13554             }
13555           uiout->field_string ("file",
13556                                symtab_to_filename_for_display (sal2.symtab));
13557           uiout->text (":");
13558
13559           if (uiout->is_mi_like_p ())
13560             {
13561               const char *fullname = symtab_to_fullname (sal2.symtab);
13562
13563               uiout->field_string ("fullname", fullname);
13564             }
13565
13566           uiout->field_int ("line", sal2.line);
13567           uiout->text ("\n");
13568
13569           b->loc->line_number = sal2.line;
13570           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13571
13572           b->location.reset (NULL);
13573           initialize_explicit_location (&explicit_loc);
13574           explicit_loc.source_filename
13575             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
13576           explicit_loc.line_offset.offset = b->loc->line_number;
13577           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
13578           b->location = new_explicit_location (&explicit_loc);
13579
13580           /* Might be nice to check if function changed, and warn if
13581              so.  */
13582
13583           release_static_tracepoint_marker (tpmarker);
13584         }
13585     }
13586   return sal;
13587 }
13588
13589 /* Returns 1 iff locations A and B are sufficiently same that
13590    we don't need to report breakpoint as changed.  */
13591
13592 static int
13593 locations_are_equal (struct bp_location *a, struct bp_location *b)
13594 {
13595   while (a && b)
13596     {
13597       if (a->address != b->address)
13598         return 0;
13599
13600       if (a->shlib_disabled != b->shlib_disabled)
13601         return 0;
13602
13603       if (a->enabled != b->enabled)
13604         return 0;
13605
13606       a = a->next;
13607       b = b->next;
13608     }
13609
13610   if ((a == NULL) != (b == NULL))
13611     return 0;
13612
13613   return 1;
13614 }
13615
13616 /* Split all locations of B that are bound to PSPACE out of B's
13617    location list to a separate list and return that list's head.  If
13618    PSPACE is NULL, hoist out all locations of B.  */
13619
13620 static struct bp_location *
13621 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
13622 {
13623   struct bp_location head;
13624   struct bp_location *i = b->loc;
13625   struct bp_location **i_link = &b->loc;
13626   struct bp_location *hoisted = &head;
13627
13628   if (pspace == NULL)
13629     {
13630       i = b->loc;
13631       b->loc = NULL;
13632       return i;
13633     }
13634
13635   head.next = NULL;
13636
13637   while (i != NULL)
13638     {
13639       if (i->pspace == pspace)
13640         {
13641           *i_link = i->next;
13642           i->next = NULL;
13643           hoisted->next = i;
13644           hoisted = i;
13645         }
13646       else
13647         i_link = &i->next;
13648       i = *i_link;
13649     }
13650
13651   return head.next;
13652 }
13653
13654 /* Create new breakpoint locations for B (a hardware or software
13655    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
13656    zero, then B is a ranged breakpoint.  Only recreates locations for
13657    FILTER_PSPACE.  Locations of other program spaces are left
13658    untouched.  */
13659
13660 void
13661 update_breakpoint_locations (struct breakpoint *b,
13662                              struct program_space *filter_pspace,
13663                              gdb::array_view<const symtab_and_line> sals,
13664                              gdb::array_view<const symtab_and_line> sals_end)
13665 {
13666   int i;
13667   struct bp_location *existing_locations;
13668
13669   if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
13670     {
13671       /* Ranged breakpoints have only one start location and one end
13672          location.  */
13673       b->enable_state = bp_disabled;
13674       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13675                            "multiple locations found\n"),
13676                          b->number);
13677       return;
13678     }
13679
13680   /* If there's no new locations, and all existing locations are
13681      pending, don't do anything.  This optimizes the common case where
13682      all locations are in the same shared library, that was unloaded.
13683      We'd like to retain the location, so that when the library is
13684      loaded again, we don't loose the enabled/disabled status of the
13685      individual locations.  */
13686   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
13687     return;
13688
13689   existing_locations = hoist_existing_locations (b, filter_pspace);
13690
13691   for (const auto &sal : sals)
13692     {
13693       struct bp_location *new_loc;
13694
13695       switch_to_program_space_and_thread (sal.pspace);
13696
13697       new_loc = add_location_to_breakpoint (b, &sal);
13698
13699       /* Reparse conditions, they might contain references to the
13700          old symtab.  */
13701       if (b->cond_string != NULL)
13702         {
13703           const char *s;
13704
13705           s = b->cond_string;
13706           TRY
13707             {
13708               new_loc->cond = parse_exp_1 (&s, sal.pc,
13709                                            block_for_pc (sal.pc),
13710                                            0);
13711             }
13712           CATCH (e, RETURN_MASK_ERROR)
13713             {
13714               warning (_("failed to reevaluate condition "
13715                          "for breakpoint %d: %s"), 
13716                        b->number, e.message);
13717               new_loc->enabled = 0;
13718             }
13719           END_CATCH
13720         }
13721
13722       if (!sals_end.empty ())
13723         {
13724           CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13725
13726           new_loc->length = end - sals[0].pc + 1;
13727         }
13728     }
13729
13730   /* If possible, carry over 'disable' status from existing
13731      breakpoints.  */
13732   {
13733     struct bp_location *e = existing_locations;
13734     /* If there are multiple breakpoints with the same function name,
13735        e.g. for inline functions, comparing function names won't work.
13736        Instead compare pc addresses; this is just a heuristic as things
13737        may have moved, but in practice it gives the correct answer
13738        often enough until a better solution is found.  */
13739     int have_ambiguous_names = ambiguous_names_p (b->loc);
13740
13741     for (; e; e = e->next)
13742       {
13743         if (!e->enabled && e->function_name)
13744           {
13745             struct bp_location *l = b->loc;
13746             if (have_ambiguous_names)
13747               {
13748                 for (; l; l = l->next)
13749                   if (breakpoint_locations_match (e, l))
13750                     {
13751                       l->enabled = 0;
13752                       break;
13753                     }
13754               }
13755             else
13756               {
13757                 for (; l; l = l->next)
13758                   if (l->function_name
13759                       && strcmp (e->function_name, l->function_name) == 0)
13760                     {
13761                       l->enabled = 0;
13762                       break;
13763                     }
13764               }
13765           }
13766       }
13767   }
13768
13769   if (!locations_are_equal (existing_locations, b->loc))
13770     observer_notify_breakpoint_modified (b);
13771 }
13772
13773 /* Find the SaL locations corresponding to the given LOCATION.
13774    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13775
13776 static std::vector<symtab_and_line>
13777 location_to_sals (struct breakpoint *b, struct event_location *location,
13778                   struct program_space *search_pspace, int *found)
13779 {
13780   struct gdb_exception exception = exception_none;
13781
13782   gdb_assert (b->ops != NULL);
13783
13784   std::vector<symtab_and_line> sals;
13785
13786   TRY
13787     {
13788       sals = b->ops->decode_location (b, location, search_pspace);
13789     }
13790   CATCH (e, RETURN_MASK_ERROR)
13791     {
13792       int not_found_and_ok = 0;
13793
13794       exception = e;
13795
13796       /* For pending breakpoints, it's expected that parsing will
13797          fail until the right shared library is loaded.  User has
13798          already told to create pending breakpoints and don't need
13799          extra messages.  If breakpoint is in bp_shlib_disabled
13800          state, then user already saw the message about that
13801          breakpoint being disabled, and don't want to see more
13802          errors.  */
13803       if (e.error == NOT_FOUND_ERROR
13804           && (b->condition_not_parsed
13805               || (b->loc != NULL
13806                   && search_pspace != NULL
13807                   && b->loc->pspace != search_pspace)
13808               || (b->loc && b->loc->shlib_disabled)
13809               || (b->loc && b->loc->pspace->executing_startup)
13810               || b->enable_state == bp_disabled))
13811         not_found_and_ok = 1;
13812
13813       if (!not_found_and_ok)
13814         {
13815           /* We surely don't want to warn about the same breakpoint
13816              10 times.  One solution, implemented here, is disable
13817              the breakpoint on error.  Another solution would be to
13818              have separate 'warning emitted' flag.  Since this
13819              happens only when a binary has changed, I don't know
13820              which approach is better.  */
13821           b->enable_state = bp_disabled;
13822           throw_exception (e);
13823         }
13824     }
13825   END_CATCH
13826
13827   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13828     {
13829       for (auto &sal : sals)
13830         resolve_sal_pc (&sal);
13831       if (b->condition_not_parsed && b->extra_string != NULL)
13832         {
13833           char *cond_string, *extra_string;
13834           int thread, task;
13835
13836           find_condition_and_thread (b->extra_string, sals[0].pc,
13837                                      &cond_string, &thread, &task,
13838                                      &extra_string);
13839           gdb_assert (b->cond_string == NULL);
13840           if (cond_string)
13841             b->cond_string = cond_string;
13842           b->thread = thread;
13843           b->task = task;
13844           if (extra_string)
13845             {
13846               xfree (b->extra_string);
13847               b->extra_string = extra_string;
13848             }
13849           b->condition_not_parsed = 0;
13850         }
13851
13852       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13853         sals[0] = update_static_tracepoint (b, sals[0]);
13854
13855       *found = 1;
13856     }
13857   else
13858     *found = 0;
13859
13860   return sals;
13861 }
13862
13863 /* The default re_set method, for typical hardware or software
13864    breakpoints.  Reevaluate the breakpoint and recreate its
13865    locations.  */
13866
13867 static void
13868 breakpoint_re_set_default (struct breakpoint *b)
13869 {
13870   struct program_space *filter_pspace = current_program_space;
13871   std::vector<symtab_and_line> expanded, expanded_end;
13872
13873   int found;
13874   std::vector<symtab_and_line> sals = location_to_sals (b, b->location.get (),
13875                                                         filter_pspace, &found);
13876   if (found)
13877     expanded = std::move (sals);
13878
13879   if (b->location_range_end != NULL)
13880     {
13881       std::vector<symtab_and_line> sals_end
13882         = location_to_sals (b, b->location_range_end.get (),
13883                             filter_pspace, &found);
13884       if (found)
13885         expanded_end = std::move (sals_end);
13886     }
13887
13888   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
13889 }
13890
13891 /* Default method for creating SALs from an address string.  It basically
13892    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13893
13894 static void
13895 create_sals_from_location_default (const struct event_location *location,
13896                                    struct linespec_result *canonical,
13897                                    enum bptype type_wanted)
13898 {
13899   parse_breakpoint_sals (location, canonical);
13900 }
13901
13902 /* Call create_breakpoints_sal for the given arguments.  This is the default
13903    function for the `create_breakpoints_sal' method of
13904    breakpoint_ops.  */
13905
13906 static void
13907 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13908                                 struct linespec_result *canonical,
13909                                 gdb::unique_xmalloc_ptr<char> cond_string,
13910                                 gdb::unique_xmalloc_ptr<char> extra_string,
13911                                 enum bptype type_wanted,
13912                                 enum bpdisp disposition,
13913                                 int thread,
13914                                 int task, int ignore_count,
13915                                 const struct breakpoint_ops *ops,
13916                                 int from_tty, int enabled,
13917                                 int internal, unsigned flags)
13918 {
13919   create_breakpoints_sal (gdbarch, canonical,
13920                           std::move (cond_string),
13921                           std::move (extra_string),
13922                           type_wanted, disposition,
13923                           thread, task, ignore_count, ops, from_tty,
13924                           enabled, internal, flags);
13925 }
13926
13927 /* Decode the line represented by S by calling decode_line_full.  This is the
13928    default function for the `decode_location' method of breakpoint_ops.  */
13929
13930 static std::vector<symtab_and_line>
13931 decode_location_default (struct breakpoint *b,
13932                          const struct event_location *location,
13933                          struct program_space *search_pspace)
13934 {
13935   struct linespec_result canonical;
13936
13937   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
13938                     (struct symtab *) NULL, 0,
13939                     &canonical, multiple_symbols_all,
13940                     b->filter);
13941
13942   /* We should get 0 or 1 resulting SALs.  */
13943   gdb_assert (canonical.lsals.size () < 2);
13944
13945   if (!canonical.lsals.empty ())
13946     {
13947       const linespec_sals &lsal = canonical.lsals[0];
13948       return std::move (lsal.sals);
13949     }
13950   return {};
13951 }
13952
13953 /* Reset a breakpoint.  */
13954
13955 static void
13956 breakpoint_re_set_one (breakpoint *b)
13957 {
13958   input_radix = b->input_radix;
13959   set_language (b->language);
13960
13961   b->ops->re_set (b);
13962 }
13963
13964 /* Re-set breakpoint locations for the current program space.
13965    Locations bound to other program spaces are left untouched.  */
13966
13967 void
13968 breakpoint_re_set (void)
13969 {
13970   struct breakpoint *b, *b_tmp;
13971
13972   {
13973     scoped_restore_current_language save_language;
13974     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
13975     scoped_restore_current_pspace_and_thread restore_pspace_thread;
13976
13977     /* Note: we must not try to insert locations until after all
13978        breakpoints have been re-set.  Otherwise, e.g., when re-setting
13979        breakpoint 1, we'd insert the locations of breakpoint 2, which
13980        hadn't been re-set yet, and thus may have stale locations.  */
13981
13982     ALL_BREAKPOINTS_SAFE (b, b_tmp)
13983       {
13984         TRY
13985           {
13986             breakpoint_re_set_one (b);
13987           }
13988         CATCH (ex, RETURN_MASK_ALL)
13989           {
13990             exception_fprintf (gdb_stderr, ex,
13991                                "Error in re-setting breakpoint %d: ",
13992                                b->number);
13993           }
13994         END_CATCH
13995       }
13996
13997     jit_breakpoint_re_set ();
13998   }
13999
14000   create_overlay_event_breakpoint ();
14001   create_longjmp_master_breakpoint ();
14002   create_std_terminate_master_breakpoint ();
14003   create_exception_master_breakpoint ();
14004
14005   /* Now we can insert.  */
14006   update_global_location_list (UGLL_MAY_INSERT);
14007 }
14008 \f
14009 /* Reset the thread number of this breakpoint:
14010
14011    - If the breakpoint is for all threads, leave it as-is.
14012    - Else, reset it to the current thread for inferior_ptid.  */
14013 void
14014 breakpoint_re_set_thread (struct breakpoint *b)
14015 {
14016   if (b->thread != -1)
14017     {
14018       if (in_thread_list (inferior_ptid))
14019         b->thread = ptid_to_global_thread_id (inferior_ptid);
14020
14021       /* We're being called after following a fork.  The new fork is
14022          selected as current, and unless this was a vfork will have a
14023          different program space from the original thread.  Reset that
14024          as well.  */
14025       b->loc->pspace = current_program_space;
14026     }
14027 }
14028
14029 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14030    If from_tty is nonzero, it prints a message to that effect,
14031    which ends with a period (no newline).  */
14032
14033 void
14034 set_ignore_count (int bptnum, int count, int from_tty)
14035 {
14036   struct breakpoint *b;
14037
14038   if (count < 0)
14039     count = 0;
14040
14041   ALL_BREAKPOINTS (b)
14042     if (b->number == bptnum)
14043     {
14044       if (is_tracepoint (b))
14045         {
14046           if (from_tty && count != 0)
14047             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14048                              bptnum);
14049           return;
14050         }
14051       
14052       b->ignore_count = count;
14053       if (from_tty)
14054         {
14055           if (count == 0)
14056             printf_filtered (_("Will stop next time "
14057                                "breakpoint %d is reached."),
14058                              bptnum);
14059           else if (count == 1)
14060             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14061                              bptnum);
14062           else
14063             printf_filtered (_("Will ignore next %d "
14064                                "crossings of breakpoint %d."),
14065                              count, bptnum);
14066         }
14067       observer_notify_breakpoint_modified (b);
14068       return;
14069     }
14070
14071   error (_("No breakpoint number %d."), bptnum);
14072 }
14073
14074 /* Command to set ignore-count of breakpoint N to COUNT.  */
14075
14076 static void
14077 ignore_command (const char *args, int from_tty)
14078 {
14079   const char *p = args;
14080   int num;
14081
14082   if (p == 0)
14083     error_no_arg (_("a breakpoint number"));
14084
14085   num = get_number (&p);
14086   if (num == 0)
14087     error (_("bad breakpoint number: '%s'"), args);
14088   if (*p == 0)
14089     error (_("Second argument (specified ignore-count) is missing."));
14090
14091   set_ignore_count (num,
14092                     longest_to_int (value_as_long (parse_and_eval (p))),
14093                     from_tty);
14094   if (from_tty)
14095     printf_filtered ("\n");
14096 }
14097 \f
14098
14099 /* Call FUNCTION on each of the breakpoints with numbers in the range
14100    defined by BP_NUM_RANGE (an inclusive range).  */
14101
14102 static void
14103 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
14104                              gdb::function_view<void (breakpoint *)> function)
14105 {
14106   if (bp_num_range.first == 0)
14107     {
14108       warning (_("bad breakpoint number at or near '%d'"),
14109                bp_num_range.first);
14110     }
14111   else
14112     {
14113       struct breakpoint *b, *tmp;
14114
14115       for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
14116         {
14117           bool match = false;
14118
14119           ALL_BREAKPOINTS_SAFE (b, tmp)
14120             if (b->number == i)
14121               {
14122                 match = true;
14123                 function (b);
14124                 break;
14125               }
14126           if (!match)
14127             printf_unfiltered (_("No breakpoint number %d.\n"), i);
14128         }
14129     }
14130 }
14131
14132 /* Call FUNCTION on each of the breakpoints whose numbers are given in
14133    ARGS.  */
14134
14135 static void
14136 map_breakpoint_numbers (const char *args,
14137                         gdb::function_view<void (breakpoint *)> function)
14138 {
14139   if (args == NULL || *args == '\0')
14140     error_no_arg (_("one or more breakpoint numbers"));
14141
14142   number_or_range_parser parser (args);
14143
14144   while (!parser.finished ())
14145     {
14146       int num = parser.get_number ();
14147       map_breakpoint_number_range (std::make_pair (num, num), function);
14148     }
14149 }
14150
14151 /* Return the breakpoint location structure corresponding to the
14152    BP_NUM and LOC_NUM values.  */
14153
14154 static struct bp_location *
14155 find_location_by_number (int bp_num, int loc_num)
14156 {
14157   struct breakpoint *b;
14158
14159   ALL_BREAKPOINTS (b)
14160     if (b->number == bp_num)
14161       {
14162         break;
14163       }
14164
14165   if (!b || b->number != bp_num)
14166     error (_("Bad breakpoint number '%d'"), bp_num);
14167   
14168   if (loc_num == 0)
14169     error (_("Bad breakpoint location number '%d'"), loc_num);
14170
14171   int n = 0;
14172   for (bp_location *loc = b->loc; loc != NULL; loc = loc->next)
14173     if (++n == loc_num)
14174       return loc;
14175
14176   error (_("Bad breakpoint location number '%d'"), loc_num);
14177 }
14178
14179 /* Modes of operation for extract_bp_num.  */
14180 enum class extract_bp_kind
14181 {
14182   /* Extracting a breakpoint number.  */
14183   bp,
14184
14185   /* Extracting a location number.  */
14186   loc,
14187 };
14188
14189 /* Extract a breakpoint or location number (as determined by KIND)
14190    from the string starting at START.  TRAILER is a character which
14191    can be found after the number.  If you don't want a trailer, use
14192    '\0'.  If END_OUT is not NULL, it is set to point after the parsed
14193    string.  This always returns a positive integer.  */
14194
14195 static int
14196 extract_bp_num (extract_bp_kind kind, const char *start,
14197                 int trailer, const char **end_out = NULL)
14198 {
14199   const char *end = start;
14200   int num = get_number_trailer (&end, trailer);
14201   if (num < 0)
14202     error (kind == extract_bp_kind::bp
14203            ? _("Negative breakpoint number '%.*s'")
14204            : _("Negative breakpoint location number '%.*s'"),
14205            int (end - start), start);
14206   if (num == 0)
14207     error (kind == extract_bp_kind::bp
14208            ? _("Bad breakpoint number '%.*s'")
14209            : _("Bad breakpoint location number '%.*s'"),
14210            int (end - start), start);
14211
14212   if (end_out != NULL)
14213     *end_out = end;
14214   return num;
14215 }
14216
14217 /* Extract a breakpoint or location range (as determined by KIND) in
14218    the form NUM1-NUM2 stored at &ARG[arg_offset].  Returns a std::pair
14219    representing the (inclusive) range.  The returned pair's elements
14220    are always positive integers.  */
14221
14222 static std::pair<int, int>
14223 extract_bp_or_bp_range (extract_bp_kind kind,
14224                         const std::string &arg,
14225                         std::string::size_type arg_offset)
14226 {
14227   std::pair<int, int> range;
14228   const char *bp_loc = &arg[arg_offset];
14229   std::string::size_type dash = arg.find ('-', arg_offset);
14230   if (dash != std::string::npos)
14231     {
14232       /* bp_loc is a range (x-z).  */
14233       if (arg.length () == dash + 1)
14234         error (kind == extract_bp_kind::bp
14235                ? _("Bad breakpoint number at or near: '%s'")
14236                : _("Bad breakpoint location number at or near: '%s'"),
14237                bp_loc);
14238
14239       const char *end;
14240       const char *start_first = bp_loc;
14241       const char *start_second = &arg[dash + 1];
14242       range.first = extract_bp_num (kind, start_first, '-');
14243       range.second = extract_bp_num (kind, start_second, '\0', &end);
14244
14245       if (range.first > range.second)
14246         error (kind == extract_bp_kind::bp
14247                ? _("Inverted breakpoint range at '%.*s'")
14248                : _("Inverted breakpoint location range at '%.*s'"),
14249                int (end - start_first), start_first);
14250     }
14251   else
14252     {
14253       /* bp_loc is a single value.  */
14254       range.first = extract_bp_num (kind, bp_loc, '\0');
14255       range.second = range.first;
14256     }
14257   return range;
14258 }
14259
14260 /* Extract the breakpoint/location range specified by ARG.  Returns
14261    the breakpoint range in BP_NUM_RANGE, and the location range in
14262    BP_LOC_RANGE.
14263
14264    ARG may be in any of the following forms:
14265
14266    x     where 'x' is a breakpoint number.
14267    x-y   where 'x' and 'y' specify a breakpoint numbers range.
14268    x.y   where 'x' is a breakpoint number and 'y' a location number.
14269    x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
14270          location number range.
14271 */
14272
14273 static void
14274 extract_bp_number_and_location (const std::string &arg,
14275                                 std::pair<int, int> &bp_num_range,
14276                                 std::pair<int, int> &bp_loc_range)
14277 {
14278   std::string::size_type dot = arg.find ('.');
14279
14280   if (dot != std::string::npos)
14281     {
14282       /* Handle 'x.y' and 'x.y-z' cases.  */
14283
14284       if (arg.length () == dot + 1 || dot == 0)
14285         error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
14286
14287       bp_num_range.first
14288         = extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
14289       bp_num_range.second = bp_num_range.first;
14290
14291       bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
14292                                              arg, dot + 1);
14293     }
14294   else
14295     {
14296       /* Handle x and x-y cases.  */
14297
14298       bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
14299       bp_loc_range.first = 0;
14300       bp_loc_range.second = 0;
14301     }
14302 }
14303
14304 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM.  ENABLE
14305    specifies whether to enable or disable.  */
14306
14307 static void
14308 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
14309 {
14310   struct bp_location *loc = find_location_by_number (bp_num, loc_num);
14311   if (loc != NULL)
14312     {
14313       if (loc->enabled != enable)
14314         {
14315           loc->enabled = enable;
14316           mark_breakpoint_location_modified (loc);
14317         }
14318       if (target_supports_enable_disable_tracepoint ()
14319           && current_trace_status ()->running && loc->owner
14320           && is_tracepoint (loc->owner))
14321         target_disable_tracepoint (loc);
14322     }
14323   update_global_location_list (UGLL_DONT_INSERT);
14324 }
14325
14326 /* Enable or disable a range of breakpoint locations.  BP_NUM is the
14327    number of the breakpoint, and BP_LOC_RANGE specifies the
14328    (inclusive) range of location numbers of that breakpoint to
14329    enable/disable.  ENABLE specifies whether to enable or disable the
14330    location.  */
14331
14332 static void
14333 enable_disable_breakpoint_location_range (int bp_num,
14334                                           std::pair<int, int> &bp_loc_range,
14335                                           bool enable)
14336 {
14337   for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
14338     enable_disable_bp_num_loc (bp_num, i, enable);
14339 }
14340
14341 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14342    If from_tty is nonzero, it prints a message to that effect,
14343    which ends with a period (no newline).  */
14344
14345 void
14346 disable_breakpoint (struct breakpoint *bpt)
14347 {
14348   /* Never disable a watchpoint scope breakpoint; we want to
14349      hit them when we leave scope so we can delete both the
14350      watchpoint and its scope breakpoint at that time.  */
14351   if (bpt->type == bp_watchpoint_scope)
14352     return;
14353
14354   bpt->enable_state = bp_disabled;
14355
14356   /* Mark breakpoint locations modified.  */
14357   mark_breakpoint_modified (bpt);
14358
14359   if (target_supports_enable_disable_tracepoint ()
14360       && current_trace_status ()->running && is_tracepoint (bpt))
14361     {
14362       struct bp_location *location;
14363      
14364       for (location = bpt->loc; location; location = location->next)
14365         target_disable_tracepoint (location);
14366     }
14367
14368   update_global_location_list (UGLL_DONT_INSERT);
14369
14370   observer_notify_breakpoint_modified (bpt);
14371 }
14372
14373 /* Enable or disable the breakpoint(s) or breakpoint location(s)
14374    specified in ARGS.  ARGS may be in any of the formats handled by
14375    extract_bp_number_and_location.  ENABLE specifies whether to enable
14376    or disable the breakpoints/locations.  */
14377
14378 static void
14379 enable_disable_command (const char *args, int from_tty, bool enable)
14380 {
14381   if (args == 0)
14382     {
14383       struct breakpoint *bpt;
14384
14385       ALL_BREAKPOINTS (bpt)
14386         if (user_breakpoint_p (bpt))
14387           {
14388             if (enable)
14389               enable_breakpoint (bpt);
14390             else
14391               disable_breakpoint (bpt);
14392           }
14393     }
14394   else
14395     {
14396       std::string num = extract_arg (&args);
14397
14398       while (!num.empty ())
14399         {
14400           std::pair<int, int> bp_num_range, bp_loc_range;
14401
14402           extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
14403
14404           if (bp_loc_range.first == bp_loc_range.second
14405               && bp_loc_range.first == 0)
14406             {
14407               /* Handle breakpoint ids with formats 'x' or 'x-z'.  */
14408               map_breakpoint_number_range (bp_num_range,
14409                                            enable
14410                                            ? enable_breakpoint
14411                                            : disable_breakpoint);
14412             }
14413           else
14414             {
14415               /* Handle breakpoint ids with formats 'x.y' or
14416                  'x.y-z'.  */
14417               enable_disable_breakpoint_location_range
14418                 (bp_num_range.first, bp_loc_range, enable);
14419             }
14420           num = extract_arg (&args);
14421         }
14422     }
14423 }
14424
14425 /* The disable command disables the specified breakpoints/locations
14426    (or all defined breakpoints) so they're no longer effective in
14427    stopping the inferior.  ARGS may be in any of the forms defined in
14428    extract_bp_number_and_location.  */
14429
14430 static void
14431 disable_command (const char *args, int from_tty)
14432 {
14433   enable_disable_command (args, from_tty, false);
14434 }
14435
14436 static void
14437 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14438                         int count)
14439 {
14440   int target_resources_ok;
14441
14442   if (bpt->type == bp_hardware_breakpoint)
14443     {
14444       int i;
14445       i = hw_breakpoint_used_count ();
14446       target_resources_ok = 
14447         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14448                                             i + 1, 0);
14449       if (target_resources_ok == 0)
14450         error (_("No hardware breakpoint support in the target."));
14451       else if (target_resources_ok < 0)
14452         error (_("Hardware breakpoints used exceeds limit."));
14453     }
14454
14455   if (is_watchpoint (bpt))
14456     {
14457       /* Initialize it just to avoid a GCC false warning.  */
14458       enum enable_state orig_enable_state = bp_disabled;
14459
14460       TRY
14461         {
14462           struct watchpoint *w = (struct watchpoint *) bpt;
14463
14464           orig_enable_state = bpt->enable_state;
14465           bpt->enable_state = bp_enabled;
14466           update_watchpoint (w, 1 /* reparse */);
14467         }
14468       CATCH (e, RETURN_MASK_ALL)
14469         {
14470           bpt->enable_state = orig_enable_state;
14471           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14472                              bpt->number);
14473           return;
14474         }
14475       END_CATCH
14476     }
14477
14478   bpt->enable_state = bp_enabled;
14479
14480   /* Mark breakpoint locations modified.  */
14481   mark_breakpoint_modified (bpt);
14482
14483   if (target_supports_enable_disable_tracepoint ()
14484       && current_trace_status ()->running && is_tracepoint (bpt))
14485     {
14486       struct bp_location *location;
14487
14488       for (location = bpt->loc; location; location = location->next)
14489         target_enable_tracepoint (location);
14490     }
14491
14492   bpt->disposition = disposition;
14493   bpt->enable_count = count;
14494   update_global_location_list (UGLL_MAY_INSERT);
14495
14496   observer_notify_breakpoint_modified (bpt);
14497 }
14498
14499
14500 void
14501 enable_breakpoint (struct breakpoint *bpt)
14502 {
14503   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14504 }
14505
14506 /* The enable command enables the specified breakpoints/locations (or
14507    all defined breakpoints) so they once again become (or continue to
14508    be) effective in stopping the inferior.  ARGS may be in any of the
14509    forms defined in extract_bp_number_and_location.  */
14510
14511 static void
14512 enable_command (const char *args, int from_tty)
14513 {
14514   enable_disable_command (args, from_tty, true);
14515 }
14516
14517 static void
14518 enable_once_command (const char *args, int from_tty)
14519 {
14520   map_breakpoint_numbers
14521     (args, [&] (breakpoint *b)
14522      {
14523        iterate_over_related_breakpoints
14524          (b, [&] (breakpoint *bpt)
14525           {
14526             enable_breakpoint_disp (bpt, disp_disable, 1);
14527           });
14528      });
14529 }
14530
14531 static void
14532 enable_count_command (const char *args, int from_tty)
14533 {
14534   int count;
14535
14536   if (args == NULL)
14537     error_no_arg (_("hit count"));
14538
14539   count = get_number (&args);
14540
14541   map_breakpoint_numbers
14542     (args, [&] (breakpoint *b)
14543      {
14544        iterate_over_related_breakpoints
14545          (b, [&] (breakpoint *bpt)
14546           {
14547             enable_breakpoint_disp (bpt, disp_disable, count);
14548           });
14549      });
14550 }
14551
14552 static void
14553 enable_delete_command (const char *args, int from_tty)
14554 {
14555   map_breakpoint_numbers
14556     (args, [&] (breakpoint *b)
14557      {
14558        iterate_over_related_breakpoints
14559          (b, [&] (breakpoint *bpt)
14560           {
14561             enable_breakpoint_disp (bpt, disp_del, 1);
14562           });
14563      });
14564 }
14565 \f
14566 static void
14567 set_breakpoint_cmd (const char *args, int from_tty)
14568 {
14569 }
14570
14571 static void
14572 show_breakpoint_cmd (const char *args, int from_tty)
14573 {
14574 }
14575
14576 /* Invalidate last known value of any hardware watchpoint if
14577    the memory which that value represents has been written to by
14578    GDB itself.  */
14579
14580 static void
14581 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14582                                       CORE_ADDR addr, ssize_t len,
14583                                       const bfd_byte *data)
14584 {
14585   struct breakpoint *bp;
14586
14587   ALL_BREAKPOINTS (bp)
14588     if (bp->enable_state == bp_enabled
14589         && bp->type == bp_hardware_watchpoint)
14590       {
14591         struct watchpoint *wp = (struct watchpoint *) bp;
14592
14593         if (wp->val_valid && wp->val)
14594           {
14595             struct bp_location *loc;
14596
14597             for (loc = bp->loc; loc != NULL; loc = loc->next)
14598               if (loc->loc_type == bp_loc_hardware_watchpoint
14599                   && loc->address + loc->length > addr
14600                   && addr + len > loc->address)
14601                 {
14602                   value_free (wp->val);
14603                   wp->val = NULL;
14604                   wp->val_valid = 0;
14605                 }
14606           }
14607       }
14608 }
14609
14610 /* Create and insert a breakpoint for software single step.  */
14611
14612 void
14613 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14614                                const address_space *aspace,
14615                                CORE_ADDR next_pc)
14616 {
14617   struct thread_info *tp = inferior_thread ();
14618   struct symtab_and_line sal;
14619   CORE_ADDR pc = next_pc;
14620
14621   if (tp->control.single_step_breakpoints == NULL)
14622     {
14623       tp->control.single_step_breakpoints
14624         = new_single_step_breakpoint (tp->global_num, gdbarch);
14625     }
14626
14627   sal = find_pc_line (pc, 0);
14628   sal.pc = pc;
14629   sal.section = find_pc_overlay (pc);
14630   sal.explicit_pc = 1;
14631   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14632
14633   update_global_location_list (UGLL_INSERT);
14634 }
14635
14636 /* Insert single step breakpoints according to the current state.  */
14637
14638 int
14639 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14640 {
14641   struct regcache *regcache = get_current_regcache ();
14642   std::vector<CORE_ADDR> next_pcs;
14643
14644   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14645
14646   if (!next_pcs.empty ())
14647     {
14648       struct frame_info *frame = get_current_frame ();
14649       const address_space *aspace = get_frame_address_space (frame);
14650
14651       for (CORE_ADDR pc : next_pcs)
14652         insert_single_step_breakpoint (gdbarch, aspace, pc);
14653
14654       return 1;
14655     }
14656   else
14657     return 0;
14658 }
14659
14660 /* See breakpoint.h.  */
14661
14662 int
14663 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14664                                        const address_space *aspace,
14665                                        CORE_ADDR pc)
14666 {
14667   struct bp_location *loc;
14668
14669   for (loc = bp->loc; loc != NULL; loc = loc->next)
14670     if (loc->inserted
14671         && breakpoint_location_address_match (loc, aspace, pc))
14672       return 1;
14673
14674   return 0;
14675 }
14676
14677 /* Check whether a software single-step breakpoint is inserted at
14678    PC.  */
14679
14680 int
14681 single_step_breakpoint_inserted_here_p (const address_space *aspace,
14682                                         CORE_ADDR pc)
14683 {
14684   struct breakpoint *bpt;
14685
14686   ALL_BREAKPOINTS (bpt)
14687     {
14688       if (bpt->type == bp_single_step
14689           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
14690         return 1;
14691     }
14692   return 0;
14693 }
14694
14695 /* Tracepoint-specific operations.  */
14696
14697 /* Set tracepoint count to NUM.  */
14698 static void
14699 set_tracepoint_count (int num)
14700 {
14701   tracepoint_count = num;
14702   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14703 }
14704
14705 static void
14706 trace_command (const char *arg, int from_tty)
14707 {
14708   struct breakpoint_ops *ops;
14709
14710   event_location_up location = string_to_event_location (&arg,
14711                                                          current_language);
14712   if (location != NULL
14713       && event_location_type (location.get ()) == PROBE_LOCATION)
14714     ops = &tracepoint_probe_breakpoint_ops;
14715   else
14716     ops = &tracepoint_breakpoint_ops;
14717
14718   create_breakpoint (get_current_arch (),
14719                      location.get (),
14720                      NULL, 0, arg, 1 /* parse arg */,
14721                      0 /* tempflag */,
14722                      bp_tracepoint /* type_wanted */,
14723                      0 /* Ignore count */,
14724                      pending_break_support,
14725                      ops,
14726                      from_tty,
14727                      1 /* enabled */,
14728                      0 /* internal */, 0);
14729 }
14730
14731 static void
14732 ftrace_command (const char *arg, int from_tty)
14733 {
14734   event_location_up location = string_to_event_location (&arg,
14735                                                          current_language);
14736   create_breakpoint (get_current_arch (),
14737                      location.get (),
14738                      NULL, 0, arg, 1 /* parse arg */,
14739                      0 /* tempflag */,
14740                      bp_fast_tracepoint /* type_wanted */,
14741                      0 /* Ignore count */,
14742                      pending_break_support,
14743                      &tracepoint_breakpoint_ops,
14744                      from_tty,
14745                      1 /* enabled */,
14746                      0 /* internal */, 0);
14747 }
14748
14749 /* strace command implementation.  Creates a static tracepoint.  */
14750
14751 static void
14752 strace_command (const char *arg, int from_tty)
14753 {
14754   struct breakpoint_ops *ops;
14755   event_location_up location;
14756
14757   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14758      or with a normal static tracepoint.  */
14759   if (arg && startswith (arg, "-m") && isspace (arg[2]))
14760     {
14761       ops = &strace_marker_breakpoint_ops;
14762       location = new_linespec_location (&arg);
14763     }
14764   else
14765     {
14766       ops = &tracepoint_breakpoint_ops;
14767       location = string_to_event_location (&arg, current_language);
14768     }
14769
14770   create_breakpoint (get_current_arch (),
14771                      location.get (),
14772                      NULL, 0, arg, 1 /* parse arg */,
14773                      0 /* tempflag */,
14774                      bp_static_tracepoint /* type_wanted */,
14775                      0 /* Ignore count */,
14776                      pending_break_support,
14777                      ops,
14778                      from_tty,
14779                      1 /* enabled */,
14780                      0 /* internal */, 0);
14781 }
14782
14783 /* Set up a fake reader function that gets command lines from a linked
14784    list that was acquired during tracepoint uploading.  */
14785
14786 static struct uploaded_tp *this_utp;
14787 static int next_cmd;
14788
14789 static char *
14790 read_uploaded_action (void)
14791 {
14792   char *rslt;
14793
14794   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
14795
14796   next_cmd++;
14797
14798   return rslt;
14799 }
14800
14801 /* Given information about a tracepoint as recorded on a target (which
14802    can be either a live system or a trace file), attempt to create an
14803    equivalent GDB tracepoint.  This is not a reliable process, since
14804    the target does not necessarily have all the information used when
14805    the tracepoint was originally defined.  */
14806   
14807 struct tracepoint *
14808 create_tracepoint_from_upload (struct uploaded_tp *utp)
14809 {
14810   const char *addr_str;
14811   char small_buf[100];
14812   struct tracepoint *tp;
14813
14814   if (utp->at_string)
14815     addr_str = utp->at_string;
14816   else
14817     {
14818       /* In the absence of a source location, fall back to raw
14819          address.  Since there is no way to confirm that the address
14820          means the same thing as when the trace was started, warn the
14821          user.  */
14822       warning (_("Uploaded tracepoint %d has no "
14823                  "source location, using raw address"),
14824                utp->number);
14825       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14826       addr_str = small_buf;
14827     }
14828
14829   /* There's not much we can do with a sequence of bytecodes.  */
14830   if (utp->cond && !utp->cond_string)
14831     warning (_("Uploaded tracepoint %d condition "
14832                "has no source form, ignoring it"),
14833              utp->number);
14834
14835   event_location_up location = string_to_event_location (&addr_str,
14836                                                          current_language);
14837   if (!create_breakpoint (get_current_arch (),
14838                           location.get (),
14839                           utp->cond_string, -1, addr_str,
14840                           0 /* parse cond/thread */,
14841                           0 /* tempflag */,
14842                           utp->type /* type_wanted */,
14843                           0 /* Ignore count */,
14844                           pending_break_support,
14845                           &tracepoint_breakpoint_ops,
14846                           0 /* from_tty */,
14847                           utp->enabled /* enabled */,
14848                           0 /* internal */,
14849                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14850     return NULL;
14851
14852   /* Get the tracepoint we just created.  */
14853   tp = get_tracepoint (tracepoint_count);
14854   gdb_assert (tp != NULL);
14855
14856   if (utp->pass > 0)
14857     {
14858       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14859                  tp->number);
14860
14861       trace_pass_command (small_buf, 0);
14862     }
14863
14864   /* If we have uploaded versions of the original commands, set up a
14865      special-purpose "reader" function and call the usual command line
14866      reader, then pass the result to the breakpoint command-setting
14867      function.  */
14868   if (!VEC_empty (char_ptr, utp->cmd_strings))
14869     {
14870       command_line_up cmd_list;
14871
14872       this_utp = utp;
14873       next_cmd = 0;
14874
14875       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
14876
14877       breakpoint_set_commands (tp, std::move (cmd_list));
14878     }
14879   else if (!VEC_empty (char_ptr, utp->actions)
14880            || !VEC_empty (char_ptr, utp->step_actions))
14881     warning (_("Uploaded tracepoint %d actions "
14882                "have no source form, ignoring them"),
14883              utp->number);
14884
14885   /* Copy any status information that might be available.  */
14886   tp->hit_count = utp->hit_count;
14887   tp->traceframe_usage = utp->traceframe_usage;
14888
14889   return tp;
14890 }
14891   
14892 /* Print information on tracepoint number TPNUM_EXP, or all if
14893    omitted.  */
14894
14895 static void
14896 info_tracepoints_command (const char *args, int from_tty)
14897 {
14898   struct ui_out *uiout = current_uiout;
14899   int num_printed;
14900
14901   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14902
14903   if (num_printed == 0)
14904     {
14905       if (args == NULL || *args == '\0')
14906         uiout->message ("No tracepoints.\n");
14907       else
14908         uiout->message ("No tracepoint matching '%s'.\n", args);
14909     }
14910
14911   default_collect_info ();
14912 }
14913
14914 /* The 'enable trace' command enables tracepoints.
14915    Not supported by all targets.  */
14916 static void
14917 enable_trace_command (const char *args, int from_tty)
14918 {
14919   enable_command (args, from_tty);
14920 }
14921
14922 /* The 'disable trace' command disables tracepoints.
14923    Not supported by all targets.  */
14924 static void
14925 disable_trace_command (const char *args, int from_tty)
14926 {
14927   disable_command (args, from_tty);
14928 }
14929
14930 /* Remove a tracepoint (or all if no argument).  */
14931 static void
14932 delete_trace_command (const char *arg, int from_tty)
14933 {
14934   struct breakpoint *b, *b_tmp;
14935
14936   dont_repeat ();
14937
14938   if (arg == 0)
14939     {
14940       int breaks_to_delete = 0;
14941
14942       /* Delete all breakpoints if no argument.
14943          Do not delete internal or call-dummy breakpoints, these
14944          have to be deleted with an explicit breakpoint number 
14945          argument.  */
14946       ALL_TRACEPOINTS (b)
14947         if (is_tracepoint (b) && user_breakpoint_p (b))
14948           {
14949             breaks_to_delete = 1;
14950             break;
14951           }
14952
14953       /* Ask user only if there are some breakpoints to delete.  */
14954       if (!from_tty
14955           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14956         {
14957           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14958             if (is_tracepoint (b) && user_breakpoint_p (b))
14959               delete_breakpoint (b);
14960         }
14961     }
14962   else
14963     map_breakpoint_numbers
14964       (arg, [&] (breakpoint *b)
14965        {
14966          iterate_over_related_breakpoints (b, delete_breakpoint);
14967        });
14968 }
14969
14970 /* Helper function for trace_pass_command.  */
14971
14972 static void
14973 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14974 {
14975   tp->pass_count = count;
14976   observer_notify_breakpoint_modified (tp);
14977   if (from_tty)
14978     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
14979                      tp->number, count);
14980 }
14981
14982 /* Set passcount for tracepoint.
14983
14984    First command argument is passcount, second is tracepoint number.
14985    If tracepoint number omitted, apply to most recently defined.
14986    Also accepts special argument "all".  */
14987
14988 static void
14989 trace_pass_command (const char *args, int from_tty)
14990 {
14991   struct tracepoint *t1;
14992   ULONGEST count;
14993
14994   if (args == 0 || *args == 0)
14995     error (_("passcount command requires an "
14996              "argument (count + optional TP num)"));
14997
14998   count = strtoulst (args, &args, 10);  /* Count comes first, then TP num.  */
14999
15000   args = skip_spaces (args);
15001   if (*args && strncasecmp (args, "all", 3) == 0)
15002     {
15003       struct breakpoint *b;
15004
15005       args += 3;                        /* Skip special argument "all".  */
15006       if (*args)
15007         error (_("Junk at end of arguments."));
15008
15009       ALL_TRACEPOINTS (b)
15010       {
15011         t1 = (struct tracepoint *) b;
15012         trace_pass_set_count (t1, count, from_tty);
15013       }
15014     }
15015   else if (*args == '\0')
15016     {
15017       t1 = get_tracepoint_by_number (&args, NULL);
15018       if (t1)
15019         trace_pass_set_count (t1, count, from_tty);
15020     }
15021   else
15022     {
15023       number_or_range_parser parser (args);
15024       while (!parser.finished ())
15025         {
15026           t1 = get_tracepoint_by_number (&args, &parser);
15027           if (t1)
15028             trace_pass_set_count (t1, count, from_tty);
15029         }
15030     }
15031 }
15032
15033 struct tracepoint *
15034 get_tracepoint (int num)
15035 {
15036   struct breakpoint *t;
15037
15038   ALL_TRACEPOINTS (t)
15039     if (t->number == num)
15040       return (struct tracepoint *) t;
15041
15042   return NULL;
15043 }
15044
15045 /* Find the tracepoint with the given target-side number (which may be
15046    different from the tracepoint number after disconnecting and
15047    reconnecting).  */
15048
15049 struct tracepoint *
15050 get_tracepoint_by_number_on_target (int num)
15051 {
15052   struct breakpoint *b;
15053
15054   ALL_TRACEPOINTS (b)
15055     {
15056       struct tracepoint *t = (struct tracepoint *) b;
15057
15058       if (t->number_on_target == num)
15059         return t;
15060     }
15061
15062   return NULL;
15063 }
15064
15065 /* Utility: parse a tracepoint number and look it up in the list.
15066    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15067    If the argument is missing, the most recent tracepoint
15068    (tracepoint_count) is returned.  */
15069
15070 struct tracepoint *
15071 get_tracepoint_by_number (const char **arg,
15072                           number_or_range_parser *parser)
15073 {
15074   struct breakpoint *t;
15075   int tpnum;
15076   const char *instring = arg == NULL ? NULL : *arg;
15077
15078   if (parser != NULL)
15079     {
15080       gdb_assert (!parser->finished ());
15081       tpnum = parser->get_number ();
15082     }
15083   else if (arg == NULL || *arg == NULL || ! **arg)
15084     tpnum = tracepoint_count;
15085   else
15086     tpnum = get_number (arg);
15087
15088   if (tpnum <= 0)
15089     {
15090       if (instring && *instring)
15091         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15092                          instring);
15093       else
15094         printf_filtered (_("No previous tracepoint\n"));
15095       return NULL;
15096     }
15097
15098   ALL_TRACEPOINTS (t)
15099     if (t->number == tpnum)
15100     {
15101       return (struct tracepoint *) t;
15102     }
15103
15104   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15105   return NULL;
15106 }
15107
15108 void
15109 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15110 {
15111   if (b->thread != -1)
15112     fprintf_unfiltered (fp, " thread %d", b->thread);
15113
15114   if (b->task != 0)
15115     fprintf_unfiltered (fp, " task %d", b->task);
15116
15117   fprintf_unfiltered (fp, "\n");
15118 }
15119
15120 /* Save information on user settable breakpoints (watchpoints, etc) to
15121    a new script file named FILENAME.  If FILTER is non-NULL, call it
15122    on each breakpoint and only include the ones for which it returns
15123    non-zero.  */
15124
15125 static void
15126 save_breakpoints (const char *filename, int from_tty,
15127                   int (*filter) (const struct breakpoint *))
15128 {
15129   struct breakpoint *tp;
15130   int any = 0;
15131   int extra_trace_bits = 0;
15132
15133   if (filename == 0 || *filename == 0)
15134     error (_("Argument required (file name in which to save)"));
15135
15136   /* See if we have anything to save.  */
15137   ALL_BREAKPOINTS (tp)
15138   {
15139     /* Skip internal and momentary breakpoints.  */
15140     if (!user_breakpoint_p (tp))
15141       continue;
15142
15143     /* If we have a filter, only save the breakpoints it accepts.  */
15144     if (filter && !filter (tp))
15145       continue;
15146
15147     any = 1;
15148
15149     if (is_tracepoint (tp))
15150       {
15151         extra_trace_bits = 1;
15152
15153         /* We can stop searching.  */
15154         break;
15155       }
15156   }
15157
15158   if (!any)
15159     {
15160       warning (_("Nothing to save."));
15161       return;
15162     }
15163
15164   gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
15165
15166   stdio_file fp;
15167
15168   if (!fp.open (expanded_filename.get (), "w"))
15169     error (_("Unable to open file '%s' for saving (%s)"),
15170            expanded_filename.get (), safe_strerror (errno));
15171
15172   if (extra_trace_bits)
15173     save_trace_state_variables (&fp);
15174
15175   ALL_BREAKPOINTS (tp)
15176   {
15177     /* Skip internal and momentary breakpoints.  */
15178     if (!user_breakpoint_p (tp))
15179       continue;
15180
15181     /* If we have a filter, only save the breakpoints it accepts.  */
15182     if (filter && !filter (tp))
15183       continue;
15184
15185     tp->ops->print_recreate (tp, &fp);
15186
15187     /* Note, we can't rely on tp->number for anything, as we can't
15188        assume the recreated breakpoint numbers will match.  Use $bpnum
15189        instead.  */
15190
15191     if (tp->cond_string)
15192       fp.printf ("  condition $bpnum %s\n", tp->cond_string);
15193
15194     if (tp->ignore_count)
15195       fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15196
15197     if (tp->type != bp_dprintf && tp->commands)
15198       {
15199         fp.puts ("  commands\n");
15200         
15201         current_uiout->redirect (&fp);
15202         TRY
15203           {
15204             print_command_lines (current_uiout, tp->commands.get (), 2);
15205           }
15206         CATCH (ex, RETURN_MASK_ALL)
15207           {
15208           current_uiout->redirect (NULL);
15209             throw_exception (ex);
15210           }
15211         END_CATCH
15212
15213         current_uiout->redirect (NULL);
15214         fp.puts ("  end\n");
15215       }
15216
15217     if (tp->enable_state == bp_disabled)
15218       fp.puts ("disable $bpnum\n");
15219
15220     /* If this is a multi-location breakpoint, check if the locations
15221        should be individually disabled.  Watchpoint locations are
15222        special, and not user visible.  */
15223     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15224       {
15225         struct bp_location *loc;
15226         int n = 1;
15227
15228         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15229           if (!loc->enabled)
15230             fp.printf ("disable $bpnum.%d\n", n);
15231       }
15232   }
15233
15234   if (extra_trace_bits && *default_collect)
15235     fp.printf ("set default-collect %s\n", default_collect);
15236
15237   if (from_tty)
15238     printf_filtered (_("Saved to file '%s'.\n"), expanded_filename.get ());
15239 }
15240
15241 /* The `save breakpoints' command.  */
15242
15243 static void
15244 save_breakpoints_command (const char *args, int from_tty)
15245 {
15246   save_breakpoints (args, from_tty, NULL);
15247 }
15248
15249 /* The `save tracepoints' command.  */
15250
15251 static void
15252 save_tracepoints_command (const char *args, int from_tty)
15253 {
15254   save_breakpoints (args, from_tty, is_tracepoint);
15255 }
15256
15257 /* Create a vector of all tracepoints.  */
15258
15259 VEC(breakpoint_p) *
15260 all_tracepoints (void)
15261 {
15262   VEC(breakpoint_p) *tp_vec = 0;
15263   struct breakpoint *tp;
15264
15265   ALL_TRACEPOINTS (tp)
15266   {
15267     VEC_safe_push (breakpoint_p, tp_vec, tp);
15268   }
15269
15270   return tp_vec;
15271 }
15272
15273 \f
15274 /* This help string is used to consolidate all the help string for specifying
15275    locations used by several commands.  */
15276
15277 #define LOCATION_HELP_STRING \
15278 "Linespecs are colon-separated lists of location parameters, such as\n\
15279 source filename, function name, label name, and line number.\n\
15280 Example: To specify the start of a label named \"the_top\" in the\n\
15281 function \"fact\" in the file \"factorial.c\", use\n\
15282 \"factorial.c:fact:the_top\".\n\
15283 \n\
15284 Address locations begin with \"*\" and specify an exact address in the\n\
15285 program.  Example: To specify the fourth byte past the start function\n\
15286 \"main\", use \"*main + 4\".\n\
15287 \n\
15288 Explicit locations are similar to linespecs but use an option/argument\n\
15289 syntax to specify location parameters.\n\
15290 Example: To specify the start of the label named \"the_top\" in the\n\
15291 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15292 -function fact -label the_top\".\n"
15293
15294 /* This help string is used for the break, hbreak, tbreak and thbreak
15295    commands.  It is defined as a macro to prevent duplication.
15296    COMMAND should be a string constant containing the name of the
15297    command.  */
15298
15299 #define BREAK_ARGS_HELP(command) \
15300 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15301 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15302 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15303 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15304 `-probe-dtrace' (for a DTrace probe).\n\
15305 LOCATION may be a linespec, address, or explicit location as described\n\
15306 below.\n\
15307 \n\
15308 With no LOCATION, uses current execution address of the selected\n\
15309 stack frame.  This is useful for breaking on return to a stack frame.\n\
15310 \n\
15311 THREADNUM is the number from \"info threads\".\n\
15312 CONDITION is a boolean expression.\n\
15313 \n" LOCATION_HELP_STRING "\n\
15314 Multiple breakpoints at one place are permitted, and useful if their\n\
15315 conditions are different.\n\
15316 \n\
15317 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15318
15319 /* List of subcommands for "catch".  */
15320 static struct cmd_list_element *catch_cmdlist;
15321
15322 /* List of subcommands for "tcatch".  */
15323 static struct cmd_list_element *tcatch_cmdlist;
15324
15325 void
15326 add_catch_command (const char *name, const char *docstring,
15327                    cmd_const_sfunc_ftype *sfunc,
15328                    completer_ftype *completer,
15329                    void *user_data_catch,
15330                    void *user_data_tcatch)
15331 {
15332   struct cmd_list_element *command;
15333
15334   command = add_cmd (name, class_breakpoint, docstring,
15335                      &catch_cmdlist);
15336   set_cmd_sfunc (command, sfunc);
15337   set_cmd_context (command, user_data_catch);
15338   set_cmd_completer (command, completer);
15339
15340   command = add_cmd (name, class_breakpoint, docstring,
15341                      &tcatch_cmdlist);
15342   set_cmd_sfunc (command, sfunc);
15343   set_cmd_context (command, user_data_tcatch);
15344   set_cmd_completer (command, completer);
15345 }
15346
15347 static void
15348 save_command (const char *arg, int from_tty)
15349 {
15350   printf_unfiltered (_("\"save\" must be followed by "
15351                        "the name of a save subcommand.\n"));
15352   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15353 }
15354
15355 struct breakpoint *
15356 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15357                           void *data)
15358 {
15359   struct breakpoint *b, *b_tmp;
15360
15361   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15362     {
15363       if ((*callback) (b, data))
15364         return b;
15365     }
15366
15367   return NULL;
15368 }
15369
15370 /* Zero if any of the breakpoint's locations could be a location where
15371    functions have been inlined, nonzero otherwise.  */
15372
15373 static int
15374 is_non_inline_function (struct breakpoint *b)
15375 {
15376   /* The shared library event breakpoint is set on the address of a
15377      non-inline function.  */
15378   if (b->type == bp_shlib_event)
15379     return 1;
15380
15381   return 0;
15382 }
15383
15384 /* Nonzero if the specified PC cannot be a location where functions
15385    have been inlined.  */
15386
15387 int
15388 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
15389                            const struct target_waitstatus *ws)
15390 {
15391   struct breakpoint *b;
15392   struct bp_location *bl;
15393
15394   ALL_BREAKPOINTS (b)
15395     {
15396       if (!is_non_inline_function (b))
15397         continue;
15398
15399       for (bl = b->loc; bl != NULL; bl = bl->next)
15400         {
15401           if (!bl->shlib_disabled
15402               && bpstat_check_location (bl, aspace, pc, ws))
15403             return 1;
15404         }
15405     }
15406
15407   return 0;
15408 }
15409
15410 /* Remove any references to OBJFILE which is going to be freed.  */
15411
15412 void
15413 breakpoint_free_objfile (struct objfile *objfile)
15414 {
15415   struct bp_location **locp, *loc;
15416
15417   ALL_BP_LOCATIONS (loc, locp)
15418     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15419       loc->symtab = NULL;
15420 }
15421
15422 void
15423 initialize_breakpoint_ops (void)
15424 {
15425   static int initialized = 0;
15426
15427   struct breakpoint_ops *ops;
15428
15429   if (initialized)
15430     return;
15431   initialized = 1;
15432
15433   /* The breakpoint_ops structure to be inherit by all kinds of
15434      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15435      internal and momentary breakpoints, etc.).  */
15436   ops = &bkpt_base_breakpoint_ops;
15437   *ops = base_breakpoint_ops;
15438   ops->re_set = bkpt_re_set;
15439   ops->insert_location = bkpt_insert_location;
15440   ops->remove_location = bkpt_remove_location;
15441   ops->breakpoint_hit = bkpt_breakpoint_hit;
15442   ops->create_sals_from_location = bkpt_create_sals_from_location;
15443   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15444   ops->decode_location = bkpt_decode_location;
15445
15446   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15447   ops = &bkpt_breakpoint_ops;
15448   *ops = bkpt_base_breakpoint_ops;
15449   ops->re_set = bkpt_re_set;
15450   ops->resources_needed = bkpt_resources_needed;
15451   ops->print_it = bkpt_print_it;
15452   ops->print_mention = bkpt_print_mention;
15453   ops->print_recreate = bkpt_print_recreate;
15454
15455   /* Ranged breakpoints.  */
15456   ops = &ranged_breakpoint_ops;
15457   *ops = bkpt_breakpoint_ops;
15458   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15459   ops->resources_needed = resources_needed_ranged_breakpoint;
15460   ops->print_it = print_it_ranged_breakpoint;
15461   ops->print_one = print_one_ranged_breakpoint;
15462   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15463   ops->print_mention = print_mention_ranged_breakpoint;
15464   ops->print_recreate = print_recreate_ranged_breakpoint;
15465
15466   /* Internal breakpoints.  */
15467   ops = &internal_breakpoint_ops;
15468   *ops = bkpt_base_breakpoint_ops;
15469   ops->re_set = internal_bkpt_re_set;
15470   ops->check_status = internal_bkpt_check_status;
15471   ops->print_it = internal_bkpt_print_it;
15472   ops->print_mention = internal_bkpt_print_mention;
15473
15474   /* Momentary breakpoints.  */
15475   ops = &momentary_breakpoint_ops;
15476   *ops = bkpt_base_breakpoint_ops;
15477   ops->re_set = momentary_bkpt_re_set;
15478   ops->check_status = momentary_bkpt_check_status;
15479   ops->print_it = momentary_bkpt_print_it;
15480   ops->print_mention = momentary_bkpt_print_mention;
15481
15482   /* Probe breakpoints.  */
15483   ops = &bkpt_probe_breakpoint_ops;
15484   *ops = bkpt_breakpoint_ops;
15485   ops->insert_location = bkpt_probe_insert_location;
15486   ops->remove_location = bkpt_probe_remove_location;
15487   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15488   ops->decode_location = bkpt_probe_decode_location;
15489
15490   /* Watchpoints.  */
15491   ops = &watchpoint_breakpoint_ops;
15492   *ops = base_breakpoint_ops;
15493   ops->re_set = re_set_watchpoint;
15494   ops->insert_location = insert_watchpoint;
15495   ops->remove_location = remove_watchpoint;
15496   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15497   ops->check_status = check_status_watchpoint;
15498   ops->resources_needed = resources_needed_watchpoint;
15499   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15500   ops->print_it = print_it_watchpoint;
15501   ops->print_mention = print_mention_watchpoint;
15502   ops->print_recreate = print_recreate_watchpoint;
15503   ops->explains_signal = explains_signal_watchpoint;
15504
15505   /* Masked watchpoints.  */
15506   ops = &masked_watchpoint_breakpoint_ops;
15507   *ops = watchpoint_breakpoint_ops;
15508   ops->insert_location = insert_masked_watchpoint;
15509   ops->remove_location = remove_masked_watchpoint;
15510   ops->resources_needed = resources_needed_masked_watchpoint;
15511   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15512   ops->print_it = print_it_masked_watchpoint;
15513   ops->print_one_detail = print_one_detail_masked_watchpoint;
15514   ops->print_mention = print_mention_masked_watchpoint;
15515   ops->print_recreate = print_recreate_masked_watchpoint;
15516
15517   /* Tracepoints.  */
15518   ops = &tracepoint_breakpoint_ops;
15519   *ops = base_breakpoint_ops;
15520   ops->re_set = tracepoint_re_set;
15521   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15522   ops->print_one_detail = tracepoint_print_one_detail;
15523   ops->print_mention = tracepoint_print_mention;
15524   ops->print_recreate = tracepoint_print_recreate;
15525   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15526   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15527   ops->decode_location = tracepoint_decode_location;
15528
15529   /* Probe tracepoints.  */
15530   ops = &tracepoint_probe_breakpoint_ops;
15531   *ops = tracepoint_breakpoint_ops;
15532   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15533   ops->decode_location = tracepoint_probe_decode_location;
15534
15535   /* Static tracepoints with marker (`-m').  */
15536   ops = &strace_marker_breakpoint_ops;
15537   *ops = tracepoint_breakpoint_ops;
15538   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15539   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15540   ops->decode_location = strace_marker_decode_location;
15541
15542   /* Fork catchpoints.  */
15543   ops = &catch_fork_breakpoint_ops;
15544   *ops = base_breakpoint_ops;
15545   ops->insert_location = insert_catch_fork;
15546   ops->remove_location = remove_catch_fork;
15547   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15548   ops->print_it = print_it_catch_fork;
15549   ops->print_one = print_one_catch_fork;
15550   ops->print_mention = print_mention_catch_fork;
15551   ops->print_recreate = print_recreate_catch_fork;
15552
15553   /* Vfork catchpoints.  */
15554   ops = &catch_vfork_breakpoint_ops;
15555   *ops = base_breakpoint_ops;
15556   ops->insert_location = insert_catch_vfork;
15557   ops->remove_location = remove_catch_vfork;
15558   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15559   ops->print_it = print_it_catch_vfork;
15560   ops->print_one = print_one_catch_vfork;
15561   ops->print_mention = print_mention_catch_vfork;
15562   ops->print_recreate = print_recreate_catch_vfork;
15563
15564   /* Exec catchpoints.  */
15565   ops = &catch_exec_breakpoint_ops;
15566   *ops = base_breakpoint_ops;
15567   ops->insert_location = insert_catch_exec;
15568   ops->remove_location = remove_catch_exec;
15569   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15570   ops->print_it = print_it_catch_exec;
15571   ops->print_one = print_one_catch_exec;
15572   ops->print_mention = print_mention_catch_exec;
15573   ops->print_recreate = print_recreate_catch_exec;
15574
15575   /* Solib-related catchpoints.  */
15576   ops = &catch_solib_breakpoint_ops;
15577   *ops = base_breakpoint_ops;
15578   ops->insert_location = insert_catch_solib;
15579   ops->remove_location = remove_catch_solib;
15580   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15581   ops->check_status = check_status_catch_solib;
15582   ops->print_it = print_it_catch_solib;
15583   ops->print_one = print_one_catch_solib;
15584   ops->print_mention = print_mention_catch_solib;
15585   ops->print_recreate = print_recreate_catch_solib;
15586
15587   ops = &dprintf_breakpoint_ops;
15588   *ops = bkpt_base_breakpoint_ops;
15589   ops->re_set = dprintf_re_set;
15590   ops->resources_needed = bkpt_resources_needed;
15591   ops->print_it = bkpt_print_it;
15592   ops->print_mention = bkpt_print_mention;
15593   ops->print_recreate = dprintf_print_recreate;
15594   ops->after_condition_true = dprintf_after_condition_true;
15595   ops->breakpoint_hit = dprintf_breakpoint_hit;
15596 }
15597
15598 /* Chain containing all defined "enable breakpoint" subcommands.  */
15599
15600 static struct cmd_list_element *enablebreaklist = NULL;
15601
15602 void
15603 _initialize_breakpoint (void)
15604 {
15605   struct cmd_list_element *c;
15606
15607   initialize_breakpoint_ops ();
15608
15609   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15610   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
15611   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
15612
15613   breakpoint_objfile_key
15614     = register_objfile_data_with_cleanup (NULL, free_breakpoint_objfile_data);
15615
15616   breakpoint_chain = 0;
15617   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15618      before a breakpoint is set.  */
15619   breakpoint_count = 0;
15620
15621   tracepoint_count = 0;
15622
15623   add_com ("ignore", class_breakpoint, ignore_command, _("\
15624 Set ignore-count of breakpoint number N to COUNT.\n\
15625 Usage is `ignore N COUNT'."));
15626
15627   add_com ("commands", class_breakpoint, commands_command, _("\
15628 Set commands to be executed when the given breakpoints are hit.\n\
15629 Give a space-separated breakpoint list as argument after \"commands\".\n\
15630 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
15631 (e.g. `5-7').\n\
15632 With no argument, the targeted breakpoint is the last one set.\n\
15633 The commands themselves follow starting on the next line.\n\
15634 Type a line containing \"end\" to indicate the end of them.\n\
15635 Give \"silent\" as the first line to make the breakpoint silent;\n\
15636 then no output is printed when it is hit, except what the commands print."));
15637
15638   c = add_com ("condition", class_breakpoint, condition_command, _("\
15639 Specify breakpoint number N to break only if COND is true.\n\
15640 Usage is `condition N COND', where N is an integer and COND is an\n\
15641 expression to be evaluated whenever breakpoint N is reached."));
15642   set_cmd_completer (c, condition_completer);
15643
15644   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15645 Set a temporary breakpoint.\n\
15646 Like \"break\" except the breakpoint is only temporary,\n\
15647 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15648 by using \"enable delete\" on the breakpoint number.\n\
15649 \n"
15650 BREAK_ARGS_HELP ("tbreak")));
15651   set_cmd_completer (c, location_completer);
15652
15653   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15654 Set a hardware assisted breakpoint.\n\
15655 Like \"break\" except the breakpoint requires hardware support,\n\
15656 some target hardware may not have this support.\n\
15657 \n"
15658 BREAK_ARGS_HELP ("hbreak")));
15659   set_cmd_completer (c, location_completer);
15660
15661   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15662 Set a temporary hardware assisted breakpoint.\n\
15663 Like \"hbreak\" except the breakpoint is only temporary,\n\
15664 so it will be deleted when hit.\n\
15665 \n"
15666 BREAK_ARGS_HELP ("thbreak")));
15667   set_cmd_completer (c, location_completer);
15668
15669   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15670 Enable some breakpoints.\n\
15671 Give breakpoint numbers (separated by spaces) as arguments.\n\
15672 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15673 This is used to cancel the effect of the \"disable\" command.\n\
15674 With a subcommand you can enable temporarily."),
15675                   &enablelist, "enable ", 1, &cmdlist);
15676
15677   add_com_alias ("en", "enable", class_breakpoint, 1);
15678
15679   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15680 Enable some breakpoints.\n\
15681 Give breakpoint numbers (separated by spaces) as arguments.\n\
15682 This is used to cancel the effect of the \"disable\" command.\n\
15683 May be abbreviated to simply \"enable\".\n"),
15684                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15685
15686   add_cmd ("once", no_class, enable_once_command, _("\
15687 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15688 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15689            &enablebreaklist);
15690
15691   add_cmd ("delete", no_class, enable_delete_command, _("\
15692 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15693 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15694            &enablebreaklist);
15695
15696   add_cmd ("count", no_class, enable_count_command, _("\
15697 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15698 If a breakpoint is hit while enabled in this fashion,\n\
15699 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15700            &enablebreaklist);
15701
15702   add_cmd ("delete", no_class, enable_delete_command, _("\
15703 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15704 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15705            &enablelist);
15706
15707   add_cmd ("once", no_class, enable_once_command, _("\
15708 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15709 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15710            &enablelist);
15711
15712   add_cmd ("count", no_class, enable_count_command, _("\
15713 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15714 If a breakpoint is hit while enabled in this fashion,\n\
15715 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15716            &enablelist);
15717
15718   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15719 Disable some breakpoints.\n\
15720 Arguments are breakpoint numbers with spaces in between.\n\
15721 To disable all breakpoints, give no argument.\n\
15722 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15723                   &disablelist, "disable ", 1, &cmdlist);
15724   add_com_alias ("dis", "disable", class_breakpoint, 1);
15725   add_com_alias ("disa", "disable", class_breakpoint, 1);
15726
15727   add_cmd ("breakpoints", class_alias, disable_command, _("\
15728 Disable some breakpoints.\n\
15729 Arguments are breakpoint numbers with spaces in between.\n\
15730 To disable all breakpoints, give no argument.\n\
15731 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15732 This command may be abbreviated \"disable\"."),
15733            &disablelist);
15734
15735   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15736 Delete some breakpoints or auto-display expressions.\n\
15737 Arguments are breakpoint numbers with spaces in between.\n\
15738 To delete all breakpoints, give no argument.\n\
15739 \n\
15740 Also a prefix command for deletion of other GDB objects.\n\
15741 The \"unset\" command is also an alias for \"delete\"."),
15742                   &deletelist, "delete ", 1, &cmdlist);
15743   add_com_alias ("d", "delete", class_breakpoint, 1);
15744   add_com_alias ("del", "delete", class_breakpoint, 1);
15745
15746   add_cmd ("breakpoints", class_alias, delete_command, _("\
15747 Delete some breakpoints or auto-display expressions.\n\
15748 Arguments are breakpoint numbers with spaces in between.\n\
15749 To delete all breakpoints, give no argument.\n\
15750 This command may be abbreviated \"delete\"."),
15751            &deletelist);
15752
15753   add_com ("clear", class_breakpoint, clear_command, _("\
15754 Clear breakpoint at specified location.\n\
15755 Argument may be a linespec, explicit, or address location as described below.\n\
15756 \n\
15757 With no argument, clears all breakpoints in the line that the selected frame\n\
15758 is executing in.\n"
15759 "\n" LOCATION_HELP_STRING "\n\
15760 See also the \"delete\" command which clears breakpoints by number."));
15761   add_com_alias ("cl", "clear", class_breakpoint, 1);
15762
15763   c = add_com ("break", class_breakpoint, break_command, _("\
15764 Set breakpoint at specified location.\n"
15765 BREAK_ARGS_HELP ("break")));
15766   set_cmd_completer (c, location_completer);
15767
15768   add_com_alias ("b", "break", class_run, 1);
15769   add_com_alias ("br", "break", class_run, 1);
15770   add_com_alias ("bre", "break", class_run, 1);
15771   add_com_alias ("brea", "break", class_run, 1);
15772
15773   if (dbx_commands)
15774     {
15775       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15776 Break in function/address or break at a line in the current file."),
15777                              &stoplist, "stop ", 1, &cmdlist);
15778       add_cmd ("in", class_breakpoint, stopin_command,
15779                _("Break in function or address."), &stoplist);
15780       add_cmd ("at", class_breakpoint, stopat_command,
15781                _("Break at a line in the current file."), &stoplist);
15782       add_com ("status", class_info, info_breakpoints_command, _("\
15783 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15784 The \"Type\" column indicates one of:\n\
15785 \tbreakpoint     - normal breakpoint\n\
15786 \twatchpoint     - watchpoint\n\
15787 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15788 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15789 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15790 address and file/line number respectively.\n\
15791 \n\
15792 Convenience variable \"$_\" and default examine address for \"x\"\n\
15793 are set to the address of the last breakpoint listed unless the command\n\
15794 is prefixed with \"server \".\n\n\
15795 Convenience variable \"$bpnum\" contains the number of the last\n\
15796 breakpoint set."));
15797     }
15798
15799   add_info ("breakpoints", info_breakpoints_command, _("\
15800 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15801 The \"Type\" column indicates one of:\n\
15802 \tbreakpoint     - normal breakpoint\n\
15803 \twatchpoint     - watchpoint\n\
15804 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15805 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15806 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15807 address and file/line number respectively.\n\
15808 \n\
15809 Convenience variable \"$_\" and default examine address for \"x\"\n\
15810 are set to the address of the last breakpoint listed unless the command\n\
15811 is prefixed with \"server \".\n\n\
15812 Convenience variable \"$bpnum\" contains the number of the last\n\
15813 breakpoint set."));
15814
15815   add_info_alias ("b", "breakpoints", 1);
15816
15817   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15818 Status of all breakpoints, or breakpoint number NUMBER.\n\
15819 The \"Type\" column indicates one of:\n\
15820 \tbreakpoint     - normal breakpoint\n\
15821 \twatchpoint     - watchpoint\n\
15822 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15823 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15824 \tuntil          - internal breakpoint used by the \"until\" command\n\
15825 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15826 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15827 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15828 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15829 address and file/line number respectively.\n\
15830 \n\
15831 Convenience variable \"$_\" and default examine address for \"x\"\n\
15832 are set to the address of the last breakpoint listed unless the command\n\
15833 is prefixed with \"server \".\n\n\
15834 Convenience variable \"$bpnum\" contains the number of the last\n\
15835 breakpoint set."),
15836            &maintenanceinfolist);
15837
15838   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15839 Set catchpoints to catch events."),
15840                   &catch_cmdlist, "catch ",
15841                   0/*allow-unknown*/, &cmdlist);
15842
15843   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15844 Set temporary catchpoints to catch events."),
15845                   &tcatch_cmdlist, "tcatch ",
15846                   0/*allow-unknown*/, &cmdlist);
15847
15848   add_catch_command ("fork", _("Catch calls to fork."),
15849                      catch_fork_command_1,
15850                      NULL,
15851                      (void *) (uintptr_t) catch_fork_permanent,
15852                      (void *) (uintptr_t) catch_fork_temporary);
15853   add_catch_command ("vfork", _("Catch calls to vfork."),
15854                      catch_fork_command_1,
15855                      NULL,
15856                      (void *) (uintptr_t) catch_vfork_permanent,
15857                      (void *) (uintptr_t) catch_vfork_temporary);
15858   add_catch_command ("exec", _("Catch calls to exec."),
15859                      catch_exec_command_1,
15860                      NULL,
15861                      CATCH_PERMANENT,
15862                      CATCH_TEMPORARY);
15863   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15864 Usage: catch load [REGEX]\n\
15865 If REGEX is given, only stop for libraries matching the regular expression."),
15866                      catch_load_command_1,
15867                      NULL,
15868                      CATCH_PERMANENT,
15869                      CATCH_TEMPORARY);
15870   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15871 Usage: catch unload [REGEX]\n\
15872 If REGEX is given, only stop for libraries matching the regular expression."),
15873                      catch_unload_command_1,
15874                      NULL,
15875                      CATCH_PERMANENT,
15876                      CATCH_TEMPORARY);
15877
15878   c = add_com ("watch", class_breakpoint, watch_command, _("\
15879 Set a watchpoint for an expression.\n\
15880 Usage: watch [-l|-location] EXPRESSION\n\
15881 A watchpoint stops execution of your program whenever the value of\n\
15882 an expression changes.\n\
15883 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15884 the memory to which it refers."));
15885   set_cmd_completer (c, expression_completer);
15886
15887   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15888 Set a read watchpoint for an expression.\n\
15889 Usage: rwatch [-l|-location] EXPRESSION\n\
15890 A watchpoint stops execution of your program whenever the value of\n\
15891 an expression is read.\n\
15892 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15893 the memory to which it refers."));
15894   set_cmd_completer (c, expression_completer);
15895
15896   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15897 Set a watchpoint for an expression.\n\
15898 Usage: awatch [-l|-location] EXPRESSION\n\
15899 A watchpoint stops execution of your program whenever the value of\n\
15900 an expression is either read or written.\n\
15901 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15902 the memory to which it refers."));
15903   set_cmd_completer (c, expression_completer);
15904
15905   add_info ("watchpoints", info_watchpoints_command, _("\
15906 Status of specified watchpoints (all watchpoints if no argument)."));
15907
15908   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15909      respond to changes - contrary to the description.  */
15910   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15911                             &can_use_hw_watchpoints, _("\
15912 Set debugger's willingness to use watchpoint hardware."), _("\
15913 Show debugger's willingness to use watchpoint hardware."), _("\
15914 If zero, gdb will not use hardware for new watchpoints, even if\n\
15915 such is available.  (However, any hardware watchpoints that were\n\
15916 created before setting this to nonzero, will continue to use watchpoint\n\
15917 hardware.)"),
15918                             NULL,
15919                             show_can_use_hw_watchpoints,
15920                             &setlist, &showlist);
15921
15922   can_use_hw_watchpoints = 1;
15923
15924   /* Tracepoint manipulation commands.  */
15925
15926   c = add_com ("trace", class_breakpoint, trace_command, _("\
15927 Set a tracepoint at specified location.\n\
15928 \n"
15929 BREAK_ARGS_HELP ("trace") "\n\
15930 Do \"help tracepoints\" for info on other tracepoint commands."));
15931   set_cmd_completer (c, location_completer);
15932
15933   add_com_alias ("tp", "trace", class_alias, 0);
15934   add_com_alias ("tr", "trace", class_alias, 1);
15935   add_com_alias ("tra", "trace", class_alias, 1);
15936   add_com_alias ("trac", "trace", class_alias, 1);
15937
15938   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15939 Set a fast tracepoint at specified location.\n\
15940 \n"
15941 BREAK_ARGS_HELP ("ftrace") "\n\
15942 Do \"help tracepoints\" for info on other tracepoint commands."));
15943   set_cmd_completer (c, location_completer);
15944
15945   c = add_com ("strace", class_breakpoint, strace_command, _("\
15946 Set a static tracepoint at location or marker.\n\
15947 \n\
15948 strace [LOCATION] [if CONDITION]\n\
15949 LOCATION may be a linespec, explicit, or address location (described below) \n\
15950 or -m MARKER_ID.\n\n\
15951 If a marker id is specified, probe the marker with that name.  With\n\
15952 no LOCATION, uses current execution address of the selected stack frame.\n\
15953 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15954 This collects arbitrary user data passed in the probe point call to the\n\
15955 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15956 by printing the $_sdata variable like any other convenience variable.\n\
15957 \n\
15958 CONDITION is a boolean expression.\n\
15959 \n" LOCATION_HELP_STRING "\n\
15960 Multiple tracepoints at one place are permitted, and useful if their\n\
15961 conditions are different.\n\
15962 \n\
15963 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15964 Do \"help tracepoints\" for info on other tracepoint commands."));
15965   set_cmd_completer (c, location_completer);
15966
15967   add_info ("tracepoints", info_tracepoints_command, _("\
15968 Status of specified tracepoints (all tracepoints if no argument).\n\
15969 Convenience variable \"$tpnum\" contains the number of the\n\
15970 last tracepoint set."));
15971
15972   add_info_alias ("tp", "tracepoints", 1);
15973
15974   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15975 Delete specified tracepoints.\n\
15976 Arguments are tracepoint numbers, separated by spaces.\n\
15977 No argument means delete all tracepoints."),
15978            &deletelist);
15979   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
15980
15981   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15982 Disable specified tracepoints.\n\
15983 Arguments are tracepoint numbers, separated by spaces.\n\
15984 No argument means disable all tracepoints."),
15985            &disablelist);
15986   deprecate_cmd (c, "disable");
15987
15988   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15989 Enable specified tracepoints.\n\
15990 Arguments are tracepoint numbers, separated by spaces.\n\
15991 No argument means enable all tracepoints."),
15992            &enablelist);
15993   deprecate_cmd (c, "enable");
15994
15995   add_com ("passcount", class_trace, trace_pass_command, _("\
15996 Set the passcount for a tracepoint.\n\
15997 The trace will end when the tracepoint has been passed 'count' times.\n\
15998 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15999 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16000
16001   add_prefix_cmd ("save", class_breakpoint, save_command,
16002                   _("Save breakpoint definitions as a script."),
16003                   &save_cmdlist, "save ",
16004                   0/*allow-unknown*/, &cmdlist);
16005
16006   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16007 Save current breakpoint definitions as a script.\n\
16008 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16009 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16010 session to restore them."),
16011                &save_cmdlist);
16012   set_cmd_completer (c, filename_completer);
16013
16014   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16015 Save current tracepoint definitions as a script.\n\
16016 Use the 'source' command in another debug session to restore them."),
16017                &save_cmdlist);
16018   set_cmd_completer (c, filename_completer);
16019
16020   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16021   deprecate_cmd (c, "save tracepoints");
16022
16023   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16024 Breakpoint specific settings\n\
16025 Configure various breakpoint-specific variables such as\n\
16026 pending breakpoint behavior"),
16027                   &breakpoint_set_cmdlist, "set breakpoint ",
16028                   0/*allow-unknown*/, &setlist);
16029   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16030 Breakpoint specific settings\n\
16031 Configure various breakpoint-specific variables such as\n\
16032 pending breakpoint behavior"),
16033                   &breakpoint_show_cmdlist, "show breakpoint ",
16034                   0/*allow-unknown*/, &showlist);
16035
16036   add_setshow_auto_boolean_cmd ("pending", no_class,
16037                                 &pending_break_support, _("\
16038 Set debugger's behavior regarding pending breakpoints."), _("\
16039 Show debugger's behavior regarding pending breakpoints."), _("\
16040 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16041 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16042 an error.  If auto, an unrecognized breakpoint location results in a\n\
16043 user-query to see if a pending breakpoint should be created."),
16044                                 NULL,
16045                                 show_pending_break_support,
16046                                 &breakpoint_set_cmdlist,
16047                                 &breakpoint_show_cmdlist);
16048
16049   pending_break_support = AUTO_BOOLEAN_AUTO;
16050
16051   add_setshow_boolean_cmd ("auto-hw", no_class,
16052                            &automatic_hardware_breakpoints, _("\
16053 Set automatic usage of hardware breakpoints."), _("\
16054 Show automatic usage of hardware breakpoints."), _("\
16055 If set, the debugger will automatically use hardware breakpoints for\n\
16056 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16057 a warning will be emitted for such breakpoints."),
16058                            NULL,
16059                            show_automatic_hardware_breakpoints,
16060                            &breakpoint_set_cmdlist,
16061                            &breakpoint_show_cmdlist);
16062
16063   add_setshow_boolean_cmd ("always-inserted", class_support,
16064                            &always_inserted_mode, _("\
16065 Set mode for inserting breakpoints."), _("\
16066 Show mode for inserting breakpoints."), _("\
16067 When this mode is on, breakpoints are inserted immediately as soon as\n\
16068 they're created, kept inserted even when execution stops, and removed\n\
16069 only when the user deletes them.  When this mode is off (the default),\n\
16070 breakpoints are inserted only when execution continues, and removed\n\
16071 when execution stops."),
16072                                 NULL,
16073                                 &show_always_inserted_mode,
16074                                 &breakpoint_set_cmdlist,
16075                                 &breakpoint_show_cmdlist);
16076
16077   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16078                         condition_evaluation_enums,
16079                         &condition_evaluation_mode_1, _("\
16080 Set mode of breakpoint condition evaluation."), _("\
16081 Show mode of breakpoint condition evaluation."), _("\
16082 When this is set to \"host\", breakpoint conditions will be\n\
16083 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16084 breakpoint conditions will be downloaded to the target (if the target\n\
16085 supports such feature) and conditions will be evaluated on the target's side.\n\
16086 If this is set to \"auto\" (default), this will be automatically set to\n\
16087 \"target\" if it supports condition evaluation, otherwise it will\n\
16088 be set to \"gdb\""),
16089                            &set_condition_evaluation_mode,
16090                            &show_condition_evaluation_mode,
16091                            &breakpoint_set_cmdlist,
16092                            &breakpoint_show_cmdlist);
16093
16094   add_com ("break-range", class_breakpoint, break_range_command, _("\
16095 Set a breakpoint for an address range.\n\
16096 break-range START-LOCATION, END-LOCATION\n\
16097 where START-LOCATION and END-LOCATION can be one of the following:\n\
16098   LINENUM, for that line in the current file,\n\
16099   FILE:LINENUM, for that line in that file,\n\
16100   +OFFSET, for that number of lines after the current line\n\
16101            or the start of the range\n\
16102   FUNCTION, for the first line in that function,\n\
16103   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16104   *ADDRESS, for the instruction at that address.\n\
16105 \n\
16106 The breakpoint will stop execution of the inferior whenever it executes\n\
16107 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16108 range (including START-LOCATION and END-LOCATION)."));
16109
16110   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16111 Set a dynamic printf at specified location.\n\
16112 dprintf location,format string,arg1,arg2,...\n\
16113 location may be a linespec, explicit, or address location.\n"
16114 "\n" LOCATION_HELP_STRING));
16115   set_cmd_completer (c, location_completer);
16116
16117   add_setshow_enum_cmd ("dprintf-style", class_support,
16118                         dprintf_style_enums, &dprintf_style, _("\
16119 Set the style of usage for dynamic printf."), _("\
16120 Show the style of usage for dynamic printf."), _("\
16121 This setting chooses how GDB will do a dynamic printf.\n\
16122 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16123 console, as with the \"printf\" command.\n\
16124 If the value is \"call\", the print is done by calling a function in your\n\
16125 program; by default printf(), but you can choose a different function or\n\
16126 output stream by setting dprintf-function and dprintf-channel."),
16127                         update_dprintf_commands, NULL,
16128                         &setlist, &showlist);
16129
16130   dprintf_function = xstrdup ("printf");
16131   add_setshow_string_cmd ("dprintf-function", class_support,
16132                           &dprintf_function, _("\
16133 Set the function to use for dynamic printf"), _("\
16134 Show the function to use for dynamic printf"), NULL,
16135                           update_dprintf_commands, NULL,
16136                           &setlist, &showlist);
16137
16138   dprintf_channel = xstrdup ("");
16139   add_setshow_string_cmd ("dprintf-channel", class_support,
16140                           &dprintf_channel, _("\
16141 Set the channel to use for dynamic printf"), _("\
16142 Show the channel to use for dynamic printf"), NULL,
16143                           update_dprintf_commands, NULL,
16144                           &setlist, &showlist);
16145
16146   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16147                            &disconnected_dprintf, _("\
16148 Set whether dprintf continues after GDB disconnects."), _("\
16149 Show whether dprintf continues after GDB disconnects."), _("\
16150 Use this to let dprintf commands continue to hit and produce output\n\
16151 even if GDB disconnects or detaches from the target."),
16152                            NULL,
16153                            NULL,
16154                            &setlist, &showlist);
16155
16156   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16157 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16158 (target agent only) This is useful for formatted output in user-defined commands."));
16159
16160   automatic_hardware_breakpoints = 1;
16161
16162   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16163   observer_attach_thread_exit (remove_threaded_breakpoints);
16164 }