Constify some commands in breakpoint.c
[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 "gdb.h"
48 #include "ui-out.h"
49 #include "cli/cli-script.h"
50 #include "block.h"
51 #include "solib.h"
52 #include "solist.h"
53 #include "observer.h"
54 #include "memattr.h"
55 #include "ada-lang.h"
56 #include "top.h"
57 #include "valprint.h"
58 #include "jit.h"
59 #include "parser-defs.h"
60 #include "gdb_regex.h"
61 #include "probe.h"
62 #include "cli/cli-utils.h"
63 #include "continuations.h"
64 #include "stack.h"
65 #include "skip.h"
66 #include "ax-gdb.h"
67 #include "dummy-frame.h"
68 #include "interps.h"
69 #include "format.h"
70 #include "thread-fsm.h"
71 #include "tid-parse.h"
72
73 /* readline include files */
74 #include "readline/readline.h"
75 #include "readline/history.h"
76
77 /* readline defines this.  */
78 #undef savestring
79
80 #include "mi/mi-common.h"
81 #include "extension.h"
82 #include <algorithm>
83 #include "progspace-and-thread.h"
84 #include "common/array-view.h"
85 #include "common/gdb_optional.h"
86
87 /* Enums for exception-handling support.  */
88 enum exception_event_kind
89 {
90   EX_EVENT_THROW,
91   EX_EVENT_RETHROW,
92   EX_EVENT_CATCH
93 };
94
95 /* Prototypes for local functions.  */
96
97 static void disable_command (char *, int);
98
99 static void enable_command (char *, int);
100
101 static void map_breakpoint_numbers (const char *,
102                                     gdb::function_view<void (breakpoint *)>);
103
104 static void ignore_command (char *, int);
105
106 static int breakpoint_re_set_one (void *);
107
108 static void breakpoint_re_set_default (struct breakpoint *);
109
110 static void
111   create_sals_from_location_default (const struct event_location *location,
112                                      struct linespec_result *canonical,
113                                      enum bptype type_wanted);
114
115 static void create_breakpoints_sal_default (struct gdbarch *,
116                                             struct linespec_result *,
117                                             gdb::unique_xmalloc_ptr<char>,
118                                             gdb::unique_xmalloc_ptr<char>,
119                                             enum bptype,
120                                             enum bpdisp, int, int,
121                                             int,
122                                             const struct breakpoint_ops *,
123                                             int, int, int, unsigned);
124
125 static std::vector<symtab_and_line> decode_location_default
126   (struct breakpoint *b, const struct event_location *location,
127    struct program_space *search_pspace);
128
129 static void clear_command (char *, int);
130
131 static void catch_command (char *, int);
132
133 static int can_use_hardware_watchpoint (struct value *);
134
135 static void mention (struct breakpoint *);
136
137 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
138                                                                enum bptype,
139                                                                const struct breakpoint_ops *);
140 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
141                                                        const struct symtab_and_line *);
142
143 /* This function is used in gdbtk sources and thus can not be made
144    static.  */
145 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
146                                        struct symtab_and_line,
147                                        enum bptype,
148                                        const struct breakpoint_ops *);
149
150 static struct breakpoint *
151   momentary_breakpoint_from_master (struct breakpoint *orig,
152                                     enum bptype type,
153                                     const struct breakpoint_ops *ops,
154                                     int loc_enabled);
155
156 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
157
158 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
159                                             CORE_ADDR bpaddr,
160                                             enum bptype bptype);
161
162 static void describe_other_breakpoints (struct gdbarch *,
163                                         struct program_space *, CORE_ADDR,
164                                         struct obj_section *, int);
165
166 static int watchpoint_locations_match (struct bp_location *loc1,
167                                        struct bp_location *loc2);
168
169 static int breakpoint_location_address_match (struct bp_location *bl,
170                                               struct address_space *aspace,
171                                               CORE_ADDR addr);
172
173 static int breakpoint_location_address_range_overlap (struct bp_location *,
174                                                       struct address_space *,
175                                                       CORE_ADDR, int);
176
177 static void info_breakpoints_command (char *, int);
178
179 static void info_watchpoints_command (char *, int);
180
181 static int breakpoint_cond_eval (void *);
182
183 static void cleanup_executing_breakpoints (void *);
184
185 static void commands_command (char *, int);
186
187 static void condition_command (char *, int);
188
189 static int remove_breakpoint (struct bp_location *);
190 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
191
192 static enum print_stop_action print_bp_stop_message (bpstat bs);
193
194 static int watchpoint_check (void *);
195
196 static int hw_breakpoint_used_count (void);
197
198 static int hw_watchpoint_use_count (struct breakpoint *);
199
200 static int hw_watchpoint_used_count_others (struct breakpoint *except,
201                                             enum bptype type,
202                                             int *other_type_used);
203
204 static void hbreak_command (char *, int);
205
206 static void thbreak_command (char *, int);
207
208 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
209                                     int count);
210
211 static void stop_command (char *arg, int from_tty);
212
213 static void tcatch_command (char *arg, int from_tty);
214
215 static void free_bp_location (struct bp_location *loc);
216 static void incref_bp_location (struct bp_location *loc);
217 static void decref_bp_location (struct bp_location **loc);
218
219 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
220
221 /* update_global_location_list's modes of operation wrt to whether to
222    insert locations now.  */
223 enum ugll_insert_mode
224 {
225   /* Don't insert any breakpoint locations into the inferior, only
226      remove already-inserted locations that no longer should be
227      inserted.  Functions that delete a breakpoint or breakpoints
228      should specify this mode, so that deleting a breakpoint doesn't
229      have the side effect of inserting the locations of other
230      breakpoints that are marked not-inserted, but should_be_inserted
231      returns true on them.
232
233      This behavior is useful is situations close to tear-down -- e.g.,
234      after an exec, while the target still has execution, but
235      breakpoint shadows of the previous executable image should *NOT*
236      be restored to the new image; or before detaching, where the
237      target still has execution and wants to delete breakpoints from
238      GDB's lists, and all breakpoints had already been removed from
239      the inferior.  */
240   UGLL_DONT_INSERT,
241
242   /* May insert breakpoints iff breakpoints_should_be_inserted_now
243      claims breakpoints should be inserted now.  */
244   UGLL_MAY_INSERT,
245
246   /* Insert locations now, irrespective of
247      breakpoints_should_be_inserted_now.  E.g., say all threads are
248      stopped right now, and the user did "continue".  We need to
249      insert breakpoints _before_ resuming the target, but
250      UGLL_MAY_INSERT wouldn't insert them, because
251      breakpoints_should_be_inserted_now returns false at that point,
252      as no thread is running yet.  */
253   UGLL_INSERT
254 };
255
256 static void update_global_location_list (enum ugll_insert_mode);
257
258 static void update_global_location_list_nothrow (enum ugll_insert_mode);
259
260 static int is_hardware_watchpoint (const struct breakpoint *bpt);
261
262 static void insert_breakpoint_locations (void);
263
264 static void info_tracepoints_command (char *, int);
265
266 static void enable_trace_command (char *, int);
267
268 static void disable_trace_command (char *, int);
269
270 static void trace_pass_command (char *, int);
271
272 static void set_tracepoint_count (int num);
273
274 static int is_masked_watchpoint (const struct breakpoint *b);
275
276 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
277
278 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
279    otherwise.  */
280
281 static int strace_marker_p (struct breakpoint *b);
282
283 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
284    that are implemented on top of software or hardware breakpoints
285    (user breakpoints, internal and momentary breakpoints, etc.).  */
286 static struct breakpoint_ops bkpt_base_breakpoint_ops;
287
288 /* Internal breakpoints class type.  */
289 static struct breakpoint_ops internal_breakpoint_ops;
290
291 /* Momentary breakpoints class type.  */
292 static struct breakpoint_ops momentary_breakpoint_ops;
293
294 /* The breakpoint_ops structure to be used in regular user created
295    breakpoints.  */
296 struct breakpoint_ops bkpt_breakpoint_ops;
297
298 /* Breakpoints set on probes.  */
299 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
300
301 /* Dynamic printf class type.  */
302 struct breakpoint_ops dprintf_breakpoint_ops;
303
304 /* The style in which to perform a dynamic printf.  This is a user
305    option because different output options have different tradeoffs;
306    if GDB does the printing, there is better error handling if there
307    is a problem with any of the arguments, but using an inferior
308    function lets you have special-purpose printers and sending of
309    output to the same place as compiled-in print functions.  */
310
311 static const char dprintf_style_gdb[] = "gdb";
312 static const char dprintf_style_call[] = "call";
313 static const char dprintf_style_agent[] = "agent";
314 static const char *const dprintf_style_enums[] = {
315   dprintf_style_gdb,
316   dprintf_style_call,
317   dprintf_style_agent,
318   NULL
319 };
320 static const char *dprintf_style = dprintf_style_gdb;
321
322 /* The function to use for dynamic printf if the preferred style is to
323    call into the inferior.  The value is simply a string that is
324    copied into the command, so it can be anything that GDB can
325    evaluate to a callable address, not necessarily a function name.  */
326
327 static char *dprintf_function;
328
329 /* The channel to use for dynamic printf if the preferred style is to
330    call into the inferior; if a nonempty string, it will be passed to
331    the call as the first argument, with the format string as the
332    second.  As with the dprintf function, this can be anything that
333    GDB knows how to evaluate, so in addition to common choices like
334    "stderr", this could be an app-specific expression like
335    "mystreams[curlogger]".  */
336
337 static char *dprintf_channel;
338
339 /* True if dprintf commands should continue to operate even if GDB
340    has disconnected.  */
341 static int disconnected_dprintf = 1;
342
343 struct command_line *
344 breakpoint_commands (struct breakpoint *b)
345 {
346   return b->commands ? b->commands.get () : NULL;
347 }
348
349 /* Flag indicating that a command has proceeded the inferior past the
350    current breakpoint.  */
351
352 static int breakpoint_proceeded;
353
354 const char *
355 bpdisp_text (enum bpdisp disp)
356 {
357   /* NOTE: the following values are a part of MI protocol and
358      represent values of 'disp' field returned when inferior stops at
359      a breakpoint.  */
360   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
361
362   return bpdisps[(int) disp];
363 }
364
365 /* Prototypes for exported functions.  */
366 /* If FALSE, gdb will not use hardware support for watchpoints, even
367    if such is available.  */
368 static int can_use_hw_watchpoints;
369
370 static void
371 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
372                              struct cmd_list_element *c,
373                              const char *value)
374 {
375   fprintf_filtered (file,
376                     _("Debugger's willingness to use "
377                       "watchpoint hardware is %s.\n"),
378                     value);
379 }
380
381 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
382    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
383    for unrecognized breakpoint locations.
384    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
385 static enum auto_boolean pending_break_support;
386 static void
387 show_pending_break_support (struct ui_file *file, int from_tty,
388                             struct cmd_list_element *c,
389                             const char *value)
390 {
391   fprintf_filtered (file,
392                     _("Debugger's behavior regarding "
393                       "pending breakpoints is %s.\n"),
394                     value);
395 }
396
397 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
398    set with "break" but falling in read-only memory.
399    If 0, gdb will warn about such breakpoints, but won't automatically
400    use hardware breakpoints.  */
401 static int automatic_hardware_breakpoints;
402 static void
403 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
404                                      struct cmd_list_element *c,
405                                      const char *value)
406 {
407   fprintf_filtered (file,
408                     _("Automatic usage of hardware breakpoints is %s.\n"),
409                     value);
410 }
411
412 /* If on, GDB keeps breakpoints inserted even if the inferior is
413    stopped, and immediately inserts any new breakpoints as soon as
414    they're created.  If off (default), GDB keeps breakpoints off of
415    the target as long as possible.  That is, it delays inserting
416    breakpoints until the next resume, and removes them again when the
417    target fully stops.  This is a bit safer in case GDB crashes while
418    processing user input.  */
419 static int always_inserted_mode = 0;
420
421 static void
422 show_always_inserted_mode (struct ui_file *file, int from_tty,
423                      struct cmd_list_element *c, const char *value)
424 {
425   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
426                     value);
427 }
428
429 /* See breakpoint.h.  */
430
431 int
432 breakpoints_should_be_inserted_now (void)
433 {
434   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
435     {
436       /* If breakpoints are global, they should be inserted even if no
437          thread under gdb's control is running, or even if there are
438          no threads under GDB's control yet.  */
439       return 1;
440     }
441   else if (target_has_execution)
442     {
443       struct thread_info *tp;
444
445       if (always_inserted_mode)
446         {
447           /* The user wants breakpoints inserted even if all threads
448              are stopped.  */
449           return 1;
450         }
451
452       if (threads_are_executing ())
453         return 1;
454
455       /* Don't remove breakpoints yet if, even though all threads are
456          stopped, we still have events to process.  */
457       ALL_NON_EXITED_THREADS (tp)
458         if (tp->resumed
459             && tp->suspend.waitstatus_pending_p)
460           return 1;
461     }
462   return 0;
463 }
464
465 static const char condition_evaluation_both[] = "host or target";
466
467 /* Modes for breakpoint condition evaluation.  */
468 static const char condition_evaluation_auto[] = "auto";
469 static const char condition_evaluation_host[] = "host";
470 static const char condition_evaluation_target[] = "target";
471 static const char *const condition_evaluation_enums[] = {
472   condition_evaluation_auto,
473   condition_evaluation_host,
474   condition_evaluation_target,
475   NULL
476 };
477
478 /* Global that holds the current mode for breakpoint condition evaluation.  */
479 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
480
481 /* Global that we use to display information to the user (gets its value from
482    condition_evaluation_mode_1.  */
483 static const char *condition_evaluation_mode = condition_evaluation_auto;
484
485 /* Translate a condition evaluation mode MODE into either "host"
486    or "target".  This is used mostly to translate from "auto" to the
487    real setting that is being used.  It returns the translated
488    evaluation mode.  */
489
490 static const char *
491 translate_condition_evaluation_mode (const char *mode)
492 {
493   if (mode == condition_evaluation_auto)
494     {
495       if (target_supports_evaluation_of_breakpoint_conditions ())
496         return condition_evaluation_target;
497       else
498         return condition_evaluation_host;
499     }
500   else
501     return mode;
502 }
503
504 /* Discovers what condition_evaluation_auto translates to.  */
505
506 static const char *
507 breakpoint_condition_evaluation_mode (void)
508 {
509   return translate_condition_evaluation_mode (condition_evaluation_mode);
510 }
511
512 /* Return true if GDB should evaluate breakpoint conditions or false
513    otherwise.  */
514
515 static int
516 gdb_evaluates_breakpoint_condition_p (void)
517 {
518   const char *mode = breakpoint_condition_evaluation_mode ();
519
520   return (mode == condition_evaluation_host);
521 }
522
523 /* Are we executing breakpoint commands?  */
524 static int executing_breakpoint_commands;
525
526 /* Are overlay event breakpoints enabled? */
527 static int overlay_events_enabled;
528
529 /* See description in breakpoint.h. */
530 int target_exact_watchpoints = 0;
531
532 /* Walk the following statement or block through all breakpoints.
533    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
534    current breakpoint.  */
535
536 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
537
538 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
539         for (B = breakpoint_chain;      \
540              B ? (TMP=B->next, 1): 0;   \
541              B = TMP)
542
543 /* Similar iterator for the low-level breakpoints.  SAFE variant is
544    not provided so update_global_location_list must not be called
545    while executing the block of ALL_BP_LOCATIONS.  */
546
547 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
548         for (BP_TMP = bp_locations;                                     \
549              BP_TMP < bp_locations + bp_locations_count && (B = *BP_TMP);\
550              BP_TMP++)
551
552 /* Iterates through locations with address ADDRESS for the currently selected
553    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
554    to where the loop should start from.
555    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
556    appropriate location to start with.  */
557
558 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
559         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
560              BP_LOCP_TMP = BP_LOCP_START;                               \
561              BP_LOCP_START                                              \
562              && (BP_LOCP_TMP < bp_locations + bp_locations_count        \
563              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
564              BP_LOCP_TMP++)
565
566 /* Iterator for tracepoints only.  */
567
568 #define ALL_TRACEPOINTS(B)  \
569   for (B = breakpoint_chain; B; B = B->next)  \
570     if (is_tracepoint (B))
571
572 /* Chains of all breakpoints defined.  */
573
574 struct breakpoint *breakpoint_chain;
575
576 /* Array is sorted by bp_locations_compare - primarily by the ADDRESS.  */
577
578 static struct bp_location **bp_locations;
579
580 /* Number of elements of BP_LOCATIONS.  */
581
582 static unsigned bp_locations_count;
583
584 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
585    ADDRESS for the current elements of BP_LOCATIONS which get a valid
586    result from bp_location_has_shadow.  You can use it for roughly
587    limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
588    an address you need to read.  */
589
590 static CORE_ADDR bp_locations_placed_address_before_address_max;
591
592 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
593    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
594    BP_LOCATIONS which get a valid result from bp_location_has_shadow.
595    You can use it for roughly limiting the subrange of BP_LOCATIONS to
596    scan for shadow bytes for an address you need to read.  */
597
598 static CORE_ADDR bp_locations_shadow_len_after_address_max;
599
600 /* The locations that no longer correspond to any breakpoint, unlinked
601    from the bp_locations array, but for which a hit may still be
602    reported by a target.  */
603 VEC(bp_location_p) *moribund_locations = NULL;
604
605 /* Number of last breakpoint made.  */
606
607 static int breakpoint_count;
608
609 /* The value of `breakpoint_count' before the last command that
610    created breakpoints.  If the last (break-like) command created more
611    than one breakpoint, then the difference between BREAKPOINT_COUNT
612    and PREV_BREAKPOINT_COUNT is more than one.  */
613 static int prev_breakpoint_count;
614
615 /* Number of last tracepoint made.  */
616
617 static int tracepoint_count;
618
619 static struct cmd_list_element *breakpoint_set_cmdlist;
620 static struct cmd_list_element *breakpoint_show_cmdlist;
621 struct cmd_list_element *save_cmdlist;
622
623 /* See declaration at breakpoint.h.  */
624
625 struct breakpoint *
626 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
627                     void *user_data)
628 {
629   struct breakpoint *b = NULL;
630
631   ALL_BREAKPOINTS (b)
632     {
633       if (func (b, user_data) != 0)
634         break;
635     }
636
637   return b;
638 }
639
640 /* Return whether a breakpoint is an active enabled breakpoint.  */
641 static int
642 breakpoint_enabled (struct breakpoint *b)
643 {
644   return (b->enable_state == bp_enabled);
645 }
646
647 /* Set breakpoint count to NUM.  */
648
649 static void
650 set_breakpoint_count (int num)
651 {
652   prev_breakpoint_count = breakpoint_count;
653   breakpoint_count = num;
654   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
655 }
656
657 /* Used by `start_rbreak_breakpoints' below, to record the current
658    breakpoint count before "rbreak" creates any breakpoint.  */
659 static int rbreak_start_breakpoint_count;
660
661 /* Called at the start an "rbreak" command to record the first
662    breakpoint made.  */
663
664 void
665 start_rbreak_breakpoints (void)
666 {
667   rbreak_start_breakpoint_count = breakpoint_count;
668 }
669
670 /* Called at the end of an "rbreak" command to record the last
671    breakpoint made.  */
672
673 void
674 end_rbreak_breakpoints (void)
675 {
676   prev_breakpoint_count = rbreak_start_breakpoint_count;
677 }
678
679 /* Used in run_command to zero the hit count when a new run starts.  */
680
681 void
682 clear_breakpoint_hit_counts (void)
683 {
684   struct breakpoint *b;
685
686   ALL_BREAKPOINTS (b)
687     b->hit_count = 0;
688 }
689
690 \f
691 /* Return the breakpoint with the specified number, or NULL
692    if the number does not refer to an existing breakpoint.  */
693
694 struct breakpoint *
695 get_breakpoint (int num)
696 {
697   struct breakpoint *b;
698
699   ALL_BREAKPOINTS (b)
700     if (b->number == num)
701       return b;
702   
703   return NULL;
704 }
705
706 \f
707
708 /* Mark locations as "conditions have changed" in case the target supports
709    evaluating conditions on its side.  */
710
711 static void
712 mark_breakpoint_modified (struct breakpoint *b)
713 {
714   struct bp_location *loc;
715
716   /* This is only meaningful if the target is
717      evaluating conditions and if the user has
718      opted for condition evaluation on the target's
719      side.  */
720   if (gdb_evaluates_breakpoint_condition_p ()
721       || !target_supports_evaluation_of_breakpoint_conditions ())
722     return;
723
724   if (!is_breakpoint (b))
725     return;
726
727   for (loc = b->loc; loc; loc = loc->next)
728     loc->condition_changed = condition_modified;
729 }
730
731 /* Mark location as "conditions have changed" in case the target supports
732    evaluating conditions on its side.  */
733
734 static void
735 mark_breakpoint_location_modified (struct bp_location *loc)
736 {
737   /* This is only meaningful if the target is
738      evaluating conditions and if the user has
739      opted for condition evaluation on the target's
740      side.  */
741   if (gdb_evaluates_breakpoint_condition_p ()
742       || !target_supports_evaluation_of_breakpoint_conditions ())
743
744     return;
745
746   if (!is_breakpoint (loc->owner))
747     return;
748
749   loc->condition_changed = condition_modified;
750 }
751
752 /* Sets the condition-evaluation mode using the static global
753    condition_evaluation_mode.  */
754
755 static void
756 set_condition_evaluation_mode (char *args, int from_tty,
757                                struct cmd_list_element *c)
758 {
759   const char *old_mode, *new_mode;
760
761   if ((condition_evaluation_mode_1 == condition_evaluation_target)
762       && !target_supports_evaluation_of_breakpoint_conditions ())
763     {
764       condition_evaluation_mode_1 = condition_evaluation_mode;
765       warning (_("Target does not support breakpoint condition evaluation.\n"
766                  "Using host evaluation mode instead."));
767       return;
768     }
769
770   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
771   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
772
773   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
774      settings was "auto".  */
775   condition_evaluation_mode = condition_evaluation_mode_1;
776
777   /* Only update the mode if the user picked a different one.  */
778   if (new_mode != old_mode)
779     {
780       struct bp_location *loc, **loc_tmp;
781       /* If the user switched to a different evaluation mode, we
782          need to synch the changes with the target as follows:
783
784          "host" -> "target": Send all (valid) conditions to the target.
785          "target" -> "host": Remove all the conditions from the target.
786       */
787
788       if (new_mode == condition_evaluation_target)
789         {
790           /* Mark everything modified and synch conditions with the
791              target.  */
792           ALL_BP_LOCATIONS (loc, loc_tmp)
793             mark_breakpoint_location_modified (loc);
794         }
795       else
796         {
797           /* Manually mark non-duplicate locations to synch conditions
798              with the target.  We do this to remove all the conditions the
799              target knows about.  */
800           ALL_BP_LOCATIONS (loc, loc_tmp)
801             if (is_breakpoint (loc->owner) && loc->inserted)
802               loc->needs_update = 1;
803         }
804
805       /* Do the update.  */
806       update_global_location_list (UGLL_MAY_INSERT);
807     }
808
809   return;
810 }
811
812 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
813    what "auto" is translating to.  */
814
815 static void
816 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
817                                 struct cmd_list_element *c, const char *value)
818 {
819   if (condition_evaluation_mode == condition_evaluation_auto)
820     fprintf_filtered (file,
821                       _("Breakpoint condition evaluation "
822                         "mode is %s (currently %s).\n"),
823                       value,
824                       breakpoint_condition_evaluation_mode ());
825   else
826     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
827                       value);
828 }
829
830 /* A comparison function for bp_location AP and BP that is used by
831    bsearch.  This comparison function only cares about addresses, unlike
832    the more general bp_locations_compare function.  */
833
834 static int
835 bp_locations_compare_addrs (const void *ap, const void *bp)
836 {
837   const struct bp_location *a = *(const struct bp_location **) ap;
838   const struct bp_location *b = *(const struct bp_location **) bp;
839
840   if (a->address == b->address)
841     return 0;
842   else
843     return ((a->address > b->address) - (a->address < b->address));
844 }
845
846 /* Helper function to skip all bp_locations with addresses
847    less than ADDRESS.  It returns the first bp_location that
848    is greater than or equal to ADDRESS.  If none is found, just
849    return NULL.  */
850
851 static struct bp_location **
852 get_first_locp_gte_addr (CORE_ADDR address)
853 {
854   struct bp_location dummy_loc;
855   struct bp_location *dummy_locp = &dummy_loc;
856   struct bp_location **locp_found = NULL;
857
858   /* Initialize the dummy location's address field.  */
859   dummy_loc.address = address;
860
861   /* Find a close match to the first location at ADDRESS.  */
862   locp_found = ((struct bp_location **)
863                 bsearch (&dummy_locp, bp_locations, bp_locations_count,
864                          sizeof (struct bp_location **),
865                          bp_locations_compare_addrs));
866
867   /* Nothing was found, nothing left to do.  */
868   if (locp_found == NULL)
869     return NULL;
870
871   /* We may have found a location that is at ADDRESS but is not the first in the
872      location's list.  Go backwards (if possible) and locate the first one.  */
873   while ((locp_found - 1) >= bp_locations
874          && (*(locp_found - 1))->address == address)
875     locp_found--;
876
877   return locp_found;
878 }
879
880 void
881 set_breakpoint_condition (struct breakpoint *b, const char *exp,
882                           int from_tty)
883 {
884   xfree (b->cond_string);
885   b->cond_string = NULL;
886
887   if (is_watchpoint (b))
888     {
889       struct watchpoint *w = (struct watchpoint *) b;
890
891       w->cond_exp.reset ();
892     }
893   else
894     {
895       struct bp_location *loc;
896
897       for (loc = b->loc; loc; loc = loc->next)
898         {
899           loc->cond.reset ();
900
901           /* No need to free the condition agent expression
902              bytecode (if we have one).  We will handle this
903              when we go through update_global_location_list.  */
904         }
905     }
906
907   if (*exp == 0)
908     {
909       if (from_tty)
910         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
911     }
912   else
913     {
914       const char *arg = exp;
915
916       /* I don't know if it matters whether this is the string the user
917          typed in or the decompiled expression.  */
918       b->cond_string = xstrdup (arg);
919       b->condition_not_parsed = 0;
920
921       if (is_watchpoint (b))
922         {
923           struct watchpoint *w = (struct watchpoint *) b;
924
925           innermost_block = NULL;
926           arg = exp;
927           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
928           if (*arg)
929             error (_("Junk at end of expression"));
930           w->cond_exp_valid_block = innermost_block;
931         }
932       else
933         {
934           struct bp_location *loc;
935
936           for (loc = b->loc; loc; loc = loc->next)
937             {
938               arg = exp;
939               loc->cond =
940                 parse_exp_1 (&arg, loc->address,
941                              block_for_pc (loc->address), 0);
942               if (*arg)
943                 error (_("Junk at end of expression"));
944             }
945         }
946     }
947   mark_breakpoint_modified (b);
948
949   observer_notify_breakpoint_modified (b);
950 }
951
952 /* Completion for the "condition" command.  */
953
954 static void
955 condition_completer (struct cmd_list_element *cmd,
956                      completion_tracker &tracker,
957                      const char *text, const char *word)
958 {
959   const char *space;
960
961   text = skip_spaces (text);
962   space = skip_to_space (text);
963   if (*space == '\0')
964     {
965       int len;
966       struct breakpoint *b;
967       VEC (char_ptr) *result = NULL;
968
969       if (text[0] == '$')
970         {
971           /* We don't support completion of history indices.  */
972           if (!isdigit (text[1]))
973             complete_internalvar (tracker, &text[1]);
974           return;
975         }
976
977       /* We're completing the breakpoint number.  */
978       len = strlen (text);
979
980       ALL_BREAKPOINTS (b)
981         {
982           char number[50];
983
984           xsnprintf (number, sizeof (number), "%d", b->number);
985
986           if (strncmp (number, text, len) == 0)
987             {
988               gdb::unique_xmalloc_ptr<char> copy (xstrdup (number));
989               tracker.add_completion (std::move (copy));
990             }
991         }
992
993       return;
994     }
995
996   /* We're completing the expression part.  */
997   text = skip_spaces (space);
998   expression_completer (cmd, tracker, text, word);
999 }
1000
1001 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1002
1003 static void
1004 condition_command (char *arg, int from_tty)
1005 {
1006   struct breakpoint *b;
1007   char *p;
1008   int bnum;
1009
1010   if (arg == 0)
1011     error_no_arg (_("breakpoint number"));
1012
1013   p = arg;
1014   bnum = get_number (&p);
1015   if (bnum == 0)
1016     error (_("Bad breakpoint argument: '%s'"), arg);
1017
1018   ALL_BREAKPOINTS (b)
1019     if (b->number == bnum)
1020       {
1021         /* Check if this breakpoint has a "stop" method implemented in an
1022            extension language.  This method and conditions entered into GDB
1023            from the CLI are mutually exclusive.  */
1024         const struct extension_language_defn *extlang
1025           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1026
1027         if (extlang != NULL)
1028           {
1029             error (_("Only one stop condition allowed.  There is currently"
1030                      " a %s stop condition defined for this breakpoint."),
1031                    ext_lang_capitalized_name (extlang));
1032           }
1033         set_breakpoint_condition (b, p, from_tty);
1034
1035         if (is_breakpoint (b))
1036           update_global_location_list (UGLL_MAY_INSERT);
1037
1038         return;
1039       }
1040
1041   error (_("No breakpoint number %d."), bnum);
1042 }
1043
1044 /* Check that COMMAND do not contain commands that are suitable
1045    only for tracepoints and not suitable for ordinary breakpoints.
1046    Throw if any such commands is found.  */
1047
1048 static void
1049 check_no_tracepoint_commands (struct command_line *commands)
1050 {
1051   struct command_line *c;
1052
1053   for (c = commands; c; c = c->next)
1054     {
1055       int i;
1056
1057       if (c->control_type == while_stepping_control)
1058         error (_("The 'while-stepping' command can "
1059                  "only be used for tracepoints"));
1060
1061       for (i = 0; i < c->body_count; ++i)
1062         check_no_tracepoint_commands ((c->body_list)[i]);
1063
1064       /* Not that command parsing removes leading whitespace and comment
1065          lines and also empty lines.  So, we only need to check for
1066          command directly.  */
1067       if (strstr (c->line, "collect ") == c->line)
1068         error (_("The 'collect' command can only be used for tracepoints"));
1069
1070       if (strstr (c->line, "teval ") == c->line)
1071         error (_("The 'teval' command can only be used for tracepoints"));
1072     }
1073 }
1074
1075 struct longjmp_breakpoint : public breakpoint
1076 {
1077   ~longjmp_breakpoint () override;
1078 };
1079
1080 /* Encapsulate tests for different types of tracepoints.  */
1081
1082 static bool
1083 is_tracepoint_type (bptype type)
1084 {
1085   return (type == bp_tracepoint
1086           || type == bp_fast_tracepoint
1087           || type == bp_static_tracepoint);
1088 }
1089
1090 static bool
1091 is_longjmp_type (bptype type)
1092 {
1093   return type == bp_longjmp || type == bp_exception;
1094 }
1095
1096 int
1097 is_tracepoint (const struct breakpoint *b)
1098 {
1099   return is_tracepoint_type (b->type);
1100 }
1101
1102 /* Factory function to create an appropriate instance of breakpoint given
1103    TYPE.  */
1104
1105 static std::unique_ptr<breakpoint>
1106 new_breakpoint_from_type (bptype type)
1107 {
1108   breakpoint *b;
1109
1110   if (is_tracepoint_type (type))
1111     b = new tracepoint ();
1112   else if (is_longjmp_type (type))
1113     b = new longjmp_breakpoint ();
1114   else
1115     b = new breakpoint ();
1116
1117   return std::unique_ptr<breakpoint> (b);
1118 }
1119
1120 /* A helper function that validates that COMMANDS are valid for a
1121    breakpoint.  This function will throw an exception if a problem is
1122    found.  */
1123
1124 static void
1125 validate_commands_for_breakpoint (struct breakpoint *b,
1126                                   struct command_line *commands)
1127 {
1128   if (is_tracepoint (b))
1129     {
1130       struct tracepoint *t = (struct tracepoint *) b;
1131       struct command_line *c;
1132       struct command_line *while_stepping = 0;
1133
1134       /* Reset the while-stepping step count.  The previous commands
1135          might have included a while-stepping action, while the new
1136          ones might not.  */
1137       t->step_count = 0;
1138
1139       /* We need to verify that each top-level element of commands is
1140          valid for tracepoints, that there's at most one
1141          while-stepping element, and that the while-stepping's body
1142          has valid tracing commands excluding nested while-stepping.
1143          We also need to validate the tracepoint action line in the
1144          context of the tracepoint --- validate_actionline actually
1145          has side effects, like setting the tracepoint's
1146          while-stepping STEP_COUNT, in addition to checking if the
1147          collect/teval actions parse and make sense in the
1148          tracepoint's context.  */
1149       for (c = commands; c; c = c->next)
1150         {
1151           if (c->control_type == while_stepping_control)
1152             {
1153               if (b->type == bp_fast_tracepoint)
1154                 error (_("The 'while-stepping' command "
1155                          "cannot be used for fast tracepoint"));
1156               else if (b->type == bp_static_tracepoint)
1157                 error (_("The 'while-stepping' command "
1158                          "cannot be used for static tracepoint"));
1159
1160               if (while_stepping)
1161                 error (_("The 'while-stepping' command "
1162                          "can be used only once"));
1163               else
1164                 while_stepping = c;
1165             }
1166
1167           validate_actionline (c->line, b);
1168         }
1169       if (while_stepping)
1170         {
1171           struct command_line *c2;
1172
1173           gdb_assert (while_stepping->body_count == 1);
1174           c2 = while_stepping->body_list[0];
1175           for (; c2; c2 = c2->next)
1176             {
1177               if (c2->control_type == while_stepping_control)
1178                 error (_("The 'while-stepping' command cannot be nested"));
1179             }
1180         }
1181     }
1182   else
1183     {
1184       check_no_tracepoint_commands (commands);
1185     }
1186 }
1187
1188 /* Return a vector of all the static tracepoints set at ADDR.  The
1189    caller is responsible for releasing the vector.  */
1190
1191 VEC(breakpoint_p) *
1192 static_tracepoints_here (CORE_ADDR addr)
1193 {
1194   struct breakpoint *b;
1195   VEC(breakpoint_p) *found = 0;
1196   struct bp_location *loc;
1197
1198   ALL_BREAKPOINTS (b)
1199     if (b->type == bp_static_tracepoint)
1200       {
1201         for (loc = b->loc; loc; loc = loc->next)
1202           if (loc->address == addr)
1203             VEC_safe_push(breakpoint_p, found, b);
1204       }
1205
1206   return found;
1207 }
1208
1209 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1210    validate that only allowed commands are included.  */
1211
1212 void
1213 breakpoint_set_commands (struct breakpoint *b, 
1214                          command_line_up &&commands)
1215 {
1216   validate_commands_for_breakpoint (b, commands.get ());
1217
1218   b->commands = std::move (commands);
1219   observer_notify_breakpoint_modified (b);
1220 }
1221
1222 /* Set the internal `silent' flag on the breakpoint.  Note that this
1223    is not the same as the "silent" that may appear in the breakpoint's
1224    commands.  */
1225
1226 void
1227 breakpoint_set_silent (struct breakpoint *b, int silent)
1228 {
1229   int old_silent = b->silent;
1230
1231   b->silent = silent;
1232   if (old_silent != silent)
1233     observer_notify_breakpoint_modified (b);
1234 }
1235
1236 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1237    breakpoint work for any thread.  */
1238
1239 void
1240 breakpoint_set_thread (struct breakpoint *b, int thread)
1241 {
1242   int old_thread = b->thread;
1243
1244   b->thread = thread;
1245   if (old_thread != thread)
1246     observer_notify_breakpoint_modified (b);
1247 }
1248
1249 /* Set the task for this breakpoint.  If TASK is 0, make the
1250    breakpoint work for any task.  */
1251
1252 void
1253 breakpoint_set_task (struct breakpoint *b, int task)
1254 {
1255   int old_task = b->task;
1256
1257   b->task = task;
1258   if (old_task != task)
1259     observer_notify_breakpoint_modified (b);
1260 }
1261
1262 void
1263 check_tracepoint_command (char *line, void *closure)
1264 {
1265   struct breakpoint *b = (struct breakpoint *) closure;
1266
1267   validate_actionline (line, b);
1268 }
1269
1270 static void
1271 commands_command_1 (const char *arg, int from_tty,
1272                     struct command_line *control)
1273 {
1274   counted_command_line cmd;
1275
1276   std::string new_arg;
1277
1278   if (arg == NULL || !*arg)
1279     {
1280       if (breakpoint_count - prev_breakpoint_count > 1)
1281         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1282                                  breakpoint_count);
1283       else if (breakpoint_count > 0)
1284         new_arg = string_printf ("%d", breakpoint_count);
1285       arg = new_arg.c_str ();
1286     }
1287
1288   map_breakpoint_numbers
1289     (arg, [&] (breakpoint *b)
1290      {
1291        if (cmd == NULL)
1292          {
1293            if (control != NULL)
1294              cmd = copy_command_lines (control->body_list[0]);
1295            else
1296              {
1297                struct cleanup *old_chain;
1298                char *str;
1299
1300                str = xstrprintf (_("Type commands for breakpoint(s) "
1301                                    "%s, one per line."),
1302                                  arg);
1303
1304                old_chain = make_cleanup (xfree, str);
1305
1306                cmd = read_command_lines (str,
1307                                          from_tty, 1,
1308                                          (is_tracepoint (b)
1309                                           ? check_tracepoint_command : 0),
1310                                          b);
1311
1312                do_cleanups (old_chain);
1313              }
1314          }
1315
1316        /* If a breakpoint was on the list more than once, we don't need to
1317           do anything.  */
1318        if (b->commands != cmd)
1319          {
1320            validate_commands_for_breakpoint (b, cmd.get ());
1321            b->commands = cmd;
1322            observer_notify_breakpoint_modified (b);
1323          }
1324      });
1325
1326   if (cmd == NULL)
1327     error (_("No breakpoints specified."));
1328 }
1329
1330 static void
1331 commands_command (char *arg, int from_tty)
1332 {
1333   commands_command_1 (arg, from_tty, NULL);
1334 }
1335
1336 /* Like commands_command, but instead of reading the commands from
1337    input stream, takes them from an already parsed command structure.
1338
1339    This is used by cli-script.c to DTRT with breakpoint commands
1340    that are part of if and while bodies.  */
1341 enum command_control_type
1342 commands_from_control_command (const char *arg, struct command_line *cmd)
1343 {
1344   commands_command_1 (arg, 0, cmd);
1345   return simple_control;
1346 }
1347
1348 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1349
1350 static int
1351 bp_location_has_shadow (struct bp_location *bl)
1352 {
1353   if (bl->loc_type != bp_loc_software_breakpoint)
1354     return 0;
1355   if (!bl->inserted)
1356     return 0;
1357   if (bl->target_info.shadow_len == 0)
1358     /* BL isn't valid, or doesn't shadow memory.  */
1359     return 0;
1360   return 1;
1361 }
1362
1363 /* Update BUF, which is LEN bytes read from the target address
1364    MEMADDR, by replacing a memory breakpoint with its shadowed
1365    contents.
1366
1367    If READBUF is not NULL, this buffer must not overlap with the of
1368    the breakpoint location's shadow_contents buffer.  Otherwise, a
1369    failed assertion internal error will be raised.  */
1370
1371 static void
1372 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1373                             const gdb_byte *writebuf_org,
1374                             ULONGEST memaddr, LONGEST len,
1375                             struct bp_target_info *target_info,
1376                             struct gdbarch *gdbarch)
1377 {
1378   /* Now do full processing of the found relevant range of elements.  */
1379   CORE_ADDR bp_addr = 0;
1380   int bp_size = 0;
1381   int bptoffset = 0;
1382
1383   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1384                                  current_program_space->aspace, 0))
1385     {
1386       /* The breakpoint is inserted in a different address space.  */
1387       return;
1388     }
1389
1390   /* Addresses and length of the part of the breakpoint that
1391      we need to copy.  */
1392   bp_addr = target_info->placed_address;
1393   bp_size = target_info->shadow_len;
1394
1395   if (bp_addr + bp_size <= memaddr)
1396     {
1397       /* The breakpoint is entirely before the chunk of memory we are
1398          reading.  */
1399       return;
1400     }
1401
1402   if (bp_addr >= memaddr + len)
1403     {
1404       /* The breakpoint is entirely after the chunk of memory we are
1405          reading.  */
1406       return;
1407     }
1408
1409   /* Offset within shadow_contents.  */
1410   if (bp_addr < memaddr)
1411     {
1412       /* Only copy the second part of the breakpoint.  */
1413       bp_size -= memaddr - bp_addr;
1414       bptoffset = memaddr - bp_addr;
1415       bp_addr = memaddr;
1416     }
1417
1418   if (bp_addr + bp_size > memaddr + len)
1419     {
1420       /* Only copy the first part of the breakpoint.  */
1421       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1422     }
1423
1424   if (readbuf != NULL)
1425     {
1426       /* Verify that the readbuf buffer does not overlap with the
1427          shadow_contents buffer.  */
1428       gdb_assert (target_info->shadow_contents >= readbuf + len
1429                   || readbuf >= (target_info->shadow_contents
1430                                  + target_info->shadow_len));
1431
1432       /* Update the read buffer with this inserted breakpoint's
1433          shadow.  */
1434       memcpy (readbuf + bp_addr - memaddr,
1435               target_info->shadow_contents + bptoffset, bp_size);
1436     }
1437   else
1438     {
1439       const unsigned char *bp;
1440       CORE_ADDR addr = target_info->reqstd_address;
1441       int placed_size;
1442
1443       /* Update the shadow with what we want to write to memory.  */
1444       memcpy (target_info->shadow_contents + bptoffset,
1445               writebuf_org + bp_addr - memaddr, bp_size);
1446
1447       /* Determine appropriate breakpoint contents and size for this
1448          address.  */
1449       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1450
1451       /* Update the final write buffer with this inserted
1452          breakpoint's INSN.  */
1453       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1454     }
1455 }
1456
1457 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1458    by replacing any memory breakpoints with their shadowed contents.
1459
1460    If READBUF is not NULL, this buffer must not overlap with any of
1461    the breakpoint location's shadow_contents buffers.  Otherwise,
1462    a failed assertion internal error will be raised.
1463
1464    The range of shadowed area by each bp_location is:
1465      bl->address - bp_locations_placed_address_before_address_max
1466      up to bl->address + bp_locations_shadow_len_after_address_max
1467    The range we were requested to resolve shadows for is:
1468      memaddr ... memaddr + len
1469    Thus the safe cutoff boundaries for performance optimization are
1470      memaddr + len <= (bl->address
1471                        - bp_locations_placed_address_before_address_max)
1472    and:
1473      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1474
1475 void
1476 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1477                         const gdb_byte *writebuf_org,
1478                         ULONGEST memaddr, LONGEST len)
1479 {
1480   /* Left boundary, right boundary and median element of our binary
1481      search.  */
1482   unsigned bc_l, bc_r, bc;
1483
1484   /* Find BC_L which is a leftmost element which may affect BUF
1485      content.  It is safe to report lower value but a failure to
1486      report higher one.  */
1487
1488   bc_l = 0;
1489   bc_r = bp_locations_count;
1490   while (bc_l + 1 < bc_r)
1491     {
1492       struct bp_location *bl;
1493
1494       bc = (bc_l + bc_r) / 2;
1495       bl = bp_locations[bc];
1496
1497       /* Check first BL->ADDRESS will not overflow due to the added
1498          constant.  Then advance the left boundary only if we are sure
1499          the BC element can in no way affect the BUF content (MEMADDR
1500          to MEMADDR + LEN range).
1501
1502          Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1503          offset so that we cannot miss a breakpoint with its shadow
1504          range tail still reaching MEMADDR.  */
1505
1506       if ((bl->address + bp_locations_shadow_len_after_address_max
1507            >= bl->address)
1508           && (bl->address + bp_locations_shadow_len_after_address_max
1509               <= memaddr))
1510         bc_l = bc;
1511       else
1512         bc_r = bc;
1513     }
1514
1515   /* Due to the binary search above, we need to make sure we pick the
1516      first location that's at BC_L's address.  E.g., if there are
1517      multiple locations at the same address, BC_L may end up pointing
1518      at a duplicate location, and miss the "master"/"inserted"
1519      location.  Say, given locations L1, L2 and L3 at addresses A and
1520      B:
1521
1522       L1@A, L2@A, L3@B, ...
1523
1524      BC_L could end up pointing at location L2, while the "master"
1525      location could be L1.  Since the `loc->inserted' flag is only set
1526      on "master" locations, we'd forget to restore the shadow of L1
1527      and L2.  */
1528   while (bc_l > 0
1529          && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1530     bc_l--;
1531
1532   /* Now do full processing of the found relevant range of elements.  */
1533
1534   for (bc = bc_l; bc < bp_locations_count; bc++)
1535   {
1536     struct bp_location *bl = bp_locations[bc];
1537
1538     /* bp_location array has BL->OWNER always non-NULL.  */
1539     if (bl->owner->type == bp_none)
1540       warning (_("reading through apparently deleted breakpoint #%d?"),
1541                bl->owner->number);
1542
1543     /* Performance optimization: any further element can no longer affect BUF
1544        content.  */
1545
1546     if (bl->address >= bp_locations_placed_address_before_address_max
1547         && memaddr + len <= (bl->address
1548                              - bp_locations_placed_address_before_address_max))
1549       break;
1550
1551     if (!bp_location_has_shadow (bl))
1552       continue;
1553
1554     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1555                                 memaddr, len, &bl->target_info, bl->gdbarch);
1556   }
1557 }
1558
1559 \f
1560
1561 /* Return true if BPT is either a software breakpoint or a hardware
1562    breakpoint.  */
1563
1564 int
1565 is_breakpoint (const struct breakpoint *bpt)
1566 {
1567   return (bpt->type == bp_breakpoint
1568           || bpt->type == bp_hardware_breakpoint
1569           || bpt->type == bp_dprintf);
1570 }
1571
1572 /* Return true if BPT is of any hardware watchpoint kind.  */
1573
1574 static int
1575 is_hardware_watchpoint (const struct breakpoint *bpt)
1576 {
1577   return (bpt->type == bp_hardware_watchpoint
1578           || bpt->type == bp_read_watchpoint
1579           || bpt->type == bp_access_watchpoint);
1580 }
1581
1582 /* Return true if BPT is of any watchpoint kind, hardware or
1583    software.  */
1584
1585 int
1586 is_watchpoint (const struct breakpoint *bpt)
1587 {
1588   return (is_hardware_watchpoint (bpt)
1589           || bpt->type == bp_watchpoint);
1590 }
1591
1592 /* Returns true if the current thread and its running state are safe
1593    to evaluate or update watchpoint B.  Watchpoints on local
1594    expressions need to be evaluated in the context of the thread that
1595    was current when the watchpoint was created, and, that thread needs
1596    to be stopped to be able to select the correct frame context.
1597    Watchpoints on global expressions can be evaluated on any thread,
1598    and in any state.  It is presently left to the target allowing
1599    memory accesses when threads are running.  */
1600
1601 static int
1602 watchpoint_in_thread_scope (struct watchpoint *b)
1603 {
1604   return (b->pspace == current_program_space
1605           && (ptid_equal (b->watchpoint_thread, null_ptid)
1606               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1607                   && !is_executing (inferior_ptid))));
1608 }
1609
1610 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1611    associated bp_watchpoint_scope breakpoint.  */
1612
1613 static void
1614 watchpoint_del_at_next_stop (struct watchpoint *w)
1615 {
1616   if (w->related_breakpoint != w)
1617     {
1618       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1619       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1620       w->related_breakpoint->disposition = disp_del_at_next_stop;
1621       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1622       w->related_breakpoint = w;
1623     }
1624   w->disposition = disp_del_at_next_stop;
1625 }
1626
1627 /* Extract a bitfield value from value VAL using the bit parameters contained in
1628    watchpoint W.  */
1629
1630 static struct value *
1631 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1632 {
1633   struct value *bit_val;
1634
1635   if (val == NULL)
1636     return NULL;
1637
1638   bit_val = allocate_value (value_type (val));
1639
1640   unpack_value_bitfield (bit_val,
1641                          w->val_bitpos,
1642                          w->val_bitsize,
1643                          value_contents_for_printing (val),
1644                          value_offset (val),
1645                          val);
1646
1647   return bit_val;
1648 }
1649
1650 /* Allocate a dummy location and add it to B, which must be a software
1651    watchpoint.  This is required because even if a software watchpoint
1652    is not watching any memory, bpstat_stop_status requires a location
1653    to be able to report stops.  */
1654
1655 static void
1656 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1657                                             struct program_space *pspace)
1658 {
1659   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1660
1661   b->loc = allocate_bp_location (b);
1662   b->loc->pspace = pspace;
1663   b->loc->address = -1;
1664   b->loc->length = -1;
1665 }
1666
1667 /* Returns true if B is a software watchpoint that is not watching any
1668    memory (e.g., "watch $pc").  */
1669
1670 static int
1671 is_no_memory_software_watchpoint (struct breakpoint *b)
1672 {
1673   return (b->type == bp_watchpoint
1674           && b->loc != NULL
1675           && b->loc->next == NULL
1676           && b->loc->address == -1
1677           && b->loc->length == -1);
1678 }
1679
1680 /* Assuming that B is a watchpoint:
1681    - Reparse watchpoint expression, if REPARSE is non-zero
1682    - Evaluate expression and store the result in B->val
1683    - Evaluate the condition if there is one, and store the result
1684      in b->loc->cond.
1685    - Update the list of values that must be watched in B->loc.
1686
1687    If the watchpoint disposition is disp_del_at_next_stop, then do
1688    nothing.  If this is local watchpoint that is out of scope, delete
1689    it.
1690
1691    Even with `set breakpoint always-inserted on' the watchpoints are
1692    removed + inserted on each stop here.  Normal breakpoints must
1693    never be removed because they might be missed by a running thread
1694    when debugging in non-stop mode.  On the other hand, hardware
1695    watchpoints (is_hardware_watchpoint; processed here) are specific
1696    to each LWP since they are stored in each LWP's hardware debug
1697    registers.  Therefore, such LWP must be stopped first in order to
1698    be able to modify its hardware watchpoints.
1699
1700    Hardware watchpoints must be reset exactly once after being
1701    presented to the user.  It cannot be done sooner, because it would
1702    reset the data used to present the watchpoint hit to the user.  And
1703    it must not be done later because it could display the same single
1704    watchpoint hit during multiple GDB stops.  Note that the latter is
1705    relevant only to the hardware watchpoint types bp_read_watchpoint
1706    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1707    not user-visible - its hit is suppressed if the memory content has
1708    not changed.
1709
1710    The following constraints influence the location where we can reset
1711    hardware watchpoints:
1712
1713    * target_stopped_by_watchpoint and target_stopped_data_address are
1714      called several times when GDB stops.
1715
1716    [linux] 
1717    * Multiple hardware watchpoints can be hit at the same time,
1718      causing GDB to stop.  GDB only presents one hardware watchpoint
1719      hit at a time as the reason for stopping, and all the other hits
1720      are presented later, one after the other, each time the user
1721      requests the execution to be resumed.  Execution is not resumed
1722      for the threads still having pending hit event stored in
1723      LWP_INFO->STATUS.  While the watchpoint is already removed from
1724      the inferior on the first stop the thread hit event is kept being
1725      reported from its cached value by linux_nat_stopped_data_address
1726      until the real thread resume happens after the watchpoint gets
1727      presented and thus its LWP_INFO->STATUS gets reset.
1728
1729    Therefore the hardware watchpoint hit can get safely reset on the
1730    watchpoint removal from inferior.  */
1731
1732 static void
1733 update_watchpoint (struct watchpoint *b, int reparse)
1734 {
1735   int within_current_scope;
1736   struct frame_id saved_frame_id;
1737   int frame_saved;
1738
1739   /* If this is a local watchpoint, we only want to check if the
1740      watchpoint frame is in scope if the current thread is the thread
1741      that was used to create the watchpoint.  */
1742   if (!watchpoint_in_thread_scope (b))
1743     return;
1744
1745   if (b->disposition == disp_del_at_next_stop)
1746     return;
1747  
1748   frame_saved = 0;
1749
1750   /* Determine if the watchpoint is within scope.  */
1751   if (b->exp_valid_block == NULL)
1752     within_current_scope = 1;
1753   else
1754     {
1755       struct frame_info *fi = get_current_frame ();
1756       struct gdbarch *frame_arch = get_frame_arch (fi);
1757       CORE_ADDR frame_pc = get_frame_pc (fi);
1758
1759       /* If we're at a point where the stack has been destroyed
1760          (e.g. in a function epilogue), unwinding may not work
1761          properly. Do not attempt to recreate locations at this
1762          point.  See similar comments in watchpoint_check.  */
1763       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1764         return;
1765
1766       /* Save the current frame's ID so we can restore it after
1767          evaluating the watchpoint expression on its own frame.  */
1768       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1769          took a frame parameter, so that we didn't have to change the
1770          selected frame.  */
1771       frame_saved = 1;
1772       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1773
1774       fi = frame_find_by_id (b->watchpoint_frame);
1775       within_current_scope = (fi != NULL);
1776       if (within_current_scope)
1777         select_frame (fi);
1778     }
1779
1780   /* We don't free locations.  They are stored in the bp_location array
1781      and update_global_location_list will eventually delete them and
1782      remove breakpoints if needed.  */
1783   b->loc = NULL;
1784
1785   if (within_current_scope && reparse)
1786     {
1787       const char *s;
1788
1789       b->exp.reset ();
1790       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1791       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1792       /* If the meaning of expression itself changed, the old value is
1793          no longer relevant.  We don't want to report a watchpoint hit
1794          to the user when the old value and the new value may actually
1795          be completely different objects.  */
1796       value_free (b->val);
1797       b->val = NULL;
1798       b->val_valid = 0;
1799
1800       /* Note that unlike with breakpoints, the watchpoint's condition
1801          expression is stored in the breakpoint object, not in the
1802          locations (re)created below.  */
1803       if (b->cond_string != NULL)
1804         {
1805           b->cond_exp.reset ();
1806
1807           s = b->cond_string;
1808           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1809         }
1810     }
1811
1812   /* If we failed to parse the expression, for example because
1813      it refers to a global variable in a not-yet-loaded shared library,
1814      don't try to insert watchpoint.  We don't automatically delete
1815      such watchpoint, though, since failure to parse expression
1816      is different from out-of-scope watchpoint.  */
1817   if (!target_has_execution)
1818     {
1819       /* Without execution, memory can't change.  No use to try and
1820          set watchpoint locations.  The watchpoint will be reset when
1821          the target gains execution, through breakpoint_re_set.  */
1822       if (!can_use_hw_watchpoints)
1823         {
1824           if (b->ops->works_in_software_mode (b))
1825             b->type = bp_watchpoint;
1826           else
1827             error (_("Can't set read/access watchpoint when "
1828                      "hardware watchpoints are disabled."));
1829         }
1830     }
1831   else if (within_current_scope && b->exp)
1832     {
1833       int pc = 0;
1834       struct value *val_chain, *v, *result, *next;
1835       struct program_space *frame_pspace;
1836
1837       fetch_subexp_value (b->exp.get (), &pc, &v, &result, &val_chain, 0);
1838
1839       /* Avoid setting b->val if it's already set.  The meaning of
1840          b->val is 'the last value' user saw, and we should update
1841          it only if we reported that last value to user.  As it
1842          happens, the code that reports it updates b->val directly.
1843          We don't keep track of the memory value for masked
1844          watchpoints.  */
1845       if (!b->val_valid && !is_masked_watchpoint (b))
1846         {
1847           if (b->val_bitsize != 0)
1848             {
1849               v = extract_bitfield_from_watchpoint_value (b, v);
1850               if (v != NULL)
1851                 release_value (v);
1852             }
1853           b->val = v;
1854           b->val_valid = 1;
1855         }
1856
1857       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1858
1859       /* Look at each value on the value chain.  */
1860       for (v = val_chain; v; v = value_next (v))
1861         {
1862           /* If it's a memory location, and GDB actually needed
1863              its contents to evaluate the expression, then we
1864              must watch it.  If the first value returned is
1865              still lazy, that means an error occurred reading it;
1866              watch it anyway in case it becomes readable.  */
1867           if (VALUE_LVAL (v) == lval_memory
1868               && (v == val_chain || ! value_lazy (v)))
1869             {
1870               struct type *vtype = check_typedef (value_type (v));
1871
1872               /* We only watch structs and arrays if user asked
1873                  for it explicitly, never if they just happen to
1874                  appear in the middle of some value chain.  */
1875               if (v == result
1876                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1877                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1878                 {
1879                   CORE_ADDR addr;
1880                   enum target_hw_bp_type type;
1881                   struct bp_location *loc, **tmp;
1882                   int bitpos = 0, bitsize = 0;
1883
1884                   if (value_bitsize (v) != 0)
1885                     {
1886                       /* Extract the bit parameters out from the bitfield
1887                          sub-expression.  */
1888                       bitpos = value_bitpos (v);
1889                       bitsize = value_bitsize (v);
1890                     }
1891                   else if (v == result && b->val_bitsize != 0)
1892                     {
1893                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1894                         lvalue whose bit parameters are saved in the fields
1895                         VAL_BITPOS and VAL_BITSIZE.  */
1896                       bitpos = b->val_bitpos;
1897                       bitsize = b->val_bitsize;
1898                     }
1899
1900                   addr = value_address (v);
1901                   if (bitsize != 0)
1902                     {
1903                       /* Skip the bytes that don't contain the bitfield.  */
1904                       addr += bitpos / 8;
1905                     }
1906
1907                   type = hw_write;
1908                   if (b->type == bp_read_watchpoint)
1909                     type = hw_read;
1910                   else if (b->type == bp_access_watchpoint)
1911                     type = hw_access;
1912
1913                   loc = allocate_bp_location (b);
1914                   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
1915                     ;
1916                   *tmp = loc;
1917                   loc->gdbarch = get_type_arch (value_type (v));
1918
1919                   loc->pspace = frame_pspace;
1920                   loc->address = addr;
1921
1922                   if (bitsize != 0)
1923                     {
1924                       /* Just cover the bytes that make up the bitfield.  */
1925                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
1926                     }
1927                   else
1928                     loc->length = TYPE_LENGTH (value_type (v));
1929
1930                   loc->watchpoint_type = type;
1931                 }
1932             }
1933         }
1934
1935       /* Change the type of breakpoint between hardware assisted or
1936          an ordinary watchpoint depending on the hardware support
1937          and free hardware slots.  REPARSE is set when the inferior
1938          is started.  */
1939       if (reparse)
1940         {
1941           int reg_cnt;
1942           enum bp_loc_type loc_type;
1943           struct bp_location *bl;
1944
1945           reg_cnt = can_use_hardware_watchpoint (val_chain);
1946
1947           if (reg_cnt)
1948             {
1949               int i, target_resources_ok, other_type_used;
1950               enum bptype type;
1951
1952               /* Use an exact watchpoint when there's only one memory region to be
1953                  watched, and only one debug register is needed to watch it.  */
1954               b->exact = target_exact_watchpoints && reg_cnt == 1;
1955
1956               /* We need to determine how many resources are already
1957                  used for all other hardware watchpoints plus this one
1958                  to see if we still have enough resources to also fit
1959                  this watchpoint in as well.  */
1960
1961               /* If this is a software watchpoint, we try to turn it
1962                  to a hardware one -- count resources as if B was of
1963                  hardware watchpoint type.  */
1964               type = b->type;
1965               if (type == bp_watchpoint)
1966                 type = bp_hardware_watchpoint;
1967
1968               /* This watchpoint may or may not have been placed on
1969                  the list yet at this point (it won't be in the list
1970                  if we're trying to create it for the first time,
1971                  through watch_command), so always account for it
1972                  manually.  */
1973
1974               /* Count resources used by all watchpoints except B.  */
1975               i = hw_watchpoint_used_count_others (b, type, &other_type_used);
1976
1977               /* Add in the resources needed for B.  */
1978               i += hw_watchpoint_use_count (b);
1979
1980               target_resources_ok
1981                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1982               if (target_resources_ok <= 0)
1983                 {
1984                   int sw_mode = b->ops->works_in_software_mode (b);
1985
1986                   if (target_resources_ok == 0 && !sw_mode)
1987                     error (_("Target does not support this type of "
1988                              "hardware watchpoint."));
1989                   else if (target_resources_ok < 0 && !sw_mode)
1990                     error (_("There are not enough available hardware "
1991                              "resources for this watchpoint."));
1992
1993                   /* Downgrade to software watchpoint.  */
1994                   b->type = bp_watchpoint;
1995                 }
1996               else
1997                 {
1998                   /* If this was a software watchpoint, we've just
1999                      found we have enough resources to turn it to a
2000                      hardware watchpoint.  Otherwise, this is a
2001                      nop.  */
2002                   b->type = type;
2003                 }
2004             }
2005           else if (!b->ops->works_in_software_mode (b))
2006             {
2007               if (!can_use_hw_watchpoints)
2008                 error (_("Can't set read/access watchpoint when "
2009                          "hardware watchpoints are disabled."));
2010               else
2011                 error (_("Expression cannot be implemented with "
2012                          "read/access watchpoint."));
2013             }
2014           else
2015             b->type = bp_watchpoint;
2016
2017           loc_type = (b->type == bp_watchpoint? bp_loc_other
2018                       : bp_loc_hardware_watchpoint);
2019           for (bl = b->loc; bl; bl = bl->next)
2020             bl->loc_type = loc_type;
2021         }
2022
2023       for (v = val_chain; v; v = next)
2024         {
2025           next = value_next (v);
2026           if (v != b->val)
2027             value_free (v);
2028         }
2029
2030       /* If a software watchpoint is not watching any memory, then the
2031          above left it without any location set up.  But,
2032          bpstat_stop_status requires a location to be able to report
2033          stops, so make sure there's at least a dummy one.  */
2034       if (b->type == bp_watchpoint && b->loc == NULL)
2035         software_watchpoint_add_no_memory_location (b, frame_pspace);
2036     }
2037   else if (!within_current_scope)
2038     {
2039       printf_filtered (_("\
2040 Watchpoint %d deleted because the program has left the block\n\
2041 in which its expression is valid.\n"),
2042                        b->number);
2043       watchpoint_del_at_next_stop (b);
2044     }
2045
2046   /* Restore the selected frame.  */
2047   if (frame_saved)
2048     select_frame (frame_find_by_id (saved_frame_id));
2049 }
2050
2051
2052 /* Returns 1 iff breakpoint location should be
2053    inserted in the inferior.  We don't differentiate the type of BL's owner
2054    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2055    breakpoint_ops is not defined, because in insert_bp_location,
2056    tracepoint's insert_location will not be called.  */
2057 static int
2058 should_be_inserted (struct bp_location *bl)
2059 {
2060   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2061     return 0;
2062
2063   if (bl->owner->disposition == disp_del_at_next_stop)
2064     return 0;
2065
2066   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2067     return 0;
2068
2069   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2070     return 0;
2071
2072   /* This is set for example, when we're attached to the parent of a
2073      vfork, and have detached from the child.  The child is running
2074      free, and we expect it to do an exec or exit, at which point the
2075      OS makes the parent schedulable again (and the target reports
2076      that the vfork is done).  Until the child is done with the shared
2077      memory region, do not insert breakpoints in the parent, otherwise
2078      the child could still trip on the parent's breakpoints.  Since
2079      the parent is blocked anyway, it won't miss any breakpoint.  */
2080   if (bl->pspace->breakpoints_not_allowed)
2081     return 0;
2082
2083   /* Don't insert a breakpoint if we're trying to step past its
2084      location, except if the breakpoint is a single-step breakpoint,
2085      and the breakpoint's thread is the thread which is stepping past
2086      a breakpoint.  */
2087   if ((bl->loc_type == bp_loc_software_breakpoint
2088        || bl->loc_type == bp_loc_hardware_breakpoint)
2089       && stepping_past_instruction_at (bl->pspace->aspace,
2090                                        bl->address)
2091       /* The single-step breakpoint may be inserted at the location
2092          we're trying to step if the instruction branches to itself.
2093          However, the instruction won't be executed at all and it may
2094          break the semantics of the instruction, for example, the
2095          instruction is a conditional branch or updates some flags.
2096          We can't fix it unless GDB is able to emulate the instruction
2097          or switch to displaced stepping.  */
2098       && !(bl->owner->type == bp_single_step
2099            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2100     {
2101       if (debug_infrun)
2102         {
2103           fprintf_unfiltered (gdb_stdlog,
2104                               "infrun: skipping breakpoint: "
2105                               "stepping past insn at: %s\n",
2106                               paddress (bl->gdbarch, bl->address));
2107         }
2108       return 0;
2109     }
2110
2111   /* Don't insert watchpoints if we're trying to step past the
2112      instruction that triggered one.  */
2113   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2114       && stepping_past_nonsteppable_watchpoint ())
2115     {
2116       if (debug_infrun)
2117         {
2118           fprintf_unfiltered (gdb_stdlog,
2119                               "infrun: stepping past non-steppable watchpoint. "
2120                               "skipping watchpoint at %s:%d\n",
2121                               paddress (bl->gdbarch, bl->address),
2122                               bl->length);
2123         }
2124       return 0;
2125     }
2126
2127   return 1;
2128 }
2129
2130 /* Same as should_be_inserted but does the check assuming
2131    that the location is not duplicated.  */
2132
2133 static int
2134 unduplicated_should_be_inserted (struct bp_location *bl)
2135 {
2136   int result;
2137   const int save_duplicate = bl->duplicate;
2138
2139   bl->duplicate = 0;
2140   result = should_be_inserted (bl);
2141   bl->duplicate = save_duplicate;
2142   return result;
2143 }
2144
2145 /* Parses a conditional described by an expression COND into an
2146    agent expression bytecode suitable for evaluation
2147    by the bytecode interpreter.  Return NULL if there was
2148    any error during parsing.  */
2149
2150 static agent_expr_up
2151 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2152 {
2153   if (cond == NULL)
2154     return NULL;
2155
2156   agent_expr_up aexpr;
2157
2158   /* We don't want to stop processing, so catch any errors
2159      that may show up.  */
2160   TRY
2161     {
2162       aexpr = gen_eval_for_expr (scope, cond);
2163     }
2164
2165   CATCH (ex, RETURN_MASK_ERROR)
2166     {
2167       /* If we got here, it means the condition could not be parsed to a valid
2168          bytecode expression and thus can't be evaluated on the target's side.
2169          It's no use iterating through the conditions.  */
2170     }
2171   END_CATCH
2172
2173   /* We have a valid agent expression.  */
2174   return aexpr;
2175 }
2176
2177 /* Based on location BL, create a list of breakpoint conditions to be
2178    passed on to the target.  If we have duplicated locations with different
2179    conditions, we will add such conditions to the list.  The idea is that the
2180    target will evaluate the list of conditions and will only notify GDB when
2181    one of them is true.  */
2182
2183 static void
2184 build_target_condition_list (struct bp_location *bl)
2185 {
2186   struct bp_location **locp = NULL, **loc2p;
2187   int null_condition_or_parse_error = 0;
2188   int modified = bl->needs_update;
2189   struct bp_location *loc;
2190
2191   /* Release conditions left over from a previous insert.  */
2192   bl->target_info.conditions.clear ();
2193
2194   /* This is only meaningful if the target is
2195      evaluating conditions and if the user has
2196      opted for condition evaluation on the target's
2197      side.  */
2198   if (gdb_evaluates_breakpoint_condition_p ()
2199       || !target_supports_evaluation_of_breakpoint_conditions ())
2200     return;
2201
2202   /* Do a first pass to check for locations with no assigned
2203      conditions or conditions that fail to parse to a valid agent expression
2204      bytecode.  If any of these happen, then it's no use to send conditions
2205      to the target since this location will always trigger and generate a
2206      response back to GDB.  */
2207   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2208     {
2209       loc = (*loc2p);
2210       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2211         {
2212           if (modified)
2213             {
2214               /* Re-parse the conditions since something changed.  In that
2215                  case we already freed the condition bytecodes (see
2216                  force_breakpoint_reinsertion).  We just
2217                  need to parse the condition to bytecodes again.  */
2218               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2219                                                         loc->cond.get ());
2220             }
2221
2222           /* If we have a NULL bytecode expression, it means something
2223              went wrong or we have a null condition expression.  */
2224           if (!loc->cond_bytecode)
2225             {
2226               null_condition_or_parse_error = 1;
2227               break;
2228             }
2229         }
2230     }
2231
2232   /* If any of these happened, it means we will have to evaluate the conditions
2233      for the location's address on gdb's side.  It is no use keeping bytecodes
2234      for all the other duplicate locations, thus we free all of them here.
2235
2236      This is so we have a finer control over which locations' conditions are
2237      being evaluated by GDB or the remote stub.  */
2238   if (null_condition_or_parse_error)
2239     {
2240       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2241         {
2242           loc = (*loc2p);
2243           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2244             {
2245               /* Only go as far as the first NULL bytecode is
2246                  located.  */
2247               if (!loc->cond_bytecode)
2248                 return;
2249
2250               loc->cond_bytecode.reset ();
2251             }
2252         }
2253     }
2254
2255   /* No NULL conditions or failed bytecode generation.  Build a condition list
2256      for this location's address.  */
2257   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2258     {
2259       loc = (*loc2p);
2260       if (loc->cond
2261           && is_breakpoint (loc->owner)
2262           && loc->pspace->num == bl->pspace->num
2263           && loc->owner->enable_state == bp_enabled
2264           && loc->enabled)
2265         {
2266           /* Add the condition to the vector.  This will be used later
2267              to send the conditions to the target.  */
2268           bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2269         }
2270     }
2271
2272   return;
2273 }
2274
2275 /* Parses a command described by string CMD into an agent expression
2276    bytecode suitable for evaluation by the bytecode interpreter.
2277    Return NULL if there was any error during parsing.  */
2278
2279 static agent_expr_up
2280 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2281 {
2282   struct cleanup *old_cleanups = 0;
2283   struct expression **argvec;
2284   const char *cmdrest;
2285   const char *format_start, *format_end;
2286   struct format_piece *fpieces;
2287   int nargs;
2288   struct gdbarch *gdbarch = get_current_arch ();
2289
2290   if (cmd == NULL)
2291     return NULL;
2292
2293   cmdrest = cmd;
2294
2295   if (*cmdrest == ',')
2296     ++cmdrest;
2297   cmdrest = skip_spaces (cmdrest);
2298
2299   if (*cmdrest++ != '"')
2300     error (_("No format string following the location"));
2301
2302   format_start = cmdrest;
2303
2304   fpieces = parse_format_string (&cmdrest);
2305
2306   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2307
2308   format_end = cmdrest;
2309
2310   if (*cmdrest++ != '"')
2311     error (_("Bad format string, non-terminated '\"'."));
2312   
2313   cmdrest = skip_spaces (cmdrest);
2314
2315   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2316     error (_("Invalid argument syntax"));
2317
2318   if (*cmdrest == ',')
2319     cmdrest++;
2320   cmdrest = skip_spaces (cmdrest);
2321
2322   /* For each argument, make an expression.  */
2323
2324   argvec = (struct expression **) alloca (strlen (cmd)
2325                                          * sizeof (struct expression *));
2326
2327   nargs = 0;
2328   while (*cmdrest != '\0')
2329     {
2330       const char *cmd1;
2331
2332       cmd1 = cmdrest;
2333       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2334       argvec[nargs++] = expr.release ();
2335       cmdrest = cmd1;
2336       if (*cmdrest == ',')
2337         ++cmdrest;
2338     }
2339
2340   agent_expr_up aexpr;
2341
2342   /* We don't want to stop processing, so catch any errors
2343      that may show up.  */
2344   TRY
2345     {
2346       aexpr = gen_printf (scope, gdbarch, 0, 0,
2347                           format_start, format_end - format_start,
2348                           fpieces, nargs, argvec);
2349     }
2350   CATCH (ex, RETURN_MASK_ERROR)
2351     {
2352       /* If we got here, it means the command could not be parsed to a valid
2353          bytecode expression and thus can't be evaluated on the target's side.
2354          It's no use iterating through the other commands.  */
2355     }
2356   END_CATCH
2357
2358   do_cleanups (old_cleanups);
2359
2360   /* We have a valid agent expression, return it.  */
2361   return aexpr;
2362 }
2363
2364 /* Based on location BL, create a list of breakpoint commands to be
2365    passed on to the target.  If we have duplicated locations with
2366    different commands, we will add any such to the list.  */
2367
2368 static void
2369 build_target_command_list (struct bp_location *bl)
2370 {
2371   struct bp_location **locp = NULL, **loc2p;
2372   int null_command_or_parse_error = 0;
2373   int modified = bl->needs_update;
2374   struct bp_location *loc;
2375
2376   /* Clear commands left over from a previous insert.  */
2377   bl->target_info.tcommands.clear ();
2378
2379   if (!target_can_run_breakpoint_commands ())
2380     return;
2381
2382   /* For now, limit to agent-style dprintf breakpoints.  */
2383   if (dprintf_style != dprintf_style_agent)
2384     return;
2385
2386   /* For now, if we have any duplicate location that isn't a dprintf,
2387      don't install the target-side commands, as that would make the
2388      breakpoint not be reported to the core, and we'd lose
2389      control.  */
2390   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2391     {
2392       loc = (*loc2p);
2393       if (is_breakpoint (loc->owner)
2394           && loc->pspace->num == bl->pspace->num
2395           && loc->owner->type != bp_dprintf)
2396         return;
2397     }
2398
2399   /* Do a first pass to check for locations with no assigned
2400      conditions or conditions that fail to parse to a valid agent expression
2401      bytecode.  If any of these happen, then it's no use to send conditions
2402      to the target since this location will always trigger and generate a
2403      response back to GDB.  */
2404   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2405     {
2406       loc = (*loc2p);
2407       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2408         {
2409           if (modified)
2410             {
2411               /* Re-parse the commands since something changed.  In that
2412                  case we already freed the command bytecodes (see
2413                  force_breakpoint_reinsertion).  We just
2414                  need to parse the command to bytecodes again.  */
2415               loc->cmd_bytecode
2416                 = parse_cmd_to_aexpr (bl->address,
2417                                       loc->owner->extra_string);
2418             }
2419
2420           /* If we have a NULL bytecode expression, it means something
2421              went wrong or we have a null command expression.  */
2422           if (!loc->cmd_bytecode)
2423             {
2424               null_command_or_parse_error = 1;
2425               break;
2426             }
2427         }
2428     }
2429
2430   /* If anything failed, then we're not doing target-side commands,
2431      and so clean up.  */
2432   if (null_command_or_parse_error)
2433     {
2434       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2435         {
2436           loc = (*loc2p);
2437           if (is_breakpoint (loc->owner)
2438               && loc->pspace->num == bl->pspace->num)
2439             {
2440               /* Only go as far as the first NULL bytecode is
2441                  located.  */
2442               if (loc->cmd_bytecode == NULL)
2443                 return;
2444
2445               loc->cmd_bytecode.reset ();
2446             }
2447         }
2448     }
2449
2450   /* No NULL commands or failed bytecode generation.  Build a command list
2451      for this location's address.  */
2452   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2453     {
2454       loc = (*loc2p);
2455       if (loc->owner->extra_string
2456           && is_breakpoint (loc->owner)
2457           && loc->pspace->num == bl->pspace->num
2458           && loc->owner->enable_state == bp_enabled
2459           && loc->enabled)
2460         {
2461           /* Add the command to the vector.  This will be used later
2462              to send the commands to the target.  */
2463           bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2464         }
2465     }
2466
2467   bl->target_info.persist = 0;
2468   /* Maybe flag this location as persistent.  */
2469   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2470     bl->target_info.persist = 1;
2471 }
2472
2473 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2474    of breakpoint according to ADDR except single-step breakpoint.
2475    Get the kind of single-step breakpoint according to the current
2476    registers state.  */
2477
2478 static int
2479 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2480 {
2481   if (bl->owner->type == bp_single_step)
2482     {
2483       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2484       struct regcache *regcache;
2485
2486       regcache = get_thread_regcache (thr->ptid);
2487
2488       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2489                                                          regcache, addr);
2490     }
2491   else
2492     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2493 }
2494
2495 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2496    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2497    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2498    Returns 0 for success, 1 if the bp_location type is not supported or
2499    -1 for failure.
2500
2501    NOTE drow/2003-09-09: This routine could be broken down to an
2502    object-style method for each breakpoint or catchpoint type.  */
2503 static int
2504 insert_bp_location (struct bp_location *bl,
2505                     struct ui_file *tmp_error_stream,
2506                     int *disabled_breaks,
2507                     int *hw_breakpoint_error,
2508                     int *hw_bp_error_explained_already)
2509 {
2510   enum errors bp_err = GDB_NO_ERROR;
2511   const char *bp_err_message = NULL;
2512
2513   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2514     return 0;
2515
2516   /* Note we don't initialize bl->target_info, as that wipes out
2517      the breakpoint location's shadow_contents if the breakpoint
2518      is still inserted at that location.  This in turn breaks
2519      target_read_memory which depends on these buffers when
2520      a memory read is requested at the breakpoint location:
2521      Once the target_info has been wiped, we fail to see that
2522      we have a breakpoint inserted at that address and thus
2523      read the breakpoint instead of returning the data saved in
2524      the breakpoint location's shadow contents.  */
2525   bl->target_info.reqstd_address = bl->address;
2526   bl->target_info.placed_address_space = bl->pspace->aspace;
2527   bl->target_info.length = bl->length;
2528
2529   /* When working with target-side conditions, we must pass all the conditions
2530      for the same breakpoint address down to the target since GDB will not
2531      insert those locations.  With a list of breakpoint conditions, the target
2532      can decide when to stop and notify GDB.  */
2533
2534   if (is_breakpoint (bl->owner))
2535     {
2536       build_target_condition_list (bl);
2537       build_target_command_list (bl);
2538       /* Reset the modification marker.  */
2539       bl->needs_update = 0;
2540     }
2541
2542   if (bl->loc_type == bp_loc_software_breakpoint
2543       || bl->loc_type == bp_loc_hardware_breakpoint)
2544     {
2545       if (bl->owner->type != bp_hardware_breakpoint)
2546         {
2547           /* If the explicitly specified breakpoint type
2548              is not hardware breakpoint, check the memory map to see
2549              if the breakpoint address is in read only memory or not.
2550
2551              Two important cases are:
2552              - location type is not hardware breakpoint, memory
2553              is readonly.  We change the type of the location to
2554              hardware breakpoint.
2555              - location type is hardware breakpoint, memory is
2556              read-write.  This means we've previously made the
2557              location hardware one, but then the memory map changed,
2558              so we undo.
2559              
2560              When breakpoints are removed, remove_breakpoints will use
2561              location types we've just set here, the only possible
2562              problem is that memory map has changed during running
2563              program, but it's not going to work anyway with current
2564              gdb.  */
2565           struct mem_region *mr 
2566             = lookup_mem_region (bl->target_info.reqstd_address);
2567           
2568           if (mr)
2569             {
2570               if (automatic_hardware_breakpoints)
2571                 {
2572                   enum bp_loc_type new_type;
2573                   
2574                   if (mr->attrib.mode != MEM_RW)
2575                     new_type = bp_loc_hardware_breakpoint;
2576                   else 
2577                     new_type = bp_loc_software_breakpoint;
2578                   
2579                   if (new_type != bl->loc_type)
2580                     {
2581                       static int said = 0;
2582
2583                       bl->loc_type = new_type;
2584                       if (!said)
2585                         {
2586                           fprintf_filtered (gdb_stdout,
2587                                             _("Note: automatically using "
2588                                               "hardware breakpoints for "
2589                                               "read-only addresses.\n"));
2590                           said = 1;
2591                         }
2592                     }
2593                 }
2594               else if (bl->loc_type == bp_loc_software_breakpoint
2595                        && mr->attrib.mode != MEM_RW)
2596                 {
2597                   fprintf_unfiltered (tmp_error_stream,
2598                                       _("Cannot insert breakpoint %d.\n"
2599                                         "Cannot set software breakpoint "
2600                                         "at read-only address %s\n"),
2601                                       bl->owner->number,
2602                                       paddress (bl->gdbarch, bl->address));
2603                   return 1;
2604                 }
2605             }
2606         }
2607         
2608       /* First check to see if we have to handle an overlay.  */
2609       if (overlay_debugging == ovly_off
2610           || bl->section == NULL
2611           || !(section_is_overlay (bl->section)))
2612         {
2613           /* No overlay handling: just set the breakpoint.  */
2614           TRY
2615             {
2616               int val;
2617
2618               val = bl->owner->ops->insert_location (bl);
2619               if (val)
2620                 bp_err = GENERIC_ERROR;
2621             }
2622           CATCH (e, RETURN_MASK_ALL)
2623             {
2624               bp_err = e.error;
2625               bp_err_message = e.message;
2626             }
2627           END_CATCH
2628         }
2629       else
2630         {
2631           /* This breakpoint is in an overlay section.
2632              Shall we set a breakpoint at the LMA?  */
2633           if (!overlay_events_enabled)
2634             {
2635               /* Yes -- overlay event support is not active, 
2636                  so we must try to set a breakpoint at the LMA.
2637                  This will not work for a hardware breakpoint.  */
2638               if (bl->loc_type == bp_loc_hardware_breakpoint)
2639                 warning (_("hardware breakpoint %d not supported in overlay!"),
2640                          bl->owner->number);
2641               else
2642                 {
2643                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2644                                                              bl->section);
2645                   /* Set a software (trap) breakpoint at the LMA.  */
2646                   bl->overlay_target_info = bl->target_info;
2647                   bl->overlay_target_info.reqstd_address = addr;
2648
2649                   /* No overlay handling: just set the breakpoint.  */
2650                   TRY
2651                     {
2652                       int val;
2653
2654                       bl->overlay_target_info.kind
2655                         = breakpoint_kind (bl, &addr);
2656                       bl->overlay_target_info.placed_address = addr;
2657                       val = target_insert_breakpoint (bl->gdbarch,
2658                                                       &bl->overlay_target_info);
2659                       if (val)
2660                         bp_err = GENERIC_ERROR;
2661                     }
2662                   CATCH (e, RETURN_MASK_ALL)
2663                     {
2664                       bp_err = e.error;
2665                       bp_err_message = e.message;
2666                     }
2667                   END_CATCH
2668
2669                   if (bp_err != GDB_NO_ERROR)
2670                     fprintf_unfiltered (tmp_error_stream,
2671                                         "Overlay breakpoint %d "
2672                                         "failed: in ROM?\n",
2673                                         bl->owner->number);
2674                 }
2675             }
2676           /* Shall we set a breakpoint at the VMA? */
2677           if (section_is_mapped (bl->section))
2678             {
2679               /* Yes.  This overlay section is mapped into memory.  */
2680               TRY
2681                 {
2682                   int val;
2683
2684                   val = bl->owner->ops->insert_location (bl);
2685                   if (val)
2686                     bp_err = GENERIC_ERROR;
2687                 }
2688               CATCH (e, RETURN_MASK_ALL)
2689                 {
2690                   bp_err = e.error;
2691                   bp_err_message = e.message;
2692                 }
2693               END_CATCH
2694             }
2695           else
2696             {
2697               /* No.  This breakpoint will not be inserted.  
2698                  No error, but do not mark the bp as 'inserted'.  */
2699               return 0;
2700             }
2701         }
2702
2703       if (bp_err != GDB_NO_ERROR)
2704         {
2705           /* Can't set the breakpoint.  */
2706
2707           /* In some cases, we might not be able to insert a
2708              breakpoint in a shared library that has already been
2709              removed, but we have not yet processed the shlib unload
2710              event.  Unfortunately, some targets that implement
2711              breakpoint insertion themselves can't tell why the
2712              breakpoint insertion failed (e.g., the remote target
2713              doesn't define error codes), so we must treat generic
2714              errors as memory errors.  */
2715           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2716               && bl->loc_type == bp_loc_software_breakpoint
2717               && (solib_name_from_address (bl->pspace, bl->address)
2718                   || shared_objfile_contains_address_p (bl->pspace,
2719                                                         bl->address)))
2720             {
2721               /* See also: disable_breakpoints_in_shlibs.  */
2722               bl->shlib_disabled = 1;
2723               observer_notify_breakpoint_modified (bl->owner);
2724               if (!*disabled_breaks)
2725                 {
2726                   fprintf_unfiltered (tmp_error_stream, 
2727                                       "Cannot insert breakpoint %d.\n", 
2728                                       bl->owner->number);
2729                   fprintf_unfiltered (tmp_error_stream, 
2730                                       "Temporarily disabling shared "
2731                                       "library breakpoints:\n");
2732                 }
2733               *disabled_breaks = 1;
2734               fprintf_unfiltered (tmp_error_stream,
2735                                   "breakpoint #%d\n", bl->owner->number);
2736               return 0;
2737             }
2738           else
2739             {
2740               if (bl->loc_type == bp_loc_hardware_breakpoint)
2741                 {
2742                   *hw_breakpoint_error = 1;
2743                   *hw_bp_error_explained_already = bp_err_message != NULL;
2744                   fprintf_unfiltered (tmp_error_stream,
2745                                       "Cannot insert hardware breakpoint %d%s",
2746                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2747                   if (bp_err_message != NULL)
2748                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2749                 }
2750               else
2751                 {
2752                   if (bp_err_message == NULL)
2753                     {
2754                       std::string message
2755                         = memory_error_message (TARGET_XFER_E_IO,
2756                                                 bl->gdbarch, bl->address);
2757
2758                       fprintf_unfiltered (tmp_error_stream,
2759                                           "Cannot insert breakpoint %d.\n"
2760                                           "%s\n",
2761                                           bl->owner->number, message.c_str ());
2762                     }
2763                   else
2764                     {
2765                       fprintf_unfiltered (tmp_error_stream,
2766                                           "Cannot insert breakpoint %d: %s\n",
2767                                           bl->owner->number,
2768                                           bp_err_message);
2769                     }
2770                 }
2771               return 1;
2772
2773             }
2774         }
2775       else
2776         bl->inserted = 1;
2777
2778       return 0;
2779     }
2780
2781   else if (bl->loc_type == bp_loc_hardware_watchpoint
2782            /* NOTE drow/2003-09-08: This state only exists for removing
2783               watchpoints.  It's not clear that it's necessary...  */
2784            && bl->owner->disposition != disp_del_at_next_stop)
2785     {
2786       int val;
2787
2788       gdb_assert (bl->owner->ops != NULL
2789                   && bl->owner->ops->insert_location != NULL);
2790
2791       val = bl->owner->ops->insert_location (bl);
2792
2793       /* If trying to set a read-watchpoint, and it turns out it's not
2794          supported, try emulating one with an access watchpoint.  */
2795       if (val == 1 && bl->watchpoint_type == hw_read)
2796         {
2797           struct bp_location *loc, **loc_temp;
2798
2799           /* But don't try to insert it, if there's already another
2800              hw_access location that would be considered a duplicate
2801              of this one.  */
2802           ALL_BP_LOCATIONS (loc, loc_temp)
2803             if (loc != bl
2804                 && loc->watchpoint_type == hw_access
2805                 && watchpoint_locations_match (bl, loc))
2806               {
2807                 bl->duplicate = 1;
2808                 bl->inserted = 1;
2809                 bl->target_info = loc->target_info;
2810                 bl->watchpoint_type = hw_access;
2811                 val = 0;
2812                 break;
2813               }
2814
2815           if (val == 1)
2816             {
2817               bl->watchpoint_type = hw_access;
2818               val = bl->owner->ops->insert_location (bl);
2819
2820               if (val)
2821                 /* Back to the original value.  */
2822                 bl->watchpoint_type = hw_read;
2823             }
2824         }
2825
2826       bl->inserted = (val == 0);
2827     }
2828
2829   else if (bl->owner->type == bp_catchpoint)
2830     {
2831       int val;
2832
2833       gdb_assert (bl->owner->ops != NULL
2834                   && bl->owner->ops->insert_location != NULL);
2835
2836       val = bl->owner->ops->insert_location (bl);
2837       if (val)
2838         {
2839           bl->owner->enable_state = bp_disabled;
2840
2841           if (val == 1)
2842             warning (_("\
2843 Error inserting catchpoint %d: Your system does not support this type\n\
2844 of catchpoint."), bl->owner->number);
2845           else
2846             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2847         }
2848
2849       bl->inserted = (val == 0);
2850
2851       /* We've already printed an error message if there was a problem
2852          inserting this catchpoint, and we've disabled the catchpoint,
2853          so just return success.  */
2854       return 0;
2855     }
2856
2857   return 0;
2858 }
2859
2860 /* This function is called when program space PSPACE is about to be
2861    deleted.  It takes care of updating breakpoints to not reference
2862    PSPACE anymore.  */
2863
2864 void
2865 breakpoint_program_space_exit (struct program_space *pspace)
2866 {
2867   struct breakpoint *b, *b_temp;
2868   struct bp_location *loc, **loc_temp;
2869
2870   /* Remove any breakpoint that was set through this program space.  */
2871   ALL_BREAKPOINTS_SAFE (b, b_temp)
2872     {
2873       if (b->pspace == pspace)
2874         delete_breakpoint (b);
2875     }
2876
2877   /* Breakpoints set through other program spaces could have locations
2878      bound to PSPACE as well.  Remove those.  */
2879   ALL_BP_LOCATIONS (loc, loc_temp)
2880     {
2881       struct bp_location *tmp;
2882
2883       if (loc->pspace == pspace)
2884         {
2885           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2886           if (loc->owner->loc == loc)
2887             loc->owner->loc = loc->next;
2888           else
2889             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2890               if (tmp->next == loc)
2891                 {
2892                   tmp->next = loc->next;
2893                   break;
2894                 }
2895         }
2896     }
2897
2898   /* Now update the global location list to permanently delete the
2899      removed locations above.  */
2900   update_global_location_list (UGLL_DONT_INSERT);
2901 }
2902
2903 /* Make sure all breakpoints are inserted in inferior.
2904    Throws exception on any error.
2905    A breakpoint that is already inserted won't be inserted
2906    again, so calling this function twice is safe.  */
2907 void
2908 insert_breakpoints (void)
2909 {
2910   struct breakpoint *bpt;
2911
2912   ALL_BREAKPOINTS (bpt)
2913     if (is_hardware_watchpoint (bpt))
2914       {
2915         struct watchpoint *w = (struct watchpoint *) bpt;
2916
2917         update_watchpoint (w, 0 /* don't reparse.  */);
2918       }
2919
2920   /* Updating watchpoints creates new locations, so update the global
2921      location list.  Explicitly tell ugll to insert locations and
2922      ignore breakpoints_always_inserted_mode.  */
2923   update_global_location_list (UGLL_INSERT);
2924 }
2925
2926 /* Invoke CALLBACK for each of bp_location.  */
2927
2928 void
2929 iterate_over_bp_locations (walk_bp_location_callback callback)
2930 {
2931   struct bp_location *loc, **loc_tmp;
2932
2933   ALL_BP_LOCATIONS (loc, loc_tmp)
2934     {
2935       callback (loc, NULL);
2936     }
2937 }
2938
2939 /* This is used when we need to synch breakpoint conditions between GDB and the
2940    target.  It is the case with deleting and disabling of breakpoints when using
2941    always-inserted mode.  */
2942
2943 static void
2944 update_inserted_breakpoint_locations (void)
2945 {
2946   struct bp_location *bl, **blp_tmp;
2947   int error_flag = 0;
2948   int val = 0;
2949   int disabled_breaks = 0;
2950   int hw_breakpoint_error = 0;
2951   int hw_bp_details_reported = 0;
2952
2953   string_file tmp_error_stream;
2954
2955   /* Explicitly mark the warning -- this will only be printed if
2956      there was an error.  */
2957   tmp_error_stream.puts ("Warning:\n");
2958
2959   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2960
2961   ALL_BP_LOCATIONS (bl, blp_tmp)
2962     {
2963       /* We only want to update software breakpoints and hardware
2964          breakpoints.  */
2965       if (!is_breakpoint (bl->owner))
2966         continue;
2967
2968       /* We only want to update locations that are already inserted
2969          and need updating.  This is to avoid unwanted insertion during
2970          deletion of breakpoints.  */
2971       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2972         continue;
2973
2974       switch_to_program_space_and_thread (bl->pspace);
2975
2976       /* For targets that support global breakpoints, there's no need
2977          to select an inferior to insert breakpoint to.  In fact, even
2978          if we aren't attached to any process yet, we should still
2979          insert breakpoints.  */
2980       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2981           && ptid_equal (inferior_ptid, null_ptid))
2982         continue;
2983
2984       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2985                                     &hw_breakpoint_error, &hw_bp_details_reported);
2986       if (val)
2987         error_flag = val;
2988     }
2989
2990   if (error_flag)
2991     {
2992       target_terminal::ours_for_output ();
2993       error_stream (tmp_error_stream);
2994     }
2995 }
2996
2997 /* Used when starting or continuing the program.  */
2998
2999 static void
3000 insert_breakpoint_locations (void)
3001 {
3002   struct breakpoint *bpt;
3003   struct bp_location *bl, **blp_tmp;
3004   int error_flag = 0;
3005   int val = 0;
3006   int disabled_breaks = 0;
3007   int hw_breakpoint_error = 0;
3008   int hw_bp_error_explained_already = 0;
3009
3010   string_file tmp_error_stream;
3011
3012   /* Explicitly mark the warning -- this will only be printed if
3013      there was an error.  */
3014   tmp_error_stream.puts ("Warning:\n");
3015
3016   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3017
3018   ALL_BP_LOCATIONS (bl, blp_tmp)
3019     {
3020       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3021         continue;
3022
3023       /* There is no point inserting thread-specific breakpoints if
3024          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3025          has BL->OWNER always non-NULL.  */
3026       if (bl->owner->thread != -1
3027           && !valid_global_thread_id (bl->owner->thread))
3028         continue;
3029
3030       switch_to_program_space_and_thread (bl->pspace);
3031
3032       /* For targets that support global breakpoints, there's no need
3033          to select an inferior to insert breakpoint to.  In fact, even
3034          if we aren't attached to any process yet, we should still
3035          insert breakpoints.  */
3036       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3037           && ptid_equal (inferior_ptid, null_ptid))
3038         continue;
3039
3040       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3041                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3042       if (val)
3043         error_flag = val;
3044     }
3045
3046   /* If we failed to insert all locations of a watchpoint, remove
3047      them, as half-inserted watchpoint is of limited use.  */
3048   ALL_BREAKPOINTS (bpt)  
3049     {
3050       int some_failed = 0;
3051       struct bp_location *loc;
3052
3053       if (!is_hardware_watchpoint (bpt))
3054         continue;
3055
3056       if (!breakpoint_enabled (bpt))
3057         continue;
3058
3059       if (bpt->disposition == disp_del_at_next_stop)
3060         continue;
3061       
3062       for (loc = bpt->loc; loc; loc = loc->next)
3063         if (!loc->inserted && should_be_inserted (loc))
3064           {
3065             some_failed = 1;
3066             break;
3067           }
3068       if (some_failed)
3069         {
3070           for (loc = bpt->loc; loc; loc = loc->next)
3071             if (loc->inserted)
3072               remove_breakpoint (loc);
3073
3074           hw_breakpoint_error = 1;
3075           tmp_error_stream.printf ("Could not insert "
3076                                    "hardware watchpoint %d.\n",
3077                                    bpt->number);
3078           error_flag = -1;
3079         }
3080     }
3081
3082   if (error_flag)
3083     {
3084       /* If a hardware breakpoint or watchpoint was inserted, add a
3085          message about possibly exhausted resources.  */
3086       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3087         {
3088           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3089 You may have requested too many hardware breakpoints/watchpoints.\n");
3090         }
3091       target_terminal::ours_for_output ();
3092       error_stream (tmp_error_stream);
3093     }
3094 }
3095
3096 /* Used when the program stops.
3097    Returns zero if successful, or non-zero if there was a problem
3098    removing a breakpoint location.  */
3099
3100 int
3101 remove_breakpoints (void)
3102 {
3103   struct bp_location *bl, **blp_tmp;
3104   int val = 0;
3105
3106   ALL_BP_LOCATIONS (bl, blp_tmp)
3107   {
3108     if (bl->inserted && !is_tracepoint (bl->owner))
3109       val |= remove_breakpoint (bl);
3110   }
3111   return val;
3112 }
3113
3114 /* When a thread exits, remove breakpoints that are related to
3115    that thread.  */
3116
3117 static void
3118 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3119 {
3120   struct breakpoint *b, *b_tmp;
3121
3122   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3123     {
3124       if (b->thread == tp->global_num && user_breakpoint_p (b))
3125         {
3126           b->disposition = disp_del_at_next_stop;
3127
3128           printf_filtered (_("\
3129 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3130                            b->number, print_thread_id (tp));
3131
3132           /* Hide it from the user.  */
3133           b->number = 0;
3134        }
3135     }
3136 }
3137
3138 /* Remove breakpoints of process PID.  */
3139
3140 int
3141 remove_breakpoints_pid (int pid)
3142 {
3143   struct bp_location *bl, **blp_tmp;
3144   int val;
3145   struct inferior *inf = find_inferior_pid (pid);
3146
3147   ALL_BP_LOCATIONS (bl, blp_tmp)
3148   {
3149     if (bl->pspace != inf->pspace)
3150       continue;
3151
3152     if (bl->inserted && !bl->target_info.persist)
3153       {
3154         val = remove_breakpoint (bl);
3155         if (val != 0)
3156           return val;
3157       }
3158   }
3159   return 0;
3160 }
3161
3162 int
3163 reattach_breakpoints (int pid)
3164 {
3165   struct bp_location *bl, **blp_tmp;
3166   int val;
3167   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3168   struct inferior *inf;
3169   struct thread_info *tp;
3170
3171   tp = any_live_thread_of_process (pid);
3172   if (tp == NULL)
3173     return 1;
3174
3175   inf = find_inferior_pid (pid);
3176
3177   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3178   inferior_ptid = tp->ptid;
3179
3180   string_file tmp_error_stream;
3181
3182   ALL_BP_LOCATIONS (bl, blp_tmp)
3183   {
3184     if (bl->pspace != inf->pspace)
3185       continue;
3186
3187     if (bl->inserted)
3188       {
3189         bl->inserted = 0;
3190         val = insert_bp_location (bl, &tmp_error_stream, &dummy1, &dummy2, &dummy3);
3191         if (val != 0)
3192           return val;
3193       }
3194   }
3195   return 0;
3196 }
3197
3198 static int internal_breakpoint_number = -1;
3199
3200 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3201    If INTERNAL is non-zero, the breakpoint number will be populated
3202    from internal_breakpoint_number and that variable decremented.
3203    Otherwise the breakpoint number will be populated from
3204    breakpoint_count and that value incremented.  Internal breakpoints
3205    do not set the internal var bpnum.  */
3206 static void
3207 set_breakpoint_number (int internal, struct breakpoint *b)
3208 {
3209   if (internal)
3210     b->number = internal_breakpoint_number--;
3211   else
3212     {
3213       set_breakpoint_count (breakpoint_count + 1);
3214       b->number = breakpoint_count;
3215     }
3216 }
3217
3218 static struct breakpoint *
3219 create_internal_breakpoint (struct gdbarch *gdbarch,
3220                             CORE_ADDR address, enum bptype type,
3221                             const struct breakpoint_ops *ops)
3222 {
3223   symtab_and_line sal;
3224   sal.pc = address;
3225   sal.section = find_pc_overlay (sal.pc);
3226   sal.pspace = current_program_space;
3227
3228   breakpoint *b = set_raw_breakpoint (gdbarch, sal, type, ops);
3229   b->number = internal_breakpoint_number--;
3230   b->disposition = disp_donttouch;
3231
3232   return b;
3233 }
3234
3235 static const char *const longjmp_names[] =
3236   {
3237     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3238   };
3239 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3240
3241 /* Per-objfile data private to breakpoint.c.  */
3242 struct breakpoint_objfile_data
3243 {
3244   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3245   struct bound_minimal_symbol overlay_msym;
3246
3247   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3248   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3249
3250   /* True if we have looked for longjmp probes.  */
3251   int longjmp_searched;
3252
3253   /* SystemTap probe points for longjmp (if any).  */
3254   VEC (probe_p) *longjmp_probes;
3255
3256   /* Minimal symbol for "std::terminate()" (if any).  */
3257   struct bound_minimal_symbol terminate_msym;
3258
3259   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3260   struct bound_minimal_symbol exception_msym;
3261
3262   /* True if we have looked for exception probes.  */
3263   int exception_searched;
3264
3265   /* SystemTap probe points for unwinding (if any).  */
3266   VEC (probe_p) *exception_probes;
3267 };
3268
3269 static const struct objfile_data *breakpoint_objfile_key;
3270
3271 /* Minimal symbol not found sentinel.  */
3272 static struct minimal_symbol msym_not_found;
3273
3274 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3275
3276 static int
3277 msym_not_found_p (const struct minimal_symbol *msym)
3278 {
3279   return msym == &msym_not_found;
3280 }
3281
3282 /* Return per-objfile data needed by breakpoint.c.
3283    Allocate the data if necessary.  */
3284
3285 static struct breakpoint_objfile_data *
3286 get_breakpoint_objfile_data (struct objfile *objfile)
3287 {
3288   struct breakpoint_objfile_data *bp_objfile_data;
3289
3290   bp_objfile_data = ((struct breakpoint_objfile_data *)
3291                      objfile_data (objfile, breakpoint_objfile_key));
3292   if (bp_objfile_data == NULL)
3293     {
3294       bp_objfile_data =
3295         XOBNEW (&objfile->objfile_obstack, struct breakpoint_objfile_data);
3296
3297       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3298       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3299     }
3300   return bp_objfile_data;
3301 }
3302
3303 static void
3304 free_breakpoint_probes (struct objfile *obj, void *data)
3305 {
3306   struct breakpoint_objfile_data *bp_objfile_data
3307     = (struct breakpoint_objfile_data *) data;
3308
3309   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3310   VEC_free (probe_p, bp_objfile_data->exception_probes);
3311 }
3312
3313 static void
3314 create_overlay_event_breakpoint (void)
3315 {
3316   struct objfile *objfile;
3317   const char *const func_name = "_ovly_debug_event";
3318
3319   ALL_OBJFILES (objfile)
3320     {
3321       struct breakpoint *b;
3322       struct breakpoint_objfile_data *bp_objfile_data;
3323       CORE_ADDR addr;
3324       struct explicit_location explicit_loc;
3325
3326       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3327
3328       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3329         continue;
3330
3331       if (bp_objfile_data->overlay_msym.minsym == NULL)
3332         {
3333           struct bound_minimal_symbol m;
3334
3335           m = lookup_minimal_symbol_text (func_name, objfile);
3336           if (m.minsym == NULL)
3337             {
3338               /* Avoid future lookups in this objfile.  */
3339               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3340               continue;
3341             }
3342           bp_objfile_data->overlay_msym = m;
3343         }
3344
3345       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3346       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3347                                       bp_overlay_event,
3348                                       &internal_breakpoint_ops);
3349       initialize_explicit_location (&explicit_loc);
3350       explicit_loc.function_name = ASTRDUP (func_name);
3351       b->location = new_explicit_location (&explicit_loc);
3352
3353       if (overlay_debugging == ovly_auto)
3354         {
3355           b->enable_state = bp_enabled;
3356           overlay_events_enabled = 1;
3357         }
3358       else
3359        {
3360          b->enable_state = bp_disabled;
3361          overlay_events_enabled = 0;
3362        }
3363     }
3364 }
3365
3366 static void
3367 create_longjmp_master_breakpoint (void)
3368 {
3369   struct program_space *pspace;
3370
3371   scoped_restore_current_program_space restore_pspace;
3372
3373   ALL_PSPACES (pspace)
3374   {
3375     struct objfile *objfile;
3376
3377     set_current_program_space (pspace);
3378
3379     ALL_OBJFILES (objfile)
3380     {
3381       int i;
3382       struct gdbarch *gdbarch;
3383       struct breakpoint_objfile_data *bp_objfile_data;
3384
3385       gdbarch = get_objfile_arch (objfile);
3386
3387       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3388
3389       if (!bp_objfile_data->longjmp_searched)
3390         {
3391           VEC (probe_p) *ret;
3392
3393           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3394           if (ret != NULL)
3395             {
3396               /* We are only interested in checking one element.  */
3397               struct probe *p = VEC_index (probe_p, ret, 0);
3398
3399               if (!can_evaluate_probe_arguments (p))
3400                 {
3401                   /* We cannot use the probe interface here, because it does
3402                      not know how to evaluate arguments.  */
3403                   VEC_free (probe_p, ret);
3404                   ret = NULL;
3405                 }
3406             }
3407           bp_objfile_data->longjmp_probes = ret;
3408           bp_objfile_data->longjmp_searched = 1;
3409         }
3410
3411       if (bp_objfile_data->longjmp_probes != NULL)
3412         {
3413           int i;
3414           struct probe *probe;
3415           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3416
3417           for (i = 0;
3418                VEC_iterate (probe_p,
3419                             bp_objfile_data->longjmp_probes,
3420                             i, probe);
3421                ++i)
3422             {
3423               struct breakpoint *b;
3424
3425               b = create_internal_breakpoint (gdbarch,
3426                                               get_probe_address (probe,
3427                                                                  objfile),
3428                                               bp_longjmp_master,
3429                                               &internal_breakpoint_ops);
3430               b->location = new_probe_location ("-probe-stap libc:longjmp");
3431               b->enable_state = bp_disabled;
3432             }
3433
3434           continue;
3435         }
3436
3437       if (!gdbarch_get_longjmp_target_p (gdbarch))
3438         continue;
3439
3440       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3441         {
3442           struct breakpoint *b;
3443           const char *func_name;
3444           CORE_ADDR addr;
3445           struct explicit_location explicit_loc;
3446
3447           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3448             continue;
3449
3450           func_name = longjmp_names[i];
3451           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3452             {
3453               struct bound_minimal_symbol m;
3454
3455               m = lookup_minimal_symbol_text (func_name, objfile);
3456               if (m.minsym == NULL)
3457                 {
3458                   /* Prevent future lookups in this objfile.  */
3459                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3460                   continue;
3461                 }
3462               bp_objfile_data->longjmp_msym[i] = m;
3463             }
3464
3465           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3466           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3467                                           &internal_breakpoint_ops);
3468           initialize_explicit_location (&explicit_loc);
3469           explicit_loc.function_name = ASTRDUP (func_name);
3470           b->location = new_explicit_location (&explicit_loc);
3471           b->enable_state = bp_disabled;
3472         }
3473     }
3474   }
3475 }
3476
3477 /* Create a master std::terminate breakpoint.  */
3478 static void
3479 create_std_terminate_master_breakpoint (void)
3480 {
3481   struct program_space *pspace;
3482   const char *const func_name = "std::terminate()";
3483
3484   scoped_restore_current_program_space restore_pspace;
3485
3486   ALL_PSPACES (pspace)
3487   {
3488     struct objfile *objfile;
3489     CORE_ADDR addr;
3490
3491     set_current_program_space (pspace);
3492
3493     ALL_OBJFILES (objfile)
3494     {
3495       struct breakpoint *b;
3496       struct breakpoint_objfile_data *bp_objfile_data;
3497       struct explicit_location explicit_loc;
3498
3499       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3500
3501       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3502         continue;
3503
3504       if (bp_objfile_data->terminate_msym.minsym == NULL)
3505         {
3506           struct bound_minimal_symbol m;
3507
3508           m = lookup_minimal_symbol (func_name, NULL, objfile);
3509           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3510                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3511             {
3512               /* Prevent future lookups in this objfile.  */
3513               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3514               continue;
3515             }
3516           bp_objfile_data->terminate_msym = m;
3517         }
3518
3519       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3520       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3521                                       bp_std_terminate_master,
3522                                       &internal_breakpoint_ops);
3523       initialize_explicit_location (&explicit_loc);
3524       explicit_loc.function_name = ASTRDUP (func_name);
3525       b->location = new_explicit_location (&explicit_loc);
3526       b->enable_state = bp_disabled;
3527     }
3528   }
3529 }
3530
3531 /* Install a master breakpoint on the unwinder's debug hook.  */
3532
3533 static void
3534 create_exception_master_breakpoint (void)
3535 {
3536   struct objfile *objfile;
3537   const char *const func_name = "_Unwind_DebugHook";
3538
3539   ALL_OBJFILES (objfile)
3540     {
3541       struct breakpoint *b;
3542       struct gdbarch *gdbarch;
3543       struct breakpoint_objfile_data *bp_objfile_data;
3544       CORE_ADDR addr;
3545       struct explicit_location explicit_loc;
3546
3547       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3548
3549       /* We prefer the SystemTap probe point if it exists.  */
3550       if (!bp_objfile_data->exception_searched)
3551         {
3552           VEC (probe_p) *ret;
3553
3554           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3555
3556           if (ret != NULL)
3557             {
3558               /* We are only interested in checking one element.  */
3559               struct probe *p = VEC_index (probe_p, ret, 0);
3560
3561               if (!can_evaluate_probe_arguments (p))
3562                 {
3563                   /* We cannot use the probe interface here, because it does
3564                      not know how to evaluate arguments.  */
3565                   VEC_free (probe_p, ret);
3566                   ret = NULL;
3567                 }
3568             }
3569           bp_objfile_data->exception_probes = ret;
3570           bp_objfile_data->exception_searched = 1;
3571         }
3572
3573       if (bp_objfile_data->exception_probes != NULL)
3574         {
3575           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3576           int i;
3577           struct probe *probe;
3578
3579           for (i = 0;
3580                VEC_iterate (probe_p,
3581                             bp_objfile_data->exception_probes,
3582                             i, probe);
3583                ++i)
3584             {
3585               struct breakpoint *b;
3586
3587               b = create_internal_breakpoint (gdbarch,
3588                                               get_probe_address (probe,
3589                                                                  objfile),
3590                                               bp_exception_master,
3591                                               &internal_breakpoint_ops);
3592               b->location = new_probe_location ("-probe-stap libgcc:unwind");
3593               b->enable_state = bp_disabled;
3594             }
3595
3596           continue;
3597         }
3598
3599       /* Otherwise, try the hook function.  */
3600
3601       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3602         continue;
3603
3604       gdbarch = get_objfile_arch (objfile);
3605
3606       if (bp_objfile_data->exception_msym.minsym == NULL)
3607         {
3608           struct bound_minimal_symbol debug_hook;
3609
3610           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3611           if (debug_hook.minsym == NULL)
3612             {
3613               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3614               continue;
3615             }
3616
3617           bp_objfile_data->exception_msym = debug_hook;
3618         }
3619
3620       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3621       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3622                                                  &current_target);
3623       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3624                                       &internal_breakpoint_ops);
3625       initialize_explicit_location (&explicit_loc);
3626       explicit_loc.function_name = ASTRDUP (func_name);
3627       b->location = new_explicit_location (&explicit_loc);
3628       b->enable_state = bp_disabled;
3629     }
3630 }
3631
3632 /* Does B have a location spec?  */
3633
3634 static int
3635 breakpoint_event_location_empty_p (const struct breakpoint *b)
3636 {
3637   return b->location != NULL && event_location_empty_p (b->location.get ());
3638 }
3639
3640 void
3641 update_breakpoints_after_exec (void)
3642 {
3643   struct breakpoint *b, *b_tmp;
3644   struct bp_location *bploc, **bplocp_tmp;
3645
3646   /* We're about to delete breakpoints from GDB's lists.  If the
3647      INSERTED flag is true, GDB will try to lift the breakpoints by
3648      writing the breakpoints' "shadow contents" back into memory.  The
3649      "shadow contents" are NOT valid after an exec, so GDB should not
3650      do that.  Instead, the target is responsible from marking
3651      breakpoints out as soon as it detects an exec.  We don't do that
3652      here instead, because there may be other attempts to delete
3653      breakpoints after detecting an exec and before reaching here.  */
3654   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3655     if (bploc->pspace == current_program_space)
3656       gdb_assert (!bploc->inserted);
3657
3658   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3659   {
3660     if (b->pspace != current_program_space)
3661       continue;
3662
3663     /* Solib breakpoints must be explicitly reset after an exec().  */
3664     if (b->type == bp_shlib_event)
3665       {
3666         delete_breakpoint (b);
3667         continue;
3668       }
3669
3670     /* JIT breakpoints must be explicitly reset after an exec().  */
3671     if (b->type == bp_jit_event)
3672       {
3673         delete_breakpoint (b);
3674         continue;
3675       }
3676
3677     /* Thread event breakpoints must be set anew after an exec(),
3678        as must overlay event and longjmp master breakpoints.  */
3679     if (b->type == bp_thread_event || b->type == bp_overlay_event
3680         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3681         || b->type == bp_exception_master)
3682       {
3683         delete_breakpoint (b);
3684         continue;
3685       }
3686
3687     /* Step-resume breakpoints are meaningless after an exec().  */
3688     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3689       {
3690         delete_breakpoint (b);
3691         continue;
3692       }
3693
3694     /* Just like single-step breakpoints.  */
3695     if (b->type == bp_single_step)
3696       {
3697         delete_breakpoint (b);
3698         continue;
3699       }
3700
3701     /* Longjmp and longjmp-resume breakpoints are also meaningless
3702        after an exec.  */
3703     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3704         || b->type == bp_longjmp_call_dummy
3705         || b->type == bp_exception || b->type == bp_exception_resume)
3706       {
3707         delete_breakpoint (b);
3708         continue;
3709       }
3710
3711     if (b->type == bp_catchpoint)
3712       {
3713         /* For now, none of the bp_catchpoint breakpoints need to
3714            do anything at this point.  In the future, if some of
3715            the catchpoints need to something, we will need to add
3716            a new method, and call this method from here.  */
3717         continue;
3718       }
3719
3720     /* bp_finish is a special case.  The only way we ought to be able
3721        to see one of these when an exec() has happened, is if the user
3722        caught a vfork, and then said "finish".  Ordinarily a finish just
3723        carries them to the call-site of the current callee, by setting
3724        a temporary bp there and resuming.  But in this case, the finish
3725        will carry them entirely through the vfork & exec.
3726
3727        We don't want to allow a bp_finish to remain inserted now.  But
3728        we can't safely delete it, 'cause finish_command has a handle to
3729        the bp on a bpstat, and will later want to delete it.  There's a
3730        chance (and I've seen it happen) that if we delete the bp_finish
3731        here, that its storage will get reused by the time finish_command
3732        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3733        We really must allow finish_command to delete a bp_finish.
3734
3735        In the absence of a general solution for the "how do we know
3736        it's safe to delete something others may have handles to?"
3737        problem, what we'll do here is just uninsert the bp_finish, and
3738        let finish_command delete it.
3739
3740        (We know the bp_finish is "doomed" in the sense that it's
3741        momentary, and will be deleted as soon as finish_command sees
3742        the inferior stopped.  So it doesn't matter that the bp's
3743        address is probably bogus in the new a.out, unlike e.g., the
3744        solib breakpoints.)  */
3745
3746     if (b->type == bp_finish)
3747       {
3748         continue;
3749       }
3750
3751     /* Without a symbolic address, we have little hope of the
3752        pre-exec() address meaning the same thing in the post-exec()
3753        a.out.  */
3754     if (breakpoint_event_location_empty_p (b))
3755       {
3756         delete_breakpoint (b);
3757         continue;
3758       }
3759   }
3760 }
3761
3762 int
3763 detach_breakpoints (ptid_t ptid)
3764 {
3765   struct bp_location *bl, **blp_tmp;
3766   int val = 0;
3767   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3768   struct inferior *inf = current_inferior ();
3769
3770   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3771     error (_("Cannot detach breakpoints of inferior_ptid"));
3772
3773   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3774   inferior_ptid = ptid;
3775   ALL_BP_LOCATIONS (bl, blp_tmp)
3776   {
3777     if (bl->pspace != inf->pspace)
3778       continue;
3779
3780     /* This function must physically remove breakpoints locations
3781        from the specified ptid, without modifying the breakpoint
3782        package's state.  Locations of type bp_loc_other are only
3783        maintained at GDB side.  So, there is no need to remove
3784        these bp_loc_other locations.  Moreover, removing these
3785        would modify the breakpoint package's state.  */
3786     if (bl->loc_type == bp_loc_other)
3787       continue;
3788
3789     if (bl->inserted)
3790       val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3791   }
3792
3793   return val;
3794 }
3795
3796 /* Remove the breakpoint location BL from the current address space.
3797    Note that this is used to detach breakpoints from a child fork.
3798    When we get here, the child isn't in the inferior list, and neither
3799    do we have objects to represent its address space --- we should
3800    *not* look at bl->pspace->aspace here.  */
3801
3802 static int
3803 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3804 {
3805   int val;
3806
3807   /* BL is never in moribund_locations by our callers.  */
3808   gdb_assert (bl->owner != NULL);
3809
3810   /* The type of none suggests that owner is actually deleted.
3811      This should not ever happen.  */
3812   gdb_assert (bl->owner->type != bp_none);
3813
3814   if (bl->loc_type == bp_loc_software_breakpoint
3815       || bl->loc_type == bp_loc_hardware_breakpoint)
3816     {
3817       /* "Normal" instruction breakpoint: either the standard
3818          trap-instruction bp (bp_breakpoint), or a
3819          bp_hardware_breakpoint.  */
3820
3821       /* First check to see if we have to handle an overlay.  */
3822       if (overlay_debugging == ovly_off
3823           || bl->section == NULL
3824           || !(section_is_overlay (bl->section)))
3825         {
3826           /* No overlay handling: just remove the breakpoint.  */
3827
3828           /* If we're trying to uninsert a memory breakpoint that we
3829              know is set in a dynamic object that is marked
3830              shlib_disabled, then either the dynamic object was
3831              removed with "remove-symbol-file" or with
3832              "nosharedlibrary".  In the former case, we don't know
3833              whether another dynamic object might have loaded over the
3834              breakpoint's address -- the user might well let us know
3835              about it next with add-symbol-file (the whole point of
3836              add-symbol-file is letting the user manually maintain a
3837              list of dynamically loaded objects).  If we have the
3838              breakpoint's shadow memory, that is, this is a software
3839              breakpoint managed by GDB, check whether the breakpoint
3840              is still inserted in memory, to avoid overwriting wrong
3841              code with stale saved shadow contents.  Note that HW
3842              breakpoints don't have shadow memory, as they're
3843              implemented using a mechanism that is not dependent on
3844              being able to modify the target's memory, and as such
3845              they should always be removed.  */
3846           if (bl->shlib_disabled
3847               && bl->target_info.shadow_len != 0
3848               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3849             val = 0;
3850           else
3851             val = bl->owner->ops->remove_location (bl, reason);
3852         }
3853       else
3854         {
3855           /* This breakpoint is in an overlay section.
3856              Did we set a breakpoint at the LMA?  */
3857           if (!overlay_events_enabled)
3858               {
3859                 /* Yes -- overlay event support is not active, so we
3860                    should have set a breakpoint at the LMA.  Remove it.  
3861                 */
3862                 /* Ignore any failures: if the LMA is in ROM, we will
3863                    have already warned when we failed to insert it.  */
3864                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3865                   target_remove_hw_breakpoint (bl->gdbarch,
3866                                                &bl->overlay_target_info);
3867                 else
3868                   target_remove_breakpoint (bl->gdbarch,
3869                                             &bl->overlay_target_info,
3870                                             reason);
3871               }
3872           /* Did we set a breakpoint at the VMA? 
3873              If so, we will have marked the breakpoint 'inserted'.  */
3874           if (bl->inserted)
3875             {
3876               /* Yes -- remove it.  Previously we did not bother to
3877                  remove the breakpoint if the section had been
3878                  unmapped, but let's not rely on that being safe.  We
3879                  don't know what the overlay manager might do.  */
3880
3881               /* However, we should remove *software* breakpoints only
3882                  if the section is still mapped, or else we overwrite
3883                  wrong code with the saved shadow contents.  */
3884               if (bl->loc_type == bp_loc_hardware_breakpoint
3885                   || section_is_mapped (bl->section))
3886                 val = bl->owner->ops->remove_location (bl, reason);
3887               else
3888                 val = 0;
3889             }
3890           else
3891             {
3892               /* No -- not inserted, so no need to remove.  No error.  */
3893               val = 0;
3894             }
3895         }
3896
3897       /* In some cases, we might not be able to remove a breakpoint in
3898          a shared library that has already been removed, but we have
3899          not yet processed the shlib unload event.  Similarly for an
3900          unloaded add-symbol-file object - the user might not yet have
3901          had the chance to remove-symbol-file it.  shlib_disabled will
3902          be set if the library/object has already been removed, but
3903          the breakpoint hasn't been uninserted yet, e.g., after
3904          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3905          always-inserted mode.  */
3906       if (val
3907           && (bl->loc_type == bp_loc_software_breakpoint
3908               && (bl->shlib_disabled
3909                   || solib_name_from_address (bl->pspace, bl->address)
3910                   || shared_objfile_contains_address_p (bl->pspace,
3911                                                         bl->address))))
3912         val = 0;
3913
3914       if (val)
3915         return val;
3916       bl->inserted = (reason == DETACH_BREAKPOINT);
3917     }
3918   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3919     {
3920       gdb_assert (bl->owner->ops != NULL
3921                   && bl->owner->ops->remove_location != NULL);
3922
3923       bl->inserted = (reason == DETACH_BREAKPOINT);
3924       bl->owner->ops->remove_location (bl, reason);
3925
3926       /* Failure to remove any of the hardware watchpoints comes here.  */
3927       if (reason == REMOVE_BREAKPOINT && bl->inserted)
3928         warning (_("Could not remove hardware watchpoint %d."),
3929                  bl->owner->number);
3930     }
3931   else if (bl->owner->type == bp_catchpoint
3932            && breakpoint_enabled (bl->owner)
3933            && !bl->duplicate)
3934     {
3935       gdb_assert (bl->owner->ops != NULL
3936                   && bl->owner->ops->remove_location != NULL);
3937
3938       val = bl->owner->ops->remove_location (bl, reason);
3939       if (val)
3940         return val;
3941
3942       bl->inserted = (reason == DETACH_BREAKPOINT);
3943     }
3944
3945   return 0;
3946 }
3947
3948 static int
3949 remove_breakpoint (struct bp_location *bl)
3950 {
3951   /* BL is never in moribund_locations by our callers.  */
3952   gdb_assert (bl->owner != NULL);
3953
3954   /* The type of none suggests that owner is actually deleted.
3955      This should not ever happen.  */
3956   gdb_assert (bl->owner->type != bp_none);
3957
3958   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3959
3960   switch_to_program_space_and_thread (bl->pspace);
3961
3962   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
3963 }
3964
3965 /* Clear the "inserted" flag in all breakpoints.  */
3966
3967 void
3968 mark_breakpoints_out (void)
3969 {
3970   struct bp_location *bl, **blp_tmp;
3971
3972   ALL_BP_LOCATIONS (bl, blp_tmp)
3973     if (bl->pspace == current_program_space)
3974       bl->inserted = 0;
3975 }
3976
3977 /* Clear the "inserted" flag in all breakpoints and delete any
3978    breakpoints which should go away between runs of the program.
3979
3980    Plus other such housekeeping that has to be done for breakpoints
3981    between runs.
3982
3983    Note: this function gets called at the end of a run (by
3984    generic_mourn_inferior) and when a run begins (by
3985    init_wait_for_inferior).  */
3986
3987
3988
3989 void
3990 breakpoint_init_inferior (enum inf_context context)
3991 {
3992   struct breakpoint *b, *b_tmp;
3993   struct bp_location *bl;
3994   int ix;
3995   struct program_space *pspace = current_program_space;
3996
3997   /* If breakpoint locations are shared across processes, then there's
3998      nothing to do.  */
3999   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4000     return;
4001
4002   mark_breakpoints_out ();
4003
4004   ALL_BREAKPOINTS_SAFE (b, b_tmp)
4005   {
4006     if (b->loc && b->loc->pspace != pspace)
4007       continue;
4008
4009     switch (b->type)
4010       {
4011       case bp_call_dummy:
4012       case bp_longjmp_call_dummy:
4013
4014         /* If the call dummy breakpoint is at the entry point it will
4015            cause problems when the inferior is rerun, so we better get
4016            rid of it.  */
4017
4018       case bp_watchpoint_scope:
4019
4020         /* Also get rid of scope breakpoints.  */
4021
4022       case bp_shlib_event:
4023
4024         /* Also remove solib event breakpoints.  Their addresses may
4025            have changed since the last time we ran the program.
4026            Actually we may now be debugging against different target;
4027            and so the solib backend that installed this breakpoint may
4028            not be used in by the target.  E.g.,
4029
4030            (gdb) file prog-linux
4031            (gdb) run               # native linux target
4032            ...
4033            (gdb) kill
4034            (gdb) file prog-win.exe
4035            (gdb) tar rem :9999     # remote Windows gdbserver.
4036         */
4037
4038       case bp_step_resume:
4039
4040         /* Also remove step-resume breakpoints.  */
4041
4042       case bp_single_step:
4043
4044         /* Also remove single-step breakpoints.  */
4045
4046         delete_breakpoint (b);
4047         break;
4048
4049       case bp_watchpoint:
4050       case bp_hardware_watchpoint:
4051       case bp_read_watchpoint:
4052       case bp_access_watchpoint:
4053         {
4054           struct watchpoint *w = (struct watchpoint *) b;
4055
4056           /* Likewise for watchpoints on local expressions.  */
4057           if (w->exp_valid_block != NULL)
4058             delete_breakpoint (b);
4059           else
4060             {
4061               /* Get rid of existing locations, which are no longer
4062                  valid.  New ones will be created in
4063                  update_watchpoint, when the inferior is restarted.
4064                  The next update_global_location_list call will
4065                  garbage collect them.  */
4066               b->loc = NULL;
4067
4068               if (context == inf_starting)
4069                 {
4070                   /* Reset val field to force reread of starting value in
4071                      insert_breakpoints.  */
4072                   if (w->val)
4073                     value_free (w->val);
4074                   w->val = NULL;
4075                   w->val_valid = 0;
4076                 }
4077             }
4078         }
4079         break;
4080       default:
4081         break;
4082       }
4083   }
4084
4085   /* Get rid of the moribund locations.  */
4086   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4087     decref_bp_location (&bl);
4088   VEC_free (bp_location_p, moribund_locations);
4089 }
4090
4091 /* These functions concern about actual breakpoints inserted in the
4092    target --- to e.g. check if we need to do decr_pc adjustment or if
4093    we need to hop over the bkpt --- so we check for address space
4094    match, not program space.  */
4095
4096 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4097    exists at PC.  It returns ordinary_breakpoint_here if it's an
4098    ordinary breakpoint, or permanent_breakpoint_here if it's a
4099    permanent breakpoint.
4100    - When continuing from a location with an ordinary breakpoint, we
4101      actually single step once before calling insert_breakpoints.
4102    - When continuing from a location with a permanent breakpoint, we
4103      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4104      the target, to advance the PC past the breakpoint.  */
4105
4106 enum breakpoint_here
4107 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4108 {
4109   struct bp_location *bl, **blp_tmp;
4110   int any_breakpoint_here = 0;
4111
4112   ALL_BP_LOCATIONS (bl, blp_tmp)
4113     {
4114       if (bl->loc_type != bp_loc_software_breakpoint
4115           && bl->loc_type != bp_loc_hardware_breakpoint)
4116         continue;
4117
4118       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4119       if ((breakpoint_enabled (bl->owner)
4120            || bl->permanent)
4121           && breakpoint_location_address_match (bl, aspace, pc))
4122         {
4123           if (overlay_debugging 
4124               && section_is_overlay (bl->section)
4125               && !section_is_mapped (bl->section))
4126             continue;           /* unmapped overlay -- can't be a match */
4127           else if (bl->permanent)
4128             return permanent_breakpoint_here;
4129           else
4130             any_breakpoint_here = 1;
4131         }
4132     }
4133
4134   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4135 }
4136
4137 /* See breakpoint.h.  */
4138
4139 int
4140 breakpoint_in_range_p (struct address_space *aspace,
4141                        CORE_ADDR addr, ULONGEST len)
4142 {
4143   struct bp_location *bl, **blp_tmp;
4144
4145   ALL_BP_LOCATIONS (bl, blp_tmp)
4146     {
4147       if (bl->loc_type != bp_loc_software_breakpoint
4148           && bl->loc_type != bp_loc_hardware_breakpoint)
4149         continue;
4150
4151       if ((breakpoint_enabled (bl->owner)
4152            || bl->permanent)
4153           && breakpoint_location_address_range_overlap (bl, aspace,
4154                                                         addr, len))
4155         {
4156           if (overlay_debugging
4157               && section_is_overlay (bl->section)
4158               && !section_is_mapped (bl->section))
4159             {
4160               /* Unmapped overlay -- can't be a match.  */
4161               continue;
4162             }
4163
4164           return 1;
4165         }
4166     }
4167
4168   return 0;
4169 }
4170
4171 /* Return true if there's a moribund breakpoint at PC.  */
4172
4173 int
4174 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4175 {
4176   struct bp_location *loc;
4177   int ix;
4178
4179   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4180     if (breakpoint_location_address_match (loc, aspace, pc))
4181       return 1;
4182
4183   return 0;
4184 }
4185
4186 /* Returns non-zero iff BL is inserted at PC, in address space
4187    ASPACE.  */
4188
4189 static int
4190 bp_location_inserted_here_p (struct bp_location *bl,
4191                              struct address_space *aspace, CORE_ADDR pc)
4192 {
4193   if (bl->inserted
4194       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4195                                    aspace, pc))
4196     {
4197       if (overlay_debugging
4198           && section_is_overlay (bl->section)
4199           && !section_is_mapped (bl->section))
4200         return 0;               /* unmapped overlay -- can't be a match */
4201       else
4202         return 1;
4203     }
4204   return 0;
4205 }
4206
4207 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4208
4209 int
4210 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4211 {
4212   struct bp_location **blp, **blp_tmp = NULL;
4213
4214   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4215     {
4216       struct bp_location *bl = *blp;
4217
4218       if (bl->loc_type != bp_loc_software_breakpoint
4219           && bl->loc_type != bp_loc_hardware_breakpoint)
4220         continue;
4221
4222       if (bp_location_inserted_here_p (bl, aspace, pc))
4223         return 1;
4224     }
4225   return 0;
4226 }
4227
4228 /* This function returns non-zero iff there is a software breakpoint
4229    inserted at PC.  */
4230
4231 int
4232 software_breakpoint_inserted_here_p (struct address_space *aspace,
4233                                      CORE_ADDR pc)
4234 {
4235   struct bp_location **blp, **blp_tmp = NULL;
4236
4237   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4238     {
4239       struct bp_location *bl = *blp;
4240
4241       if (bl->loc_type != bp_loc_software_breakpoint)
4242         continue;
4243
4244       if (bp_location_inserted_here_p (bl, aspace, pc))
4245         return 1;
4246     }
4247
4248   return 0;
4249 }
4250
4251 /* See breakpoint.h.  */
4252
4253 int
4254 hardware_breakpoint_inserted_here_p (struct address_space *aspace,
4255                                      CORE_ADDR pc)
4256 {
4257   struct bp_location **blp, **blp_tmp = NULL;
4258
4259   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4260     {
4261       struct bp_location *bl = *blp;
4262
4263       if (bl->loc_type != bp_loc_hardware_breakpoint)
4264         continue;
4265
4266       if (bp_location_inserted_here_p (bl, aspace, pc))
4267         return 1;
4268     }
4269
4270   return 0;
4271 }
4272
4273 int
4274 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4275                                        CORE_ADDR addr, ULONGEST len)
4276 {
4277   struct breakpoint *bpt;
4278
4279   ALL_BREAKPOINTS (bpt)
4280     {
4281       struct bp_location *loc;
4282
4283       if (bpt->type != bp_hardware_watchpoint
4284           && bpt->type != bp_access_watchpoint)
4285         continue;
4286
4287       if (!breakpoint_enabled (bpt))
4288         continue;
4289
4290       for (loc = bpt->loc; loc; loc = loc->next)
4291         if (loc->pspace->aspace == aspace && loc->inserted)
4292           {
4293             CORE_ADDR l, h;
4294
4295             /* Check for intersection.  */
4296             l = std::max<CORE_ADDR> (loc->address, addr);
4297             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4298             if (l < h)
4299               return 1;
4300           }
4301     }
4302   return 0;
4303 }
4304 \f
4305
4306 /* bpstat stuff.  External routines' interfaces are documented
4307    in breakpoint.h.  */
4308
4309 int
4310 is_catchpoint (struct breakpoint *ep)
4311 {
4312   return (ep->type == bp_catchpoint);
4313 }
4314
4315 /* Frees any storage that is part of a bpstat.  Does not walk the
4316    'next' chain.  */
4317
4318 bpstats::~bpstats ()
4319 {
4320   if (old_val != NULL)
4321     value_free (old_val);
4322   if (bp_location_at != NULL)
4323     decref_bp_location (&bp_location_at);
4324 }
4325
4326 /* Clear a bpstat so that it says we are not at any breakpoint.
4327    Also free any storage that is part of a bpstat.  */
4328
4329 void
4330 bpstat_clear (bpstat *bsp)
4331 {
4332   bpstat p;
4333   bpstat q;
4334
4335   if (bsp == 0)
4336     return;
4337   p = *bsp;
4338   while (p != NULL)
4339     {
4340       q = p->next;
4341       delete p;
4342       p = q;
4343     }
4344   *bsp = NULL;
4345 }
4346
4347 bpstats::bpstats (const bpstats &other)
4348   : next (NULL),
4349     bp_location_at (other.bp_location_at),
4350     breakpoint_at (other.breakpoint_at),
4351     commands (other.commands),
4352     old_val (other.old_val),
4353     print (other.print),
4354     stop (other.stop),
4355     print_it (other.print_it)
4356 {
4357   if (old_val != NULL)
4358     {
4359       old_val = value_copy (old_val);
4360       release_value (old_val);
4361     }
4362   incref_bp_location (bp_location_at);
4363 }
4364
4365 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4366    is part of the bpstat is copied as well.  */
4367
4368 bpstat
4369 bpstat_copy (bpstat bs)
4370 {
4371   bpstat p = NULL;
4372   bpstat tmp;
4373   bpstat retval = NULL;
4374
4375   if (bs == NULL)
4376     return bs;
4377
4378   for (; bs != NULL; bs = bs->next)
4379     {
4380       tmp = new bpstats (*bs);
4381
4382       if (p == NULL)
4383         /* This is the first thing in the chain.  */
4384         retval = tmp;
4385       else
4386         p->next = tmp;
4387       p = tmp;
4388     }
4389   p->next = NULL;
4390   return retval;
4391 }
4392
4393 /* Find the bpstat associated with this breakpoint.  */
4394
4395 bpstat
4396 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4397 {
4398   if (bsp == NULL)
4399     return NULL;
4400
4401   for (; bsp != NULL; bsp = bsp->next)
4402     {
4403       if (bsp->breakpoint_at == breakpoint)
4404         return bsp;
4405     }
4406   return NULL;
4407 }
4408
4409 /* See breakpoint.h.  */
4410
4411 int
4412 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4413 {
4414   for (; bsp != NULL; bsp = bsp->next)
4415     {
4416       if (bsp->breakpoint_at == NULL)
4417         {
4418           /* A moribund location can never explain a signal other than
4419              GDB_SIGNAL_TRAP.  */
4420           if (sig == GDB_SIGNAL_TRAP)
4421             return 1;
4422         }
4423       else
4424         {
4425           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4426                                                         sig))
4427             return 1;
4428         }
4429     }
4430
4431   return 0;
4432 }
4433
4434 /* Put in *NUM the breakpoint number of the first breakpoint we are
4435    stopped at.  *BSP upon return is a bpstat which points to the
4436    remaining breakpoints stopped at (but which is not guaranteed to be
4437    good for anything but further calls to bpstat_num).
4438
4439    Return 0 if passed a bpstat which does not indicate any breakpoints.
4440    Return -1 if stopped at a breakpoint that has been deleted since
4441    we set it.
4442    Return 1 otherwise.  */
4443
4444 int
4445 bpstat_num (bpstat *bsp, int *num)
4446 {
4447   struct breakpoint *b;
4448
4449   if ((*bsp) == NULL)
4450     return 0;                   /* No more breakpoint values */
4451
4452   /* We assume we'll never have several bpstats that correspond to a
4453      single breakpoint -- otherwise, this function might return the
4454      same number more than once and this will look ugly.  */
4455   b = (*bsp)->breakpoint_at;
4456   *bsp = (*bsp)->next;
4457   if (b == NULL)
4458     return -1;                  /* breakpoint that's been deleted since */
4459
4460   *num = b->number;             /* We have its number */
4461   return 1;
4462 }
4463
4464 /* See breakpoint.h.  */
4465
4466 void
4467 bpstat_clear_actions (void)
4468 {
4469   struct thread_info *tp;
4470   bpstat bs;
4471
4472   if (ptid_equal (inferior_ptid, null_ptid))
4473     return;
4474
4475   tp = find_thread_ptid (inferior_ptid);
4476   if (tp == NULL)
4477     return;
4478
4479   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4480     {
4481       bs->commands = NULL;
4482
4483       if (bs->old_val != NULL)
4484         {
4485           value_free (bs->old_val);
4486           bs->old_val = NULL;
4487         }
4488     }
4489 }
4490
4491 /* Called when a command is about to proceed the inferior.  */
4492
4493 static void
4494 breakpoint_about_to_proceed (void)
4495 {
4496   if (!ptid_equal (inferior_ptid, null_ptid))
4497     {
4498       struct thread_info *tp = inferior_thread ();
4499
4500       /* Allow inferior function calls in breakpoint commands to not
4501          interrupt the command list.  When the call finishes
4502          successfully, the inferior will be standing at the same
4503          breakpoint as if nothing happened.  */
4504       if (tp->control.in_infcall)
4505         return;
4506     }
4507
4508   breakpoint_proceeded = 1;
4509 }
4510
4511 /* Stub for cleaning up our state if we error-out of a breakpoint
4512    command.  */
4513 static void
4514 cleanup_executing_breakpoints (void *ignore)
4515 {
4516   executing_breakpoint_commands = 0;
4517 }
4518
4519 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4520    or its equivalent.  */
4521
4522 static int
4523 command_line_is_silent (struct command_line *cmd)
4524 {
4525   return cmd && (strcmp ("silent", cmd->line) == 0);
4526 }
4527
4528 /* Execute all the commands associated with all the breakpoints at
4529    this location.  Any of these commands could cause the process to
4530    proceed beyond this point, etc.  We look out for such changes by
4531    checking the global "breakpoint_proceeded" after each command.
4532
4533    Returns true if a breakpoint command resumed the inferior.  In that
4534    case, it is the caller's responsibility to recall it again with the
4535    bpstat of the current thread.  */
4536
4537 static int
4538 bpstat_do_actions_1 (bpstat *bsp)
4539 {
4540   bpstat bs;
4541   struct cleanup *old_chain;
4542   int again = 0;
4543
4544   /* Avoid endless recursion if a `source' command is contained
4545      in bs->commands.  */
4546   if (executing_breakpoint_commands)
4547     return 0;
4548
4549   executing_breakpoint_commands = 1;
4550   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4551
4552   scoped_restore preventer = prevent_dont_repeat ();
4553
4554   /* This pointer will iterate over the list of bpstat's.  */
4555   bs = *bsp;
4556
4557   breakpoint_proceeded = 0;
4558   for (; bs != NULL; bs = bs->next)
4559     {
4560       struct command_line *cmd = NULL;
4561
4562       /* Take ownership of the BSP's command tree, if it has one.
4563
4564          The command tree could legitimately contain commands like
4565          'step' and 'next', which call clear_proceed_status, which
4566          frees stop_bpstat's command tree.  To make sure this doesn't
4567          free the tree we're executing out from under us, we need to
4568          take ownership of the tree ourselves.  Since a given bpstat's
4569          commands are only executed once, we don't need to copy it; we
4570          can clear the pointer in the bpstat, and make sure we free
4571          the tree when we're done.  */
4572       counted_command_line ccmd = bs->commands;
4573       bs->commands = NULL;
4574       if (ccmd != NULL)
4575         cmd = ccmd.get ();
4576       if (command_line_is_silent (cmd))
4577         {
4578           /* The action has been already done by bpstat_stop_status.  */
4579           cmd = cmd->next;
4580         }
4581
4582       while (cmd != NULL)
4583         {
4584           execute_control_command (cmd);
4585
4586           if (breakpoint_proceeded)
4587             break;
4588           else
4589             cmd = cmd->next;
4590         }
4591
4592       if (breakpoint_proceeded)
4593         {
4594           if (current_ui->async)
4595             /* If we are in async mode, then the target might be still
4596                running, not stopped at any breakpoint, so nothing for
4597                us to do here -- just return to the event loop.  */
4598             ;
4599           else
4600             /* In sync mode, when execute_control_command returns
4601                we're already standing on the next breakpoint.
4602                Breakpoint commands for that stop were not run, since
4603                execute_command does not run breakpoint commands --
4604                only command_line_handler does, but that one is not
4605                involved in execution of breakpoint commands.  So, we
4606                can now execute breakpoint commands.  It should be
4607                noted that making execute_command do bpstat actions is
4608                not an option -- in this case we'll have recursive
4609                invocation of bpstat for each breakpoint with a
4610                command, and can easily blow up GDB stack.  Instead, we
4611                return true, which will trigger the caller to recall us
4612                with the new stop_bpstat.  */
4613             again = 1;
4614           break;
4615         }
4616     }
4617   do_cleanups (old_chain);
4618   return again;
4619 }
4620
4621 void
4622 bpstat_do_actions (void)
4623 {
4624   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4625
4626   /* Do any commands attached to breakpoint we are stopped at.  */
4627   while (!ptid_equal (inferior_ptid, null_ptid)
4628          && target_has_execution
4629          && !is_exited (inferior_ptid)
4630          && !is_executing (inferior_ptid))
4631     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4632        and only return when it is stopped at the next breakpoint, we
4633        keep doing breakpoint actions until it returns false to
4634        indicate the inferior was not resumed.  */
4635     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4636       break;
4637
4638   discard_cleanups (cleanup_if_error);
4639 }
4640
4641 /* Print out the (old or new) value associated with a watchpoint.  */
4642
4643 static void
4644 watchpoint_value_print (struct value *val, struct ui_file *stream)
4645 {
4646   if (val == NULL)
4647     fprintf_unfiltered (stream, _("<unreadable>"));
4648   else
4649     {
4650       struct value_print_options opts;
4651       get_user_print_options (&opts);
4652       value_print (val, stream, &opts);
4653     }
4654 }
4655
4656 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4657    debugging multiple threads.  */
4658
4659 void
4660 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4661 {
4662   if (uiout->is_mi_like_p ())
4663     return;
4664
4665   uiout->text ("\n");
4666
4667   if (show_thread_that_caused_stop ())
4668     {
4669       const char *name;
4670       struct thread_info *thr = inferior_thread ();
4671
4672       uiout->text ("Thread ");
4673       uiout->field_fmt ("thread-id", "%s", print_thread_id (thr));
4674
4675       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4676       if (name != NULL)
4677         {
4678           uiout->text (" \"");
4679           uiout->field_fmt ("name", "%s", name);
4680           uiout->text ("\"");
4681         }
4682
4683       uiout->text (" hit ");
4684     }
4685 }
4686
4687 /* Generic routine for printing messages indicating why we
4688    stopped.  The behavior of this function depends on the value
4689    'print_it' in the bpstat structure.  Under some circumstances we
4690    may decide not to print anything here and delegate the task to
4691    normal_stop().  */
4692
4693 static enum print_stop_action
4694 print_bp_stop_message (bpstat bs)
4695 {
4696   switch (bs->print_it)
4697     {
4698     case print_it_noop:
4699       /* Nothing should be printed for this bpstat entry.  */
4700       return PRINT_UNKNOWN;
4701       break;
4702
4703     case print_it_done:
4704       /* We still want to print the frame, but we already printed the
4705          relevant messages.  */
4706       return PRINT_SRC_AND_LOC;
4707       break;
4708
4709     case print_it_normal:
4710       {
4711         struct breakpoint *b = bs->breakpoint_at;
4712
4713         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4714            which has since been deleted.  */
4715         if (b == NULL)
4716           return PRINT_UNKNOWN;
4717
4718         /* Normal case.  Call the breakpoint's print_it method.  */
4719         return b->ops->print_it (bs);
4720       }
4721       break;
4722
4723     default:
4724       internal_error (__FILE__, __LINE__,
4725                       _("print_bp_stop_message: unrecognized enum value"));
4726       break;
4727     }
4728 }
4729
4730 /* A helper function that prints a shared library stopped event.  */
4731
4732 static void
4733 print_solib_event (int is_catchpoint)
4734 {
4735   int any_deleted
4736     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4737   int any_added
4738     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4739
4740   if (!is_catchpoint)
4741     {
4742       if (any_added || any_deleted)
4743         current_uiout->text (_("Stopped due to shared library event:\n"));
4744       else
4745         current_uiout->text (_("Stopped due to shared library event (no "
4746                                "libraries added or removed)\n"));
4747     }
4748
4749   if (current_uiout->is_mi_like_p ())
4750     current_uiout->field_string ("reason",
4751                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4752
4753   if (any_deleted)
4754     {
4755       char *name;
4756       int ix;
4757
4758       current_uiout->text (_("  Inferior unloaded "));
4759       ui_out_emit_list list_emitter (current_uiout, "removed");
4760       for (ix = 0;
4761            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4762                         ix, name);
4763            ++ix)
4764         {
4765           if (ix > 0)
4766             current_uiout->text ("    ");
4767           current_uiout->field_string ("library", name);
4768           current_uiout->text ("\n");
4769         }
4770     }
4771
4772   if (any_added)
4773     {
4774       struct so_list *iter;
4775       int ix;
4776
4777       current_uiout->text (_("  Inferior loaded "));
4778       ui_out_emit_list list_emitter (current_uiout, "added");
4779       for (ix = 0;
4780            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4781                         ix, iter);
4782            ++ix)
4783         {
4784           if (ix > 0)
4785             current_uiout->text ("    ");
4786           current_uiout->field_string ("library", iter->so_name);
4787           current_uiout->text ("\n");
4788         }
4789     }
4790 }
4791
4792 /* Print a message indicating what happened.  This is called from
4793    normal_stop().  The input to this routine is the head of the bpstat
4794    list - a list of the eventpoints that caused this stop.  KIND is
4795    the target_waitkind for the stopping event.  This
4796    routine calls the generic print routine for printing a message
4797    about reasons for stopping.  This will print (for example) the
4798    "Breakpoint n," part of the output.  The return value of this
4799    routine is one of:
4800
4801    PRINT_UNKNOWN: Means we printed nothing.
4802    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4803    code to print the location.  An example is 
4804    "Breakpoint 1, " which should be followed by
4805    the location.
4806    PRINT_SRC_ONLY: Means we printed something, but there is no need
4807    to also print the location part of the message.
4808    An example is the catch/throw messages, which
4809    don't require a location appended to the end.
4810    PRINT_NOTHING: We have done some printing and we don't need any 
4811    further info to be printed.  */
4812
4813 enum print_stop_action
4814 bpstat_print (bpstat bs, int kind)
4815 {
4816   enum print_stop_action val;
4817
4818   /* Maybe another breakpoint in the chain caused us to stop.
4819      (Currently all watchpoints go on the bpstat whether hit or not.
4820      That probably could (should) be changed, provided care is taken
4821      with respect to bpstat_explains_signal).  */
4822   for (; bs; bs = bs->next)
4823     {
4824       val = print_bp_stop_message (bs);
4825       if (val == PRINT_SRC_ONLY 
4826           || val == PRINT_SRC_AND_LOC 
4827           || val == PRINT_NOTHING)
4828         return val;
4829     }
4830
4831   /* If we had hit a shared library event breakpoint,
4832      print_bp_stop_message would print out this message.  If we hit an
4833      OS-level shared library event, do the same thing.  */
4834   if (kind == TARGET_WAITKIND_LOADED)
4835     {
4836       print_solib_event (0);
4837       return PRINT_NOTHING;
4838     }
4839
4840   /* We reached the end of the chain, or we got a null BS to start
4841      with and nothing was printed.  */
4842   return PRINT_UNKNOWN;
4843 }
4844
4845 /* Evaluate the expression EXP and return 1 if value is zero.
4846    This returns the inverse of the condition because it is called
4847    from catch_errors which returns 0 if an exception happened, and if an
4848    exception happens we want execution to stop.
4849    The argument is a "struct expression *" that has been cast to a
4850    "void *" to make it pass through catch_errors.  */
4851
4852 static int
4853 breakpoint_cond_eval (void *exp)
4854 {
4855   struct value *mark = value_mark ();
4856   int i = !value_true (evaluate_expression ((struct expression *) exp));
4857
4858   value_free_to_mark (mark);
4859   return i;
4860 }
4861
4862 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4863
4864 bpstats::bpstats (struct bp_location *bl, bpstat **bs_link_pointer)
4865   : next (NULL),
4866     bp_location_at (bl),
4867     breakpoint_at (bl->owner),
4868     commands (NULL),
4869     old_val (NULL),
4870     print (0),
4871     stop (0),
4872     print_it (print_it_normal)
4873 {
4874   incref_bp_location (bl);
4875   **bs_link_pointer = this;
4876   *bs_link_pointer = &next;
4877 }
4878
4879 bpstats::bpstats ()
4880   : next (NULL),
4881     bp_location_at (NULL),
4882     breakpoint_at (NULL),
4883     commands (NULL),
4884     old_val (NULL),
4885     print (0),
4886     stop (0),
4887     print_it (print_it_normal)
4888 {
4889 }
4890 \f
4891 /* The target has stopped with waitstatus WS.  Check if any hardware
4892    watchpoints have triggered, according to the target.  */
4893
4894 int
4895 watchpoints_triggered (struct target_waitstatus *ws)
4896 {
4897   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4898   CORE_ADDR addr;
4899   struct breakpoint *b;
4900
4901   if (!stopped_by_watchpoint)
4902     {
4903       /* We were not stopped by a watchpoint.  Mark all watchpoints
4904          as not triggered.  */
4905       ALL_BREAKPOINTS (b)
4906         if (is_hardware_watchpoint (b))
4907           {
4908             struct watchpoint *w = (struct watchpoint *) b;
4909
4910             w->watchpoint_triggered = watch_triggered_no;
4911           }
4912
4913       return 0;
4914     }
4915
4916   if (!target_stopped_data_address (&current_target, &addr))
4917     {
4918       /* We were stopped by a watchpoint, but we don't know where.
4919          Mark all watchpoints as unknown.  */
4920       ALL_BREAKPOINTS (b)
4921         if (is_hardware_watchpoint (b))
4922           {
4923             struct watchpoint *w = (struct watchpoint *) b;
4924
4925             w->watchpoint_triggered = watch_triggered_unknown;
4926           }
4927
4928       return 1;
4929     }
4930
4931   /* The target could report the data address.  Mark watchpoints
4932      affected by this data address as triggered, and all others as not
4933      triggered.  */
4934
4935   ALL_BREAKPOINTS (b)
4936     if (is_hardware_watchpoint (b))
4937       {
4938         struct watchpoint *w = (struct watchpoint *) b;
4939         struct bp_location *loc;
4940
4941         w->watchpoint_triggered = watch_triggered_no;
4942         for (loc = b->loc; loc; loc = loc->next)
4943           {
4944             if (is_masked_watchpoint (b))
4945               {
4946                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4947                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4948
4949                 if (newaddr == start)
4950                   {
4951                     w->watchpoint_triggered = watch_triggered_yes;
4952                     break;
4953                   }
4954               }
4955             /* Exact match not required.  Within range is sufficient.  */
4956             else if (target_watchpoint_addr_within_range (&current_target,
4957                                                          addr, loc->address,
4958                                                          loc->length))
4959               {
4960                 w->watchpoint_triggered = watch_triggered_yes;
4961                 break;
4962               }
4963           }
4964       }
4965
4966   return 1;
4967 }
4968
4969 /* Possible return values for watchpoint_check (this can't be an enum
4970    because of check_errors).  */
4971 /* The watchpoint has been deleted.  */
4972 #define WP_DELETED 1
4973 /* The value has changed.  */
4974 #define WP_VALUE_CHANGED 2
4975 /* The value has not changed.  */
4976 #define WP_VALUE_NOT_CHANGED 3
4977 /* Ignore this watchpoint, no matter if the value changed or not.  */
4978 #define WP_IGNORE 4
4979
4980 #define BP_TEMPFLAG 1
4981 #define BP_HARDWAREFLAG 2
4982
4983 /* Evaluate watchpoint condition expression and check if its value
4984    changed.
4985
4986    P should be a pointer to struct bpstat, but is defined as a void *
4987    in order for this function to be usable with catch_errors.  */
4988
4989 static int
4990 watchpoint_check (void *p)
4991 {
4992   bpstat bs = (bpstat) p;
4993   struct watchpoint *b;
4994   struct frame_info *fr;
4995   int within_current_scope;
4996
4997   /* BS is built from an existing struct breakpoint.  */
4998   gdb_assert (bs->breakpoint_at != NULL);
4999   b = (struct watchpoint *) bs->breakpoint_at;
5000
5001   /* If this is a local watchpoint, we only want to check if the
5002      watchpoint frame is in scope if the current thread is the thread
5003      that was used to create the watchpoint.  */
5004   if (!watchpoint_in_thread_scope (b))
5005     return WP_IGNORE;
5006
5007   if (b->exp_valid_block == NULL)
5008     within_current_scope = 1;
5009   else
5010     {
5011       struct frame_info *frame = get_current_frame ();
5012       struct gdbarch *frame_arch = get_frame_arch (frame);
5013       CORE_ADDR frame_pc = get_frame_pc (frame);
5014
5015       /* stack_frame_destroyed_p() returns a non-zero value if we're
5016          still in the function but the stack frame has already been
5017          invalidated.  Since we can't rely on the values of local
5018          variables after the stack has been destroyed, we are treating
5019          the watchpoint in that state as `not changed' without further
5020          checking.  Don't mark watchpoints as changed if the current
5021          frame is in an epilogue - even if they are in some other
5022          frame, our view of the stack is likely to be wrong and
5023          frame_find_by_id could error out.  */
5024       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
5025         return WP_IGNORE;
5026
5027       fr = frame_find_by_id (b->watchpoint_frame);
5028       within_current_scope = (fr != NULL);
5029
5030       /* If we've gotten confused in the unwinder, we might have
5031          returned a frame that can't describe this variable.  */
5032       if (within_current_scope)
5033         {
5034           struct symbol *function;
5035
5036           function = get_frame_function (fr);
5037           if (function == NULL
5038               || !contained_in (b->exp_valid_block,
5039                                 SYMBOL_BLOCK_VALUE (function)))
5040             within_current_scope = 0;
5041         }
5042
5043       if (within_current_scope)
5044         /* If we end up stopping, the current frame will get selected
5045            in normal_stop.  So this call to select_frame won't affect
5046            the user.  */
5047         select_frame (fr);
5048     }
5049
5050   if (within_current_scope)
5051     {
5052       /* We use value_{,free_to_}mark because it could be a *long*
5053          time before we return to the command level and call
5054          free_all_values.  We can't call free_all_values because we
5055          might be in the middle of evaluating a function call.  */
5056
5057       int pc = 0;
5058       struct value *mark;
5059       struct value *new_val;
5060
5061       if (is_masked_watchpoint (b))
5062         /* Since we don't know the exact trigger address (from
5063            stopped_data_address), just tell the user we've triggered
5064            a mask watchpoint.  */
5065         return WP_VALUE_CHANGED;
5066
5067       mark = value_mark ();
5068       fetch_subexp_value (b->exp.get (), &pc, &new_val, NULL, NULL, 0);
5069
5070       if (b->val_bitsize != 0)
5071         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5072
5073       /* We use value_equal_contents instead of value_equal because
5074          the latter coerces an array to a pointer, thus comparing just
5075          the address of the array instead of its contents.  This is
5076          not what we want.  */
5077       if ((b->val != NULL) != (new_val != NULL)
5078           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5079         {
5080           if (new_val != NULL)
5081             {
5082               release_value (new_val);
5083               value_free_to_mark (mark);
5084             }
5085           bs->old_val = b->val;
5086           b->val = new_val;
5087           b->val_valid = 1;
5088           return WP_VALUE_CHANGED;
5089         }
5090       else
5091         {
5092           /* Nothing changed.  */
5093           value_free_to_mark (mark);
5094           return WP_VALUE_NOT_CHANGED;
5095         }
5096     }
5097   else
5098     {
5099       /* This seems like the only logical thing to do because
5100          if we temporarily ignored the watchpoint, then when
5101          we reenter the block in which it is valid it contains
5102          garbage (in the case of a function, it may have two
5103          garbage values, one before and one after the prologue).
5104          So we can't even detect the first assignment to it and
5105          watch after that (since the garbage may or may not equal
5106          the first value assigned).  */
5107       /* We print all the stop information in
5108          breakpoint_ops->print_it, but in this case, by the time we
5109          call breakpoint_ops->print_it this bp will be deleted
5110          already.  So we have no choice but print the information
5111          here.  */
5112
5113       SWITCH_THRU_ALL_UIS ()
5114         {
5115           struct ui_out *uiout = current_uiout;
5116
5117           if (uiout->is_mi_like_p ())
5118             uiout->field_string
5119               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5120           uiout->text ("\nWatchpoint ");
5121           uiout->field_int ("wpnum", b->number);
5122           uiout->text (" deleted because the program has left the block in\n"
5123                        "which its expression is valid.\n");
5124         }
5125
5126       /* Make sure the watchpoint's commands aren't executed.  */
5127       b->commands = NULL;
5128       watchpoint_del_at_next_stop (b);
5129
5130       return WP_DELETED;
5131     }
5132 }
5133
5134 /* Return true if it looks like target has stopped due to hitting
5135    breakpoint location BL.  This function does not check if we should
5136    stop, only if BL explains the stop.  */
5137
5138 static int
5139 bpstat_check_location (const struct bp_location *bl,
5140                        struct address_space *aspace, CORE_ADDR bp_addr,
5141                        const struct target_waitstatus *ws)
5142 {
5143   struct breakpoint *b = bl->owner;
5144
5145   /* BL is from an existing breakpoint.  */
5146   gdb_assert (b != NULL);
5147
5148   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5149 }
5150
5151 /* Determine if the watched values have actually changed, and we
5152    should stop.  If not, set BS->stop to 0.  */
5153
5154 static void
5155 bpstat_check_watchpoint (bpstat bs)
5156 {
5157   const struct bp_location *bl;
5158   struct watchpoint *b;
5159
5160   /* BS is built for existing struct breakpoint.  */
5161   bl = bs->bp_location_at;
5162   gdb_assert (bl != NULL);
5163   b = (struct watchpoint *) bs->breakpoint_at;
5164   gdb_assert (b != NULL);
5165
5166     {
5167       int must_check_value = 0;
5168       
5169       if (b->type == bp_watchpoint)
5170         /* For a software watchpoint, we must always check the
5171            watched value.  */
5172         must_check_value = 1;
5173       else if (b->watchpoint_triggered == watch_triggered_yes)
5174         /* We have a hardware watchpoint (read, write, or access)
5175            and the target earlier reported an address watched by
5176            this watchpoint.  */
5177         must_check_value = 1;
5178       else if (b->watchpoint_triggered == watch_triggered_unknown
5179                && b->type == bp_hardware_watchpoint)
5180         /* We were stopped by a hardware watchpoint, but the target could
5181            not report the data address.  We must check the watchpoint's
5182            value.  Access and read watchpoints are out of luck; without
5183            a data address, we can't figure it out.  */
5184         must_check_value = 1;
5185
5186       if (must_check_value)
5187         {
5188           char *message
5189             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5190                           b->number);
5191           struct cleanup *cleanups = make_cleanup (xfree, message);
5192           int e = catch_errors (watchpoint_check, bs, message,
5193                                 RETURN_MASK_ALL);
5194           do_cleanups (cleanups);
5195           switch (e)
5196             {
5197             case WP_DELETED:
5198               /* We've already printed what needs to be printed.  */
5199               bs->print_it = print_it_done;
5200               /* Stop.  */
5201               break;
5202             case WP_IGNORE:
5203               bs->print_it = print_it_noop;
5204               bs->stop = 0;
5205               break;
5206             case WP_VALUE_CHANGED:
5207               if (b->type == bp_read_watchpoint)
5208                 {
5209                   /* There are two cases to consider here:
5210
5211                      1. We're watching the triggered memory for reads.
5212                      In that case, trust the target, and always report
5213                      the watchpoint hit to the user.  Even though
5214                      reads don't cause value changes, the value may
5215                      have changed since the last time it was read, and
5216                      since we're not trapping writes, we will not see
5217                      those, and as such we should ignore our notion of
5218                      old value.
5219
5220                      2. We're watching the triggered memory for both
5221                      reads and writes.  There are two ways this may
5222                      happen:
5223
5224                      2.1. This is a target that can't break on data
5225                      reads only, but can break on accesses (reads or
5226                      writes), such as e.g., x86.  We detect this case
5227                      at the time we try to insert read watchpoints.
5228
5229                      2.2. Otherwise, the target supports read
5230                      watchpoints, but, the user set an access or write
5231                      watchpoint watching the same memory as this read
5232                      watchpoint.
5233
5234                      If we're watching memory writes as well as reads,
5235                      ignore watchpoint hits when we find that the
5236                      value hasn't changed, as reads don't cause
5237                      changes.  This still gives false positives when
5238                      the program writes the same value to memory as
5239                      what there was already in memory (we will confuse
5240                      it for a read), but it's much better than
5241                      nothing.  */
5242
5243                   int other_write_watchpoint = 0;
5244
5245                   if (bl->watchpoint_type == hw_read)
5246                     {
5247                       struct breakpoint *other_b;
5248
5249                       ALL_BREAKPOINTS (other_b)
5250                         if (other_b->type == bp_hardware_watchpoint
5251                             || other_b->type == bp_access_watchpoint)
5252                           {
5253                             struct watchpoint *other_w =
5254                               (struct watchpoint *) other_b;
5255
5256                             if (other_w->watchpoint_triggered
5257                                 == watch_triggered_yes)
5258                               {
5259                                 other_write_watchpoint = 1;
5260                                 break;
5261                               }
5262                           }
5263                     }
5264
5265                   if (other_write_watchpoint
5266                       || bl->watchpoint_type == hw_access)
5267                     {
5268                       /* We're watching the same memory for writes,
5269                          and the value changed since the last time we
5270                          updated it, so this trap must be for a write.
5271                          Ignore it.  */
5272                       bs->print_it = print_it_noop;
5273                       bs->stop = 0;
5274                     }
5275                 }
5276               break;
5277             case WP_VALUE_NOT_CHANGED:
5278               if (b->type == bp_hardware_watchpoint
5279                   || b->type == bp_watchpoint)
5280                 {
5281                   /* Don't stop: write watchpoints shouldn't fire if
5282                      the value hasn't changed.  */
5283                   bs->print_it = print_it_noop;
5284                   bs->stop = 0;
5285                 }
5286               /* Stop.  */
5287               break;
5288             default:
5289               /* Can't happen.  */
5290             case 0:
5291               /* Error from catch_errors.  */
5292               {
5293                 SWITCH_THRU_ALL_UIS ()
5294                   {
5295                     printf_filtered (_("Watchpoint %d deleted.\n"),
5296                                      b->number);
5297                   }
5298                 watchpoint_del_at_next_stop (b);
5299                 /* We've already printed what needs to be printed.  */
5300                 bs->print_it = print_it_done;
5301               }
5302               break;
5303             }
5304         }
5305       else      /* must_check_value == 0 */
5306         {
5307           /* This is a case where some watchpoint(s) triggered, but
5308              not at the address of this watchpoint, or else no
5309              watchpoint triggered after all.  So don't print
5310              anything for this watchpoint.  */
5311           bs->print_it = print_it_noop;
5312           bs->stop = 0;
5313         }
5314     }
5315 }
5316
5317 /* For breakpoints that are currently marked as telling gdb to stop,
5318    check conditions (condition proper, frame, thread and ignore count)
5319    of breakpoint referred to by BS.  If we should not stop for this
5320    breakpoint, set BS->stop to 0.  */
5321
5322 static void
5323 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5324 {
5325   const struct bp_location *bl;
5326   struct breakpoint *b;
5327   int value_is_zero = 0;
5328   struct expression *cond;
5329
5330   gdb_assert (bs->stop);
5331
5332   /* BS is built for existing struct breakpoint.  */
5333   bl = bs->bp_location_at;
5334   gdb_assert (bl != NULL);
5335   b = bs->breakpoint_at;
5336   gdb_assert (b != NULL);
5337
5338   /* Even if the target evaluated the condition on its end and notified GDB, we
5339      need to do so again since GDB does not know if we stopped due to a
5340      breakpoint or a single step breakpoint.  */
5341
5342   if (frame_id_p (b->frame_id)
5343       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5344     {
5345       bs->stop = 0;
5346       return;
5347     }
5348
5349   /* If this is a thread/task-specific breakpoint, don't waste cpu
5350      evaluating the condition if this isn't the specified
5351      thread/task.  */
5352   if ((b->thread != -1 && b->thread != ptid_to_global_thread_id (ptid))
5353       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5354
5355     {
5356       bs->stop = 0;
5357       return;
5358     }
5359
5360   /* Evaluate extension language breakpoints that have a "stop" method
5361      implemented.  */
5362   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5363
5364   if (is_watchpoint (b))
5365     {
5366       struct watchpoint *w = (struct watchpoint *) b;
5367
5368       cond = w->cond_exp.get ();
5369     }
5370   else
5371     cond = bl->cond.get ();
5372
5373   if (cond && b->disposition != disp_del_at_next_stop)
5374     {
5375       int within_current_scope = 1;
5376       struct watchpoint * w;
5377
5378       /* We use value_mark and value_free_to_mark because it could
5379          be a long time before we return to the command level and
5380          call free_all_values.  We can't call free_all_values
5381          because we might be in the middle of evaluating a
5382          function call.  */
5383       struct value *mark = value_mark ();
5384
5385       if (is_watchpoint (b))
5386         w = (struct watchpoint *) b;
5387       else
5388         w = NULL;
5389
5390       /* Need to select the frame, with all that implies so that
5391          the conditions will have the right context.  Because we
5392          use the frame, we will not see an inlined function's
5393          variables when we arrive at a breakpoint at the start
5394          of the inlined function; the current frame will be the
5395          call site.  */
5396       if (w == NULL || w->cond_exp_valid_block == NULL)
5397         select_frame (get_current_frame ());
5398       else
5399         {
5400           struct frame_info *frame;
5401
5402           /* For local watchpoint expressions, which particular
5403              instance of a local is being watched matters, so we
5404              keep track of the frame to evaluate the expression
5405              in.  To evaluate the condition however, it doesn't
5406              really matter which instantiation of the function
5407              where the condition makes sense triggers the
5408              watchpoint.  This allows an expression like "watch
5409              global if q > 10" set in `func', catch writes to
5410              global on all threads that call `func', or catch
5411              writes on all recursive calls of `func' by a single
5412              thread.  We simply always evaluate the condition in
5413              the innermost frame that's executing where it makes
5414              sense to evaluate the condition.  It seems
5415              intuitive.  */
5416           frame = block_innermost_frame (w->cond_exp_valid_block);
5417           if (frame != NULL)
5418             select_frame (frame);
5419           else
5420             within_current_scope = 0;
5421         }
5422       if (within_current_scope)
5423         value_is_zero
5424           = catch_errors (breakpoint_cond_eval, cond,
5425                           "Error in testing breakpoint condition:\n",
5426                           RETURN_MASK_ALL);
5427       else
5428         {
5429           warning (_("Watchpoint condition cannot be tested "
5430                      "in the current scope"));
5431           /* If we failed to set the right context for this
5432              watchpoint, unconditionally report it.  */
5433           value_is_zero = 0;
5434         }
5435       /* FIXME-someday, should give breakpoint #.  */
5436       value_free_to_mark (mark);
5437     }
5438
5439   if (cond && value_is_zero)
5440     {
5441       bs->stop = 0;
5442     }
5443   else if (b->ignore_count > 0)
5444     {
5445       b->ignore_count--;
5446       bs->stop = 0;
5447       /* Increase the hit count even though we don't stop.  */
5448       ++(b->hit_count);
5449       observer_notify_breakpoint_modified (b);
5450     }   
5451 }
5452
5453 /* Returns true if we need to track moribund locations of LOC's type
5454    on the current target.  */
5455
5456 static int
5457 need_moribund_for_location_type (struct bp_location *loc)
5458 {
5459   return ((loc->loc_type == bp_loc_software_breakpoint
5460            && !target_supports_stopped_by_sw_breakpoint ())
5461           || (loc->loc_type == bp_loc_hardware_breakpoint
5462               && !target_supports_stopped_by_hw_breakpoint ()));
5463 }
5464
5465
5466 /* Get a bpstat associated with having just stopped at address
5467    BP_ADDR in thread PTID.
5468
5469    Determine whether we stopped at a breakpoint, etc, or whether we
5470    don't understand this stop.  Result is a chain of bpstat's such
5471    that:
5472
5473    if we don't understand the stop, the result is a null pointer.
5474
5475    if we understand why we stopped, the result is not null.
5476
5477    Each element of the chain refers to a particular breakpoint or
5478    watchpoint at which we have stopped.  (We may have stopped for
5479    several reasons concurrently.)
5480
5481    Each element of the chain has valid next, breakpoint_at,
5482    commands, FIXME??? fields.  */
5483
5484 bpstat
5485 bpstat_stop_status (struct address_space *aspace,
5486                     CORE_ADDR bp_addr, ptid_t ptid,
5487                     const struct target_waitstatus *ws)
5488 {
5489   struct breakpoint *b = NULL;
5490   struct bp_location *bl;
5491   struct bp_location *loc;
5492   /* First item of allocated bpstat's.  */
5493   bpstat bs_head = NULL, *bs_link = &bs_head;
5494   /* Pointer to the last thing in the chain currently.  */
5495   bpstat bs;
5496   int ix;
5497   int need_remove_insert;
5498   int removed_any;
5499
5500   /* First, build the bpstat chain with locations that explain a
5501      target stop, while being careful to not set the target running,
5502      as that may invalidate locations (in particular watchpoint
5503      locations are recreated).  Resuming will happen here with
5504      breakpoint conditions or watchpoint expressions that include
5505      inferior function calls.  */
5506
5507   ALL_BREAKPOINTS (b)
5508     {
5509       if (!breakpoint_enabled (b))
5510         continue;
5511
5512       for (bl = b->loc; bl != NULL; bl = bl->next)
5513         {
5514           /* For hardware watchpoints, we look only at the first
5515              location.  The watchpoint_check function will work on the
5516              entire expression, not the individual locations.  For
5517              read watchpoints, the watchpoints_triggered function has
5518              checked all locations already.  */
5519           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5520             break;
5521
5522           if (!bl->enabled || bl->shlib_disabled)
5523             continue;
5524
5525           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5526             continue;
5527
5528           /* Come here if it's a watchpoint, or if the break address
5529              matches.  */
5530
5531           bs = new bpstats (bl, &bs_link);      /* Alloc a bpstat to
5532                                                    explain stop.  */
5533
5534           /* Assume we stop.  Should we find a watchpoint that is not
5535              actually triggered, or if the condition of the breakpoint
5536              evaluates as false, we'll reset 'stop' to 0.  */
5537           bs->stop = 1;
5538           bs->print = 1;
5539
5540           /* If this is a scope breakpoint, mark the associated
5541              watchpoint as triggered so that we will handle the
5542              out-of-scope event.  We'll get to the watchpoint next
5543              iteration.  */
5544           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5545             {
5546               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5547
5548               w->watchpoint_triggered = watch_triggered_yes;
5549             }
5550         }
5551     }
5552
5553   /* Check if a moribund breakpoint explains the stop.  */
5554   if (!target_supports_stopped_by_sw_breakpoint ()
5555       || !target_supports_stopped_by_hw_breakpoint ())
5556     {
5557       for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5558         {
5559           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5560               && need_moribund_for_location_type (loc))
5561             {
5562               bs = new bpstats (loc, &bs_link);
5563               /* For hits of moribund locations, we should just proceed.  */
5564               bs->stop = 0;
5565               bs->print = 0;
5566               bs->print_it = print_it_noop;
5567             }
5568         }
5569     }
5570
5571   /* A bit of special processing for shlib breakpoints.  We need to
5572      process solib loading here, so that the lists of loaded and
5573      unloaded libraries are correct before we handle "catch load" and
5574      "catch unload".  */
5575   for (bs = bs_head; bs != NULL; bs = bs->next)
5576     {
5577       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5578         {
5579           handle_solib_event ();
5580           break;
5581         }
5582     }
5583
5584   /* Now go through the locations that caused the target to stop, and
5585      check whether we're interested in reporting this stop to higher
5586      layers, or whether we should resume the target transparently.  */
5587
5588   removed_any = 0;
5589
5590   for (bs = bs_head; bs != NULL; bs = bs->next)
5591     {
5592       if (!bs->stop)
5593         continue;
5594
5595       b = bs->breakpoint_at;
5596       b->ops->check_status (bs);
5597       if (bs->stop)
5598         {
5599           bpstat_check_breakpoint_conditions (bs, ptid);
5600
5601           if (bs->stop)
5602             {
5603               ++(b->hit_count);
5604               observer_notify_breakpoint_modified (b);
5605
5606               /* We will stop here.  */
5607               if (b->disposition == disp_disable)
5608                 {
5609                   --(b->enable_count);
5610                   if (b->enable_count <= 0)
5611                     b->enable_state = bp_disabled;
5612                   removed_any = 1;
5613                 }
5614               if (b->silent)
5615                 bs->print = 0;
5616               bs->commands = b->commands;
5617               if (command_line_is_silent (bs->commands
5618                                           ? bs->commands.get () : NULL))
5619                 bs->print = 0;
5620
5621               b->ops->after_condition_true (bs);
5622             }
5623
5624         }
5625
5626       /* Print nothing for this entry if we don't stop or don't
5627          print.  */
5628       if (!bs->stop || !bs->print)
5629         bs->print_it = print_it_noop;
5630     }
5631
5632   /* If we aren't stopping, the value of some hardware watchpoint may
5633      not have changed, but the intermediate memory locations we are
5634      watching may have.  Don't bother if we're stopping; this will get
5635      done later.  */
5636   need_remove_insert = 0;
5637   if (! bpstat_causes_stop (bs_head))
5638     for (bs = bs_head; bs != NULL; bs = bs->next)
5639       if (!bs->stop
5640           && bs->breakpoint_at
5641           && is_hardware_watchpoint (bs->breakpoint_at))
5642         {
5643           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5644
5645           update_watchpoint (w, 0 /* don't reparse.  */);
5646           need_remove_insert = 1;
5647         }
5648
5649   if (need_remove_insert)
5650     update_global_location_list (UGLL_MAY_INSERT);
5651   else if (removed_any)
5652     update_global_location_list (UGLL_DONT_INSERT);
5653
5654   return bs_head;
5655 }
5656
5657 static void
5658 handle_jit_event (void)
5659 {
5660   struct frame_info *frame;
5661   struct gdbarch *gdbarch;
5662
5663   if (debug_infrun)
5664     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5665
5666   /* Switch terminal for any messages produced by
5667      breakpoint_re_set.  */
5668   target_terminal::ours_for_output ();
5669
5670   frame = get_current_frame ();
5671   gdbarch = get_frame_arch (frame);
5672
5673   jit_event_handler (gdbarch);
5674
5675   target_terminal::inferior ();
5676 }
5677
5678 /* Prepare WHAT final decision for infrun.  */
5679
5680 /* Decide what infrun needs to do with this bpstat.  */
5681
5682 struct bpstat_what
5683 bpstat_what (bpstat bs_head)
5684 {
5685   struct bpstat_what retval;
5686   bpstat bs;
5687
5688   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5689   retval.call_dummy = STOP_NONE;
5690   retval.is_longjmp = 0;
5691
5692   for (bs = bs_head; bs != NULL; bs = bs->next)
5693     {
5694       /* Extract this BS's action.  After processing each BS, we check
5695          if its action overrides all we've seem so far.  */
5696       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5697       enum bptype bptype;
5698
5699       if (bs->breakpoint_at == NULL)
5700         {
5701           /* I suspect this can happen if it was a momentary
5702              breakpoint which has since been deleted.  */
5703           bptype = bp_none;
5704         }
5705       else
5706         bptype = bs->breakpoint_at->type;
5707
5708       switch (bptype)
5709         {
5710         case bp_none:
5711           break;
5712         case bp_breakpoint:
5713         case bp_hardware_breakpoint:
5714         case bp_single_step:
5715         case bp_until:
5716         case bp_finish:
5717         case bp_shlib_event:
5718           if (bs->stop)
5719             {
5720               if (bs->print)
5721                 this_action = BPSTAT_WHAT_STOP_NOISY;
5722               else
5723                 this_action = BPSTAT_WHAT_STOP_SILENT;
5724             }
5725           else
5726             this_action = BPSTAT_WHAT_SINGLE;
5727           break;
5728         case bp_watchpoint:
5729         case bp_hardware_watchpoint:
5730         case bp_read_watchpoint:
5731         case bp_access_watchpoint:
5732           if (bs->stop)
5733             {
5734               if (bs->print)
5735                 this_action = BPSTAT_WHAT_STOP_NOISY;
5736               else
5737                 this_action = BPSTAT_WHAT_STOP_SILENT;
5738             }
5739           else
5740             {
5741               /* There was a watchpoint, but we're not stopping.
5742                  This requires no further action.  */
5743             }
5744           break;
5745         case bp_longjmp:
5746         case bp_longjmp_call_dummy:
5747         case bp_exception:
5748           if (bs->stop)
5749             {
5750               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5751               retval.is_longjmp = bptype != bp_exception;
5752             }
5753           else
5754             this_action = BPSTAT_WHAT_SINGLE;
5755           break;
5756         case bp_longjmp_resume:
5757         case bp_exception_resume:
5758           if (bs->stop)
5759             {
5760               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5761               retval.is_longjmp = bptype == bp_longjmp_resume;
5762             }
5763           else
5764             this_action = BPSTAT_WHAT_SINGLE;
5765           break;
5766         case bp_step_resume:
5767           if (bs->stop)
5768             this_action = BPSTAT_WHAT_STEP_RESUME;
5769           else
5770             {
5771               /* It is for the wrong frame.  */
5772               this_action = BPSTAT_WHAT_SINGLE;
5773             }
5774           break;
5775         case bp_hp_step_resume:
5776           if (bs->stop)
5777             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5778           else
5779             {
5780               /* It is for the wrong frame.  */
5781               this_action = BPSTAT_WHAT_SINGLE;
5782             }
5783           break;
5784         case bp_watchpoint_scope:
5785         case bp_thread_event:
5786         case bp_overlay_event:
5787         case bp_longjmp_master:
5788         case bp_std_terminate_master:
5789         case bp_exception_master:
5790           this_action = BPSTAT_WHAT_SINGLE;
5791           break;
5792         case bp_catchpoint:
5793           if (bs->stop)
5794             {
5795               if (bs->print)
5796                 this_action = BPSTAT_WHAT_STOP_NOISY;
5797               else
5798                 this_action = BPSTAT_WHAT_STOP_SILENT;
5799             }
5800           else
5801             {
5802               /* There was a catchpoint, but we're not stopping.
5803                  This requires no further action.  */
5804             }
5805           break;
5806         case bp_jit_event:
5807           this_action = BPSTAT_WHAT_SINGLE;
5808           break;
5809         case bp_call_dummy:
5810           /* Make sure the action is stop (silent or noisy),
5811              so infrun.c pops the dummy frame.  */
5812           retval.call_dummy = STOP_STACK_DUMMY;
5813           this_action = BPSTAT_WHAT_STOP_SILENT;
5814           break;
5815         case bp_std_terminate:
5816           /* Make sure the action is stop (silent or noisy),
5817              so infrun.c pops the dummy frame.  */
5818           retval.call_dummy = STOP_STD_TERMINATE;
5819           this_action = BPSTAT_WHAT_STOP_SILENT;
5820           break;
5821         case bp_tracepoint:
5822         case bp_fast_tracepoint:
5823         case bp_static_tracepoint:
5824           /* Tracepoint hits should not be reported back to GDB, and
5825              if one got through somehow, it should have been filtered
5826              out already.  */
5827           internal_error (__FILE__, __LINE__,
5828                           _("bpstat_what: tracepoint encountered"));
5829           break;
5830         case bp_gnu_ifunc_resolver:
5831           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5832           this_action = BPSTAT_WHAT_SINGLE;
5833           break;
5834         case bp_gnu_ifunc_resolver_return:
5835           /* The breakpoint will be removed, execution will restart from the
5836              PC of the former breakpoint.  */
5837           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5838           break;
5839
5840         case bp_dprintf:
5841           if (bs->stop)
5842             this_action = BPSTAT_WHAT_STOP_SILENT;
5843           else
5844             this_action = BPSTAT_WHAT_SINGLE;
5845           break;
5846
5847         default:
5848           internal_error (__FILE__, __LINE__,
5849                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5850         }
5851
5852       retval.main_action = std::max (retval.main_action, this_action);
5853     }
5854
5855   return retval;
5856 }
5857
5858 void
5859 bpstat_run_callbacks (bpstat bs_head)
5860 {
5861   bpstat bs;
5862
5863   for (bs = bs_head; bs != NULL; bs = bs->next)
5864     {
5865       struct breakpoint *b = bs->breakpoint_at;
5866
5867       if (b == NULL)
5868         continue;
5869       switch (b->type)
5870         {
5871         case bp_jit_event:
5872           handle_jit_event ();
5873           break;
5874         case bp_gnu_ifunc_resolver:
5875           gnu_ifunc_resolver_stop (b);
5876           break;
5877         case bp_gnu_ifunc_resolver_return:
5878           gnu_ifunc_resolver_return_stop (b);
5879           break;
5880         }
5881     }
5882 }
5883
5884 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5885    without hardware support).  This isn't related to a specific bpstat,
5886    just to things like whether watchpoints are set.  */
5887
5888 int
5889 bpstat_should_step (void)
5890 {
5891   struct breakpoint *b;
5892
5893   ALL_BREAKPOINTS (b)
5894     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5895       return 1;
5896   return 0;
5897 }
5898
5899 int
5900 bpstat_causes_stop (bpstat bs)
5901 {
5902   for (; bs != NULL; bs = bs->next)
5903     if (bs->stop)
5904       return 1;
5905
5906   return 0;
5907 }
5908
5909 \f
5910
5911 /* Compute a string of spaces suitable to indent the next line
5912    so it starts at the position corresponding to the table column
5913    named COL_NAME in the currently active table of UIOUT.  */
5914
5915 static char *
5916 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5917 {
5918   static char wrap_indent[80];
5919   int i, total_width, width, align;
5920   const char *text;
5921
5922   total_width = 0;
5923   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
5924     {
5925       if (strcmp (text, col_name) == 0)
5926         {
5927           gdb_assert (total_width < sizeof wrap_indent);
5928           memset (wrap_indent, ' ', total_width);
5929           wrap_indent[total_width] = 0;
5930
5931           return wrap_indent;
5932         }
5933
5934       total_width += width + 1;
5935     }
5936
5937   return NULL;
5938 }
5939
5940 /* Determine if the locations of this breakpoint will have their conditions
5941    evaluated by the target, host or a mix of both.  Returns the following:
5942
5943     "host": Host evals condition.
5944     "host or target": Host or Target evals condition.
5945     "target": Target evals condition.
5946 */
5947
5948 static const char *
5949 bp_condition_evaluator (struct breakpoint *b)
5950 {
5951   struct bp_location *bl;
5952   char host_evals = 0;
5953   char target_evals = 0;
5954
5955   if (!b)
5956     return NULL;
5957
5958   if (!is_breakpoint (b))
5959     return NULL;
5960
5961   if (gdb_evaluates_breakpoint_condition_p ()
5962       || !target_supports_evaluation_of_breakpoint_conditions ())
5963     return condition_evaluation_host;
5964
5965   for (bl = b->loc; bl; bl = bl->next)
5966     {
5967       if (bl->cond_bytecode)
5968         target_evals++;
5969       else
5970         host_evals++;
5971     }
5972
5973   if (host_evals && target_evals)
5974     return condition_evaluation_both;
5975   else if (target_evals)
5976     return condition_evaluation_target;
5977   else
5978     return condition_evaluation_host;
5979 }
5980
5981 /* Determine the breakpoint location's condition evaluator.  This is
5982    similar to bp_condition_evaluator, but for locations.  */
5983
5984 static const char *
5985 bp_location_condition_evaluator (struct bp_location *bl)
5986 {
5987   if (bl && !is_breakpoint (bl->owner))
5988     return NULL;
5989
5990   if (gdb_evaluates_breakpoint_condition_p ()
5991       || !target_supports_evaluation_of_breakpoint_conditions ())
5992     return condition_evaluation_host;
5993
5994   if (bl && bl->cond_bytecode)
5995     return condition_evaluation_target;
5996   else
5997     return condition_evaluation_host;
5998 }
5999
6000 /* Print the LOC location out of the list of B->LOC locations.  */
6001
6002 static void
6003 print_breakpoint_location (struct breakpoint *b,
6004                            struct bp_location *loc)
6005 {
6006   struct ui_out *uiout = current_uiout;
6007
6008   scoped_restore_current_program_space restore_pspace;
6009
6010   if (loc != NULL && loc->shlib_disabled)
6011     loc = NULL;
6012
6013   if (loc != NULL)
6014     set_current_program_space (loc->pspace);
6015
6016   if (b->display_canonical)
6017     uiout->field_string ("what", event_location_to_string (b->location.get ()));
6018   else if (loc && loc->symtab)
6019     {
6020       struct symbol *sym 
6021         = find_pc_sect_function (loc->address, loc->section);
6022       if (sym)
6023         {
6024           uiout->text ("in ");
6025           uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
6026           uiout->text (" ");
6027           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
6028           uiout->text ("at ");
6029         }
6030       uiout->field_string ("file",
6031                            symtab_to_filename_for_display (loc->symtab));
6032       uiout->text (":");
6033
6034       if (uiout->is_mi_like_p ())
6035         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
6036       
6037       uiout->field_int ("line", loc->line_number);
6038     }
6039   else if (loc)
6040     {
6041       string_file stb;
6042
6043       print_address_symbolic (loc->gdbarch, loc->address, &stb,
6044                               demangle, "");
6045       uiout->field_stream ("at", stb);
6046     }
6047   else
6048     {
6049       uiout->field_string ("pending",
6050                            event_location_to_string (b->location.get ()));
6051       /* If extra_string is available, it could be holding a condition
6052          or dprintf arguments.  In either case, make sure it is printed,
6053          too, but only for non-MI streams.  */
6054       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
6055         {
6056           if (b->type == bp_dprintf)
6057             uiout->text (",");
6058           else
6059             uiout->text (" ");
6060           uiout->text (b->extra_string);
6061         }
6062     }
6063
6064   if (loc && is_breakpoint (b)
6065       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6066       && bp_condition_evaluator (b) == condition_evaluation_both)
6067     {
6068       uiout->text (" (");
6069       uiout->field_string ("evaluated-by",
6070                            bp_location_condition_evaluator (loc));
6071       uiout->text (")");
6072     }
6073 }
6074
6075 static const char *
6076 bptype_string (enum bptype type)
6077 {
6078   struct ep_type_description
6079     {
6080       enum bptype type;
6081       const char *description;
6082     };
6083   static struct ep_type_description bptypes[] =
6084   {
6085     {bp_none, "?deleted?"},
6086     {bp_breakpoint, "breakpoint"},
6087     {bp_hardware_breakpoint, "hw breakpoint"},
6088     {bp_single_step, "sw single-step"},
6089     {bp_until, "until"},
6090     {bp_finish, "finish"},
6091     {bp_watchpoint, "watchpoint"},
6092     {bp_hardware_watchpoint, "hw watchpoint"},
6093     {bp_read_watchpoint, "read watchpoint"},
6094     {bp_access_watchpoint, "acc watchpoint"},
6095     {bp_longjmp, "longjmp"},
6096     {bp_longjmp_resume, "longjmp resume"},
6097     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6098     {bp_exception, "exception"},
6099     {bp_exception_resume, "exception resume"},
6100     {bp_step_resume, "step resume"},
6101     {bp_hp_step_resume, "high-priority step resume"},
6102     {bp_watchpoint_scope, "watchpoint scope"},
6103     {bp_call_dummy, "call dummy"},
6104     {bp_std_terminate, "std::terminate"},
6105     {bp_shlib_event, "shlib events"},
6106     {bp_thread_event, "thread events"},
6107     {bp_overlay_event, "overlay events"},
6108     {bp_longjmp_master, "longjmp master"},
6109     {bp_std_terminate_master, "std::terminate master"},
6110     {bp_exception_master, "exception master"},
6111     {bp_catchpoint, "catchpoint"},
6112     {bp_tracepoint, "tracepoint"},
6113     {bp_fast_tracepoint, "fast tracepoint"},
6114     {bp_static_tracepoint, "static tracepoint"},
6115     {bp_dprintf, "dprintf"},
6116     {bp_jit_event, "jit events"},
6117     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6118     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6119   };
6120
6121   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6122       || ((int) type != bptypes[(int) type].type))
6123     internal_error (__FILE__, __LINE__,
6124                     _("bptypes table does not describe type #%d."),
6125                     (int) type);
6126
6127   return bptypes[(int) type].description;
6128 }
6129
6130 /* For MI, output a field named 'thread-groups' with a list as the value.
6131    For CLI, prefix the list with the string 'inf'. */
6132
6133 static void
6134 output_thread_groups (struct ui_out *uiout,
6135                       const char *field_name,
6136                       VEC(int) *inf_num,
6137                       int mi_only)
6138 {
6139   int is_mi = uiout->is_mi_like_p ();
6140   int inf;
6141   int i;
6142
6143   /* For backward compatibility, don't display inferiors in CLI unless
6144      there are several.  Always display them for MI. */
6145   if (!is_mi && mi_only)
6146     return;
6147
6148   ui_out_emit_list list_emitter (uiout, field_name);
6149
6150   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6151     {
6152       if (is_mi)
6153         {
6154           char mi_group[10];
6155
6156           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6157           uiout->field_string (NULL, mi_group);
6158         }
6159       else
6160         {
6161           if (i == 0)
6162             uiout->text (" inf ");
6163           else
6164             uiout->text (", ");
6165         
6166           uiout->text (plongest (inf));
6167         }
6168     }
6169 }
6170
6171 /* Print B to gdb_stdout.  */
6172
6173 static void
6174 print_one_breakpoint_location (struct breakpoint *b,
6175                                struct bp_location *loc,
6176                                int loc_number,
6177                                struct bp_location **last_loc,
6178                                int allflag)
6179 {
6180   struct command_line *l;
6181   static char bpenables[] = "nynny";
6182
6183   struct ui_out *uiout = current_uiout;
6184   int header_of_multiple = 0;
6185   int part_of_multiple = (loc != NULL);
6186   struct value_print_options opts;
6187
6188   get_user_print_options (&opts);
6189
6190   gdb_assert (!loc || loc_number != 0);
6191   /* See comment in print_one_breakpoint concerning treatment of
6192      breakpoints with single disabled location.  */
6193   if (loc == NULL 
6194       && (b->loc != NULL 
6195           && (b->loc->next != NULL || !b->loc->enabled)))
6196     header_of_multiple = 1;
6197   if (loc == NULL)
6198     loc = b->loc;
6199
6200   annotate_record ();
6201
6202   /* 1 */
6203   annotate_field (0);
6204   if (part_of_multiple)
6205     {
6206       char *formatted;
6207       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6208       uiout->field_string ("number", formatted);
6209       xfree (formatted);
6210     }
6211   else
6212     {
6213       uiout->field_int ("number", b->number);
6214     }
6215
6216   /* 2 */
6217   annotate_field (1);
6218   if (part_of_multiple)
6219     uiout->field_skip ("type");
6220   else
6221     uiout->field_string ("type", bptype_string (b->type));
6222
6223   /* 3 */
6224   annotate_field (2);
6225   if (part_of_multiple)
6226     uiout->field_skip ("disp");
6227   else
6228     uiout->field_string ("disp", bpdisp_text (b->disposition));
6229
6230
6231   /* 4 */
6232   annotate_field (3);
6233   if (part_of_multiple)
6234     uiout->field_string ("enabled", loc->enabled ? "y" : "n");
6235   else
6236     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6237   uiout->spaces (2);
6238
6239   
6240   /* 5 and 6 */
6241   if (b->ops != NULL && b->ops->print_one != NULL)
6242     {
6243       /* Although the print_one can possibly print all locations,
6244          calling it here is not likely to get any nice result.  So,
6245          make sure there's just one location.  */
6246       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6247       b->ops->print_one (b, last_loc);
6248     }
6249   else
6250     switch (b->type)
6251       {
6252       case bp_none:
6253         internal_error (__FILE__, __LINE__,
6254                         _("print_one_breakpoint: bp_none encountered\n"));
6255         break;
6256
6257       case bp_watchpoint:
6258       case bp_hardware_watchpoint:
6259       case bp_read_watchpoint:
6260       case bp_access_watchpoint:
6261         {
6262           struct watchpoint *w = (struct watchpoint *) b;
6263
6264           /* Field 4, the address, is omitted (which makes the columns
6265              not line up too nicely with the headers, but the effect
6266              is relatively readable).  */
6267           if (opts.addressprint)
6268             uiout->field_skip ("addr");
6269           annotate_field (5);
6270           uiout->field_string ("what", w->exp_string);
6271         }
6272         break;
6273
6274       case bp_breakpoint:
6275       case bp_hardware_breakpoint:
6276       case bp_single_step:
6277       case bp_until:
6278       case bp_finish:
6279       case bp_longjmp:
6280       case bp_longjmp_resume:
6281       case bp_longjmp_call_dummy:
6282       case bp_exception:
6283       case bp_exception_resume:
6284       case bp_step_resume:
6285       case bp_hp_step_resume:
6286       case bp_watchpoint_scope:
6287       case bp_call_dummy:
6288       case bp_std_terminate:
6289       case bp_shlib_event:
6290       case bp_thread_event:
6291       case bp_overlay_event:
6292       case bp_longjmp_master:
6293       case bp_std_terminate_master:
6294       case bp_exception_master:
6295       case bp_tracepoint:
6296       case bp_fast_tracepoint:
6297       case bp_static_tracepoint:
6298       case bp_dprintf:
6299       case bp_jit_event:
6300       case bp_gnu_ifunc_resolver:
6301       case bp_gnu_ifunc_resolver_return:
6302         if (opts.addressprint)
6303           {
6304             annotate_field (4);
6305             if (header_of_multiple)
6306               uiout->field_string ("addr", "<MULTIPLE>");
6307             else if (b->loc == NULL || loc->shlib_disabled)
6308               uiout->field_string ("addr", "<PENDING>");
6309             else
6310               uiout->field_core_addr ("addr",
6311                                       loc->gdbarch, loc->address);
6312           }
6313         annotate_field (5);
6314         if (!header_of_multiple)
6315           print_breakpoint_location (b, loc);
6316         if (b->loc)
6317           *last_loc = b->loc;
6318         break;
6319       }
6320
6321
6322   if (loc != NULL && !header_of_multiple)
6323     {
6324       struct inferior *inf;
6325       VEC(int) *inf_num = NULL;
6326       int mi_only = 1;
6327
6328       ALL_INFERIORS (inf)
6329         {
6330           if (inf->pspace == loc->pspace)
6331             VEC_safe_push (int, inf_num, inf->num);
6332         }
6333
6334         /* For backward compatibility, don't display inferiors in CLI unless
6335            there are several.  Always display for MI. */
6336         if (allflag
6337             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6338                 && (number_of_program_spaces () > 1
6339                     || number_of_inferiors () > 1)
6340                 /* LOC is for existing B, it cannot be in
6341                    moribund_locations and thus having NULL OWNER.  */
6342                 && loc->owner->type != bp_catchpoint))
6343         mi_only = 0;
6344       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6345       VEC_free (int, inf_num);
6346     }
6347
6348   if (!part_of_multiple)
6349     {
6350       if (b->thread != -1)
6351         {
6352           /* FIXME: This seems to be redundant and lost here; see the
6353              "stop only in" line a little further down.  */
6354           uiout->text (" thread ");
6355           uiout->field_int ("thread", b->thread);
6356         }
6357       else if (b->task != 0)
6358         {
6359           uiout->text (" task ");
6360           uiout->field_int ("task", b->task);
6361         }
6362     }
6363
6364   uiout->text ("\n");
6365
6366   if (!part_of_multiple)
6367     b->ops->print_one_detail (b, uiout);
6368
6369   if (part_of_multiple && frame_id_p (b->frame_id))
6370     {
6371       annotate_field (6);
6372       uiout->text ("\tstop only in stack frame at ");
6373       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6374          the frame ID.  */
6375       uiout->field_core_addr ("frame",
6376                               b->gdbarch, b->frame_id.stack_addr);
6377       uiout->text ("\n");
6378     }
6379   
6380   if (!part_of_multiple && b->cond_string)
6381     {
6382       annotate_field (7);
6383       if (is_tracepoint (b))
6384         uiout->text ("\ttrace only if ");
6385       else
6386         uiout->text ("\tstop only if ");
6387       uiout->field_string ("cond", b->cond_string);
6388
6389       /* Print whether the target is doing the breakpoint's condition
6390          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6391       if (is_breakpoint (b)
6392           && breakpoint_condition_evaluation_mode ()
6393           == condition_evaluation_target)
6394         {
6395           uiout->text (" (");
6396           uiout->field_string ("evaluated-by",
6397                                bp_condition_evaluator (b));
6398           uiout->text (" evals)");
6399         }
6400       uiout->text ("\n");
6401     }
6402
6403   if (!part_of_multiple && b->thread != -1)
6404     {
6405       /* FIXME should make an annotation for this.  */
6406       uiout->text ("\tstop only in thread ");
6407       if (uiout->is_mi_like_p ())
6408         uiout->field_int ("thread", b->thread);
6409       else
6410         {
6411           struct thread_info *thr = find_thread_global_id (b->thread);
6412
6413           uiout->field_string ("thread", print_thread_id (thr));
6414         }
6415       uiout->text ("\n");
6416     }
6417   
6418   if (!part_of_multiple)
6419     {
6420       if (b->hit_count)
6421         {
6422           /* FIXME should make an annotation for this.  */
6423           if (is_catchpoint (b))
6424             uiout->text ("\tcatchpoint");
6425           else if (is_tracepoint (b))
6426             uiout->text ("\ttracepoint");
6427           else
6428             uiout->text ("\tbreakpoint");
6429           uiout->text (" already hit ");
6430           uiout->field_int ("times", b->hit_count);
6431           if (b->hit_count == 1)
6432             uiout->text (" time\n");
6433           else
6434             uiout->text (" times\n");
6435         }
6436       else
6437         {
6438           /* Output the count also if it is zero, but only if this is mi.  */
6439           if (uiout->is_mi_like_p ())
6440             uiout->field_int ("times", b->hit_count);
6441         }
6442     }
6443
6444   if (!part_of_multiple && b->ignore_count)
6445     {
6446       annotate_field (8);
6447       uiout->text ("\tignore next ");
6448       uiout->field_int ("ignore", b->ignore_count);
6449       uiout->text (" hits\n");
6450     }
6451
6452   /* Note that an enable count of 1 corresponds to "enable once"
6453      behavior, which is reported by the combination of enablement and
6454      disposition, so we don't need to mention it here.  */
6455   if (!part_of_multiple && b->enable_count > 1)
6456     {
6457       annotate_field (8);
6458       uiout->text ("\tdisable after ");
6459       /* Tweak the wording to clarify that ignore and enable counts
6460          are distinct, and have additive effect.  */
6461       if (b->ignore_count)
6462         uiout->text ("additional ");
6463       else
6464         uiout->text ("next ");
6465       uiout->field_int ("enable", b->enable_count);
6466       uiout->text (" hits\n");
6467     }
6468
6469   if (!part_of_multiple && is_tracepoint (b))
6470     {
6471       struct tracepoint *tp = (struct tracepoint *) b;
6472
6473       if (tp->traceframe_usage)
6474         {
6475           uiout->text ("\ttrace buffer usage ");
6476           uiout->field_int ("traceframe-usage", tp->traceframe_usage);
6477           uiout->text (" bytes\n");
6478         }
6479     }
6480
6481   l = b->commands ? b->commands.get () : NULL;
6482   if (!part_of_multiple && l)
6483     {
6484       annotate_field (9);
6485       ui_out_emit_tuple tuple_emitter (uiout, "script");
6486       print_command_lines (uiout, l, 4);
6487     }
6488
6489   if (is_tracepoint (b))
6490     {
6491       struct tracepoint *t = (struct tracepoint *) b;
6492
6493       if (!part_of_multiple && t->pass_count)
6494         {
6495           annotate_field (10);
6496           uiout->text ("\tpass count ");
6497           uiout->field_int ("pass", t->pass_count);
6498           uiout->text (" \n");
6499         }
6500
6501       /* Don't display it when tracepoint or tracepoint location is
6502          pending.   */
6503       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6504         {
6505           annotate_field (11);
6506
6507           if (uiout->is_mi_like_p ())
6508             uiout->field_string ("installed",
6509                                  loc->inserted ? "y" : "n");
6510           else
6511             {
6512               if (loc->inserted)
6513                 uiout->text ("\t");
6514               else
6515                 uiout->text ("\tnot ");
6516               uiout->text ("installed on target\n");
6517             }
6518         }
6519     }
6520
6521   if (uiout->is_mi_like_p () && !part_of_multiple)
6522     {
6523       if (is_watchpoint (b))
6524         {
6525           struct watchpoint *w = (struct watchpoint *) b;
6526
6527           uiout->field_string ("original-location", w->exp_string);
6528         }
6529       else if (b->location != NULL
6530                && event_location_to_string (b->location.get ()) != NULL)
6531         uiout->field_string ("original-location",
6532                              event_location_to_string (b->location.get ()));
6533     }
6534 }
6535
6536 static void
6537 print_one_breakpoint (struct breakpoint *b,
6538                       struct bp_location **last_loc, 
6539                       int allflag)
6540 {
6541   struct ui_out *uiout = current_uiout;
6542
6543   {
6544     ui_out_emit_tuple tuple_emitter (uiout, "bkpt");
6545
6546     print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6547   }
6548
6549   /* If this breakpoint has custom print function,
6550      it's already printed.  Otherwise, print individual
6551      locations, if any.  */
6552   if (b->ops == NULL || b->ops->print_one == NULL)
6553     {
6554       /* If breakpoint has a single location that is disabled, we
6555          print it as if it had several locations, since otherwise it's
6556          hard to represent "breakpoint enabled, location disabled"
6557          situation.
6558
6559          Note that while hardware watchpoints have several locations
6560          internally, that's not a property exposed to user.  */
6561       if (b->loc 
6562           && !is_hardware_watchpoint (b)
6563           && (b->loc->next || !b->loc->enabled))
6564         {
6565           struct bp_location *loc;
6566           int n = 1;
6567
6568           for (loc = b->loc; loc; loc = loc->next, ++n)
6569             {
6570               ui_out_emit_tuple tuple_emitter (uiout, NULL);
6571               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6572             }
6573         }
6574     }
6575 }
6576
6577 static int
6578 breakpoint_address_bits (struct breakpoint *b)
6579 {
6580   int print_address_bits = 0;
6581   struct bp_location *loc;
6582
6583   /* Software watchpoints that aren't watching memory don't have an
6584      address to print.  */
6585   if (is_no_memory_software_watchpoint (b))
6586     return 0;
6587
6588   for (loc = b->loc; loc; loc = loc->next)
6589     {
6590       int addr_bit;
6591
6592       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6593       if (addr_bit > print_address_bits)
6594         print_address_bits = addr_bit;
6595     }
6596
6597   return print_address_bits;
6598 }
6599
6600 struct captured_breakpoint_query_args
6601   {
6602     int bnum;
6603   };
6604
6605 static int
6606 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6607 {
6608   struct captured_breakpoint_query_args *args
6609     = (struct captured_breakpoint_query_args *) data;
6610   struct breakpoint *b;
6611   struct bp_location *dummy_loc = NULL;
6612
6613   ALL_BREAKPOINTS (b)
6614     {
6615       if (args->bnum == b->number)
6616         {
6617           print_one_breakpoint (b, &dummy_loc, 0);
6618           return GDB_RC_OK;
6619         }
6620     }
6621   return GDB_RC_NONE;
6622 }
6623
6624 enum gdb_rc
6625 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6626                       char **error_message)
6627 {
6628   struct captured_breakpoint_query_args args;
6629
6630   args.bnum = bnum;
6631   /* For the moment we don't trust print_one_breakpoint() to not throw
6632      an error.  */
6633   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6634                                  error_message, RETURN_MASK_ALL) < 0)
6635     return GDB_RC_FAIL;
6636   else
6637     return GDB_RC_OK;
6638 }
6639
6640 /* Return true if this breakpoint was set by the user, false if it is
6641    internal or momentary.  */
6642
6643 int
6644 user_breakpoint_p (struct breakpoint *b)
6645 {
6646   return b->number > 0;
6647 }
6648
6649 /* See breakpoint.h.  */
6650
6651 int
6652 pending_breakpoint_p (struct breakpoint *b)
6653 {
6654   return b->loc == NULL;
6655 }
6656
6657 /* Print information on user settable breakpoint (watchpoint, etc)
6658    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6659    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6660    FILTER is non-NULL, call it on each breakpoint and only include the
6661    ones for which it returns non-zero.  Return the total number of
6662    breakpoints listed.  */
6663
6664 static int
6665 breakpoint_1 (const char *args, int allflag, 
6666               int (*filter) (const struct breakpoint *))
6667 {
6668   struct breakpoint *b;
6669   struct bp_location *last_loc = NULL;
6670   int nr_printable_breakpoints;
6671   struct value_print_options opts;
6672   int print_address_bits = 0;
6673   int print_type_col_width = 14;
6674   struct ui_out *uiout = current_uiout;
6675
6676   get_user_print_options (&opts);
6677
6678   /* Compute the number of rows in the table, as well as the size
6679      required for address fields.  */
6680   nr_printable_breakpoints = 0;
6681   ALL_BREAKPOINTS (b)
6682     {
6683       /* If we have a filter, only list the breakpoints it accepts.  */
6684       if (filter && !filter (b))
6685         continue;
6686
6687       /* If we have an "args" string, it is a list of breakpoints to 
6688          accept.  Skip the others.  */
6689       if (args != NULL && *args != '\0')
6690         {
6691           if (allflag && parse_and_eval_long (args) != b->number)
6692             continue;
6693           if (!allflag && !number_is_in_list (args, b->number))
6694             continue;
6695         }
6696
6697       if (allflag || user_breakpoint_p (b))
6698         {
6699           int addr_bit, type_len;
6700
6701           addr_bit = breakpoint_address_bits (b);
6702           if (addr_bit > print_address_bits)
6703             print_address_bits = addr_bit;
6704
6705           type_len = strlen (bptype_string (b->type));
6706           if (type_len > print_type_col_width)
6707             print_type_col_width = type_len;
6708
6709           nr_printable_breakpoints++;
6710         }
6711     }
6712
6713   {
6714     ui_out_emit_table table_emitter (uiout,
6715                                      opts.addressprint ? 6 : 5,
6716                                      nr_printable_breakpoints,
6717                                      "BreakpointTable");
6718
6719     if (nr_printable_breakpoints > 0)
6720       annotate_breakpoints_headers ();
6721     if (nr_printable_breakpoints > 0)
6722       annotate_field (0);
6723     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6724     if (nr_printable_breakpoints > 0)
6725       annotate_field (1);
6726     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6727     if (nr_printable_breakpoints > 0)
6728       annotate_field (2);
6729     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6730     if (nr_printable_breakpoints > 0)
6731       annotate_field (3);
6732     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6733     if (opts.addressprint)
6734       {
6735         if (nr_printable_breakpoints > 0)
6736           annotate_field (4);
6737         if (print_address_bits <= 32)
6738           uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6739         else
6740           uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6741       }
6742     if (nr_printable_breakpoints > 0)
6743       annotate_field (5);
6744     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6745     uiout->table_body ();
6746     if (nr_printable_breakpoints > 0)
6747       annotate_breakpoints_table ();
6748
6749     ALL_BREAKPOINTS (b)
6750       {
6751         QUIT;
6752         /* If we have a filter, only list the breakpoints it accepts.  */
6753         if (filter && !filter (b))
6754           continue;
6755
6756         /* If we have an "args" string, it is a list of breakpoints to 
6757            accept.  Skip the others.  */
6758
6759         if (args != NULL && *args != '\0')
6760           {
6761             if (allflag)        /* maintenance info breakpoint */
6762               {
6763                 if (parse_and_eval_long (args) != b->number)
6764                   continue;
6765               }
6766             else                /* all others */
6767               {
6768                 if (!number_is_in_list (args, b->number))
6769                   continue;
6770               }
6771           }
6772         /* We only print out user settable breakpoints unless the
6773            allflag is set.  */
6774         if (allflag || user_breakpoint_p (b))
6775           print_one_breakpoint (b, &last_loc, allflag);
6776       }
6777   }
6778
6779   if (nr_printable_breakpoints == 0)
6780     {
6781       /* If there's a filter, let the caller decide how to report
6782          empty list.  */
6783       if (!filter)
6784         {
6785           if (args == NULL || *args == '\0')
6786             uiout->message ("No breakpoints or watchpoints.\n");
6787           else
6788             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6789                             args);
6790         }
6791     }
6792   else
6793     {
6794       if (last_loc && !server_command)
6795         set_next_address (last_loc->gdbarch, last_loc->address);
6796     }
6797
6798   /* FIXME?  Should this be moved up so that it is only called when
6799      there have been breakpoints? */
6800   annotate_breakpoints_table_end ();
6801
6802   return nr_printable_breakpoints;
6803 }
6804
6805 /* Display the value of default-collect in a way that is generally
6806    compatible with the breakpoint list.  */
6807
6808 static void
6809 default_collect_info (void)
6810 {
6811   struct ui_out *uiout = current_uiout;
6812
6813   /* If it has no value (which is frequently the case), say nothing; a
6814      message like "No default-collect." gets in user's face when it's
6815      not wanted.  */
6816   if (!*default_collect)
6817     return;
6818
6819   /* The following phrase lines up nicely with per-tracepoint collect
6820      actions.  */
6821   uiout->text ("default collect ");
6822   uiout->field_string ("default-collect", default_collect);
6823   uiout->text (" \n");
6824 }
6825   
6826 static void
6827 info_breakpoints_command (char *args, int from_tty)
6828 {
6829   breakpoint_1 (args, 0, NULL);
6830
6831   default_collect_info ();
6832 }
6833
6834 static void
6835 info_watchpoints_command (char *args, int from_tty)
6836 {
6837   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6838   struct ui_out *uiout = current_uiout;
6839
6840   if (num_printed == 0)
6841     {
6842       if (args == NULL || *args == '\0')
6843         uiout->message ("No watchpoints.\n");
6844       else
6845         uiout->message ("No watchpoint matching '%s'.\n", args);
6846     }
6847 }
6848
6849 static void
6850 maintenance_info_breakpoints (const char *args, int from_tty)
6851 {
6852   breakpoint_1 (args, 1, NULL);
6853
6854   default_collect_info ();
6855 }
6856
6857 static int
6858 breakpoint_has_pc (struct breakpoint *b,
6859                    struct program_space *pspace,
6860                    CORE_ADDR pc, struct obj_section *section)
6861 {
6862   struct bp_location *bl = b->loc;
6863
6864   for (; bl; bl = bl->next)
6865     {
6866       if (bl->pspace == pspace
6867           && bl->address == pc
6868           && (!overlay_debugging || bl->section == section))
6869         return 1;         
6870     }
6871   return 0;
6872 }
6873
6874 /* Print a message describing any user-breakpoints set at PC.  This
6875    concerns with logical breakpoints, so we match program spaces, not
6876    address spaces.  */
6877
6878 static void
6879 describe_other_breakpoints (struct gdbarch *gdbarch,
6880                             struct program_space *pspace, CORE_ADDR pc,
6881                             struct obj_section *section, int thread)
6882 {
6883   int others = 0;
6884   struct breakpoint *b;
6885
6886   ALL_BREAKPOINTS (b)
6887     others += (user_breakpoint_p (b)
6888                && breakpoint_has_pc (b, pspace, pc, section));
6889   if (others > 0)
6890     {
6891       if (others == 1)
6892         printf_filtered (_("Note: breakpoint "));
6893       else /* if (others == ???) */
6894         printf_filtered (_("Note: breakpoints "));
6895       ALL_BREAKPOINTS (b)
6896         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6897           {
6898             others--;
6899             printf_filtered ("%d", b->number);
6900             if (b->thread == -1 && thread != -1)
6901               printf_filtered (" (all threads)");
6902             else if (b->thread != -1)
6903               printf_filtered (" (thread %d)", b->thread);
6904             printf_filtered ("%s%s ",
6905                              ((b->enable_state == bp_disabled
6906                                || b->enable_state == bp_call_disabled)
6907                               ? " (disabled)"
6908                               : ""),
6909                              (others > 1) ? "," 
6910                              : ((others == 1) ? " and" : ""));
6911           }
6912       printf_filtered (_("also set at pc "));
6913       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6914       printf_filtered (".\n");
6915     }
6916 }
6917 \f
6918
6919 /* Return true iff it is meaningful to use the address member of
6920    BPT locations.  For some breakpoint types, the locations' address members
6921    are irrelevant and it makes no sense to attempt to compare them to other
6922    addresses (or use them for any other purpose either).
6923
6924    More specifically, each of the following breakpoint types will
6925    always have a zero valued location address and we don't want to mark
6926    breakpoints of any of these types to be a duplicate of an actual
6927    breakpoint location at address zero:
6928
6929       bp_watchpoint
6930       bp_catchpoint
6931
6932 */
6933
6934 static int
6935 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6936 {
6937   enum bptype type = bpt->type;
6938
6939   return (type != bp_watchpoint && type != bp_catchpoint);
6940 }
6941
6942 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6943    true if LOC1 and LOC2 represent the same watchpoint location.  */
6944
6945 static int
6946 watchpoint_locations_match (struct bp_location *loc1, 
6947                             struct bp_location *loc2)
6948 {
6949   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6950   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6951
6952   /* Both of them must exist.  */
6953   gdb_assert (w1 != NULL);
6954   gdb_assert (w2 != NULL);
6955
6956   /* If the target can evaluate the condition expression in hardware,
6957      then we we need to insert both watchpoints even if they are at
6958      the same place.  Otherwise the watchpoint will only trigger when
6959      the condition of whichever watchpoint was inserted evaluates to
6960      true, not giving a chance for GDB to check the condition of the
6961      other watchpoint.  */
6962   if ((w1->cond_exp
6963        && target_can_accel_watchpoint_condition (loc1->address, 
6964                                                  loc1->length,
6965                                                  loc1->watchpoint_type,
6966                                                  w1->cond_exp.get ()))
6967       || (w2->cond_exp
6968           && target_can_accel_watchpoint_condition (loc2->address, 
6969                                                     loc2->length,
6970                                                     loc2->watchpoint_type,
6971                                                     w2->cond_exp.get ())))
6972     return 0;
6973
6974   /* Note that this checks the owner's type, not the location's.  In
6975      case the target does not support read watchpoints, but does
6976      support access watchpoints, we'll have bp_read_watchpoint
6977      watchpoints with hw_access locations.  Those should be considered
6978      duplicates of hw_read locations.  The hw_read locations will
6979      become hw_access locations later.  */
6980   return (loc1->owner->type == loc2->owner->type
6981           && loc1->pspace->aspace == loc2->pspace->aspace
6982           && loc1->address == loc2->address
6983           && loc1->length == loc2->length);
6984 }
6985
6986 /* See breakpoint.h.  */
6987
6988 int
6989 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6990                           struct address_space *aspace2, CORE_ADDR addr2)
6991 {
6992   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6993            || aspace1 == aspace2)
6994           && addr1 == addr2);
6995 }
6996
6997 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6998    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6999    matches ASPACE2.  On targets that have global breakpoints, the address
7000    space doesn't really matter.  */
7001
7002 static int
7003 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
7004                                 int len1, struct address_space *aspace2,
7005                                 CORE_ADDR addr2)
7006 {
7007   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7008            || aspace1 == aspace2)
7009           && addr2 >= addr1 && addr2 < addr1 + len1);
7010 }
7011
7012 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
7013    a ranged breakpoint.  In most targets, a match happens only if ASPACE
7014    matches the breakpoint's address space.  On targets that have global
7015    breakpoints, the address space doesn't really matter.  */
7016
7017 static int
7018 breakpoint_location_address_match (struct bp_location *bl,
7019                                    struct address_space *aspace,
7020                                    CORE_ADDR addr)
7021 {
7022   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
7023                                     aspace, addr)
7024           || (bl->length
7025               && breakpoint_address_match_range (bl->pspace->aspace,
7026                                                  bl->address, bl->length,
7027                                                  aspace, addr)));
7028 }
7029
7030 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
7031    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
7032    match happens only if ASPACE matches the breakpoint's address
7033    space.  On targets that have global breakpoints, the address space
7034    doesn't really matter.  */
7035
7036 static int
7037 breakpoint_location_address_range_overlap (struct bp_location *bl,
7038                                            struct address_space *aspace,
7039                                            CORE_ADDR addr, int len)
7040 {
7041   if (gdbarch_has_global_breakpoints (target_gdbarch ())
7042       || bl->pspace->aspace == aspace)
7043     {
7044       int bl_len = bl->length != 0 ? bl->length : 1;
7045
7046       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
7047         return 1;
7048     }
7049   return 0;
7050 }
7051
7052 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7053    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7054    true, otherwise returns false.  */
7055
7056 static int
7057 tracepoint_locations_match (struct bp_location *loc1,
7058                             struct bp_location *loc2)
7059 {
7060   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7061     /* Since tracepoint locations are never duplicated with others', tracepoint
7062        locations at the same address of different tracepoints are regarded as
7063        different locations.  */
7064     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7065   else
7066     return 0;
7067 }
7068
7069 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7070    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
7071    represent the same location.  */
7072
7073 static int
7074 breakpoint_locations_match (struct bp_location *loc1, 
7075                             struct bp_location *loc2)
7076 {
7077   int hw_point1, hw_point2;
7078
7079   /* Both of them must not be in moribund_locations.  */
7080   gdb_assert (loc1->owner != NULL);
7081   gdb_assert (loc2->owner != NULL);
7082
7083   hw_point1 = is_hardware_watchpoint (loc1->owner);
7084   hw_point2 = is_hardware_watchpoint (loc2->owner);
7085
7086   if (hw_point1 != hw_point2)
7087     return 0;
7088   else if (hw_point1)
7089     return watchpoint_locations_match (loc1, loc2);
7090   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7091     return tracepoint_locations_match (loc1, loc2);
7092   else
7093     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7094     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7095                                      loc2->pspace->aspace, loc2->address)
7096             && loc1->length == loc2->length);
7097 }
7098
7099 static void
7100 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7101                                int bnum, int have_bnum)
7102 {
7103   /* The longest string possibly returned by hex_string_custom
7104      is 50 chars.  These must be at least that big for safety.  */
7105   char astr1[64];
7106   char astr2[64];
7107
7108   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7109   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7110   if (have_bnum)
7111     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7112              bnum, astr1, astr2);
7113   else
7114     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7115 }
7116
7117 /* Adjust a breakpoint's address to account for architectural
7118    constraints on breakpoint placement.  Return the adjusted address.
7119    Note: Very few targets require this kind of adjustment.  For most
7120    targets, this function is simply the identity function.  */
7121
7122 static CORE_ADDR
7123 adjust_breakpoint_address (struct gdbarch *gdbarch,
7124                            CORE_ADDR bpaddr, enum bptype bptype)
7125 {
7126   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7127     {
7128       /* Very few targets need any kind of breakpoint adjustment.  */
7129       return bpaddr;
7130     }
7131   else if (bptype == bp_watchpoint
7132            || bptype == bp_hardware_watchpoint
7133            || bptype == bp_read_watchpoint
7134            || bptype == bp_access_watchpoint
7135            || bptype == bp_catchpoint)
7136     {
7137       /* Watchpoints and the various bp_catch_* eventpoints should not
7138          have their addresses modified.  */
7139       return bpaddr;
7140     }
7141   else if (bptype == bp_single_step)
7142     {
7143       /* Single-step breakpoints should not have their addresses
7144          modified.  If there's any architectural constrain that
7145          applies to this address, then it should have already been
7146          taken into account when the breakpoint was created in the
7147          first place.  If we didn't do this, stepping through e.g.,
7148          Thumb-2 IT blocks would break.  */
7149       return bpaddr;
7150     }
7151   else
7152     {
7153       CORE_ADDR adjusted_bpaddr;
7154
7155       /* Some targets have architectural constraints on the placement
7156          of breakpoint instructions.  Obtain the adjusted address.  */
7157       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7158
7159       /* An adjusted breakpoint address can significantly alter
7160          a user's expectations.  Print a warning if an adjustment
7161          is required.  */
7162       if (adjusted_bpaddr != bpaddr)
7163         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7164
7165       return adjusted_bpaddr;
7166     }
7167 }
7168
7169 bp_location::bp_location (const bp_location_ops *ops, breakpoint *owner)
7170 {
7171   bp_location *loc = this;
7172
7173   gdb_assert (ops != NULL);
7174
7175   loc->ops = ops;
7176   loc->owner = owner;
7177   loc->cond_bytecode = NULL;
7178   loc->shlib_disabled = 0;
7179   loc->enabled = 1;
7180
7181   switch (owner->type)
7182     {
7183     case bp_breakpoint:
7184     case bp_single_step:
7185     case bp_until:
7186     case bp_finish:
7187     case bp_longjmp:
7188     case bp_longjmp_resume:
7189     case bp_longjmp_call_dummy:
7190     case bp_exception:
7191     case bp_exception_resume:
7192     case bp_step_resume:
7193     case bp_hp_step_resume:
7194     case bp_watchpoint_scope:
7195     case bp_call_dummy:
7196     case bp_std_terminate:
7197     case bp_shlib_event:
7198     case bp_thread_event:
7199     case bp_overlay_event:
7200     case bp_jit_event:
7201     case bp_longjmp_master:
7202     case bp_std_terminate_master:
7203     case bp_exception_master:
7204     case bp_gnu_ifunc_resolver:
7205     case bp_gnu_ifunc_resolver_return:
7206     case bp_dprintf:
7207       loc->loc_type = bp_loc_software_breakpoint;
7208       mark_breakpoint_location_modified (loc);
7209       break;
7210     case bp_hardware_breakpoint:
7211       loc->loc_type = bp_loc_hardware_breakpoint;
7212       mark_breakpoint_location_modified (loc);
7213       break;
7214     case bp_hardware_watchpoint:
7215     case bp_read_watchpoint:
7216     case bp_access_watchpoint:
7217       loc->loc_type = bp_loc_hardware_watchpoint;
7218       break;
7219     case bp_watchpoint:
7220     case bp_catchpoint:
7221     case bp_tracepoint:
7222     case bp_fast_tracepoint:
7223     case bp_static_tracepoint:
7224       loc->loc_type = bp_loc_other;
7225       break;
7226     default:
7227       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7228     }
7229
7230   loc->refc = 1;
7231 }
7232
7233 /* Allocate a struct bp_location.  */
7234
7235 static struct bp_location *
7236 allocate_bp_location (struct breakpoint *bpt)
7237 {
7238   return bpt->ops->allocate_location (bpt);
7239 }
7240
7241 static void
7242 free_bp_location (struct bp_location *loc)
7243 {
7244   loc->ops->dtor (loc);
7245   delete loc;
7246 }
7247
7248 /* Increment reference count.  */
7249
7250 static void
7251 incref_bp_location (struct bp_location *bl)
7252 {
7253   ++bl->refc;
7254 }
7255
7256 /* Decrement reference count.  If the reference count reaches 0,
7257    destroy the bp_location.  Sets *BLP to NULL.  */
7258
7259 static void
7260 decref_bp_location (struct bp_location **blp)
7261 {
7262   gdb_assert ((*blp)->refc > 0);
7263
7264   if (--(*blp)->refc == 0)
7265     free_bp_location (*blp);
7266   *blp = NULL;
7267 }
7268
7269 /* Add breakpoint B at the end of the global breakpoint chain.  */
7270
7271 static breakpoint *
7272 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7273 {
7274   struct breakpoint *b1;
7275   struct breakpoint *result = b.get ();
7276
7277   /* Add this breakpoint to the end of the chain so that a list of
7278      breakpoints will come out in order of increasing numbers.  */
7279
7280   b1 = breakpoint_chain;
7281   if (b1 == 0)
7282     breakpoint_chain = b.release ();
7283   else
7284     {
7285       while (b1->next)
7286         b1 = b1->next;
7287       b1->next = b.release ();
7288     }
7289
7290   return result;
7291 }
7292
7293 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7294
7295 static void
7296 init_raw_breakpoint_without_location (struct breakpoint *b,
7297                                       struct gdbarch *gdbarch,
7298                                       enum bptype bptype,
7299                                       const struct breakpoint_ops *ops)
7300 {
7301   gdb_assert (ops != NULL);
7302
7303   b->ops = ops;
7304   b->type = bptype;
7305   b->gdbarch = gdbarch;
7306   b->language = current_language->la_language;
7307   b->input_radix = input_radix;
7308   b->related_breakpoint = b;
7309 }
7310
7311 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7312    that has type BPTYPE and has no locations as yet.  */
7313
7314 static struct breakpoint *
7315 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7316                                      enum bptype bptype,
7317                                      const struct breakpoint_ops *ops)
7318 {
7319   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7320
7321   init_raw_breakpoint_without_location (b.get (), gdbarch, bptype, ops);
7322   return add_to_breakpoint_chain (std::move (b));
7323 }
7324
7325 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7326    resolutions should be made as the user specified the location explicitly
7327    enough.  */
7328
7329 static void
7330 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7331 {
7332   gdb_assert (loc->owner != NULL);
7333
7334   if (loc->owner->type == bp_breakpoint
7335       || loc->owner->type == bp_hardware_breakpoint
7336       || is_tracepoint (loc->owner))
7337     {
7338       int is_gnu_ifunc;
7339       const char *function_name;
7340       CORE_ADDR func_addr;
7341
7342       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7343                                           &func_addr, NULL, &is_gnu_ifunc);
7344
7345       if (is_gnu_ifunc && !explicit_loc)
7346         {
7347           struct breakpoint *b = loc->owner;
7348
7349           gdb_assert (loc->pspace == current_program_space);
7350           if (gnu_ifunc_resolve_name (function_name,
7351                                       &loc->requested_address))
7352             {
7353               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7354               loc->address = adjust_breakpoint_address (loc->gdbarch,
7355                                                         loc->requested_address,
7356                                                         b->type);
7357             }
7358           else if (b->type == bp_breakpoint && b->loc == loc
7359                    && loc->next == NULL && b->related_breakpoint == b)
7360             {
7361               /* Create only the whole new breakpoint of this type but do not
7362                  mess more complicated breakpoints with multiple locations.  */
7363               b->type = bp_gnu_ifunc_resolver;
7364               /* Remember the resolver's address for use by the return
7365                  breakpoint.  */
7366               loc->related_address = func_addr;
7367             }
7368         }
7369
7370       if (function_name)
7371         loc->function_name = xstrdup (function_name);
7372     }
7373 }
7374
7375 /* Attempt to determine architecture of location identified by SAL.  */
7376 struct gdbarch *
7377 get_sal_arch (struct symtab_and_line sal)
7378 {
7379   if (sal.section)
7380     return get_objfile_arch (sal.section->objfile);
7381   if (sal.symtab)
7382     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7383
7384   return NULL;
7385 }
7386
7387 /* Low level routine for partially initializing a breakpoint of type
7388    BPTYPE.  The newly created breakpoint's address, section, source
7389    file name, and line number are provided by SAL.
7390
7391    It is expected that the caller will complete the initialization of
7392    the newly created breakpoint struct as well as output any status
7393    information regarding the creation of a new breakpoint.  */
7394
7395 static void
7396 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7397                      struct symtab_and_line sal, enum bptype bptype,
7398                      const struct breakpoint_ops *ops)
7399 {
7400   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7401
7402   add_location_to_breakpoint (b, &sal);
7403
7404   if (bptype != bp_catchpoint)
7405     gdb_assert (sal.pspace != NULL);
7406
7407   /* Store the program space that was used to set the breakpoint,
7408      except for ordinary breakpoints, which are independent of the
7409      program space.  */
7410   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7411     b->pspace = sal.pspace;
7412 }
7413
7414 /* set_raw_breakpoint is a low level routine for allocating and
7415    partially initializing a breakpoint of type BPTYPE.  The newly
7416    created breakpoint's address, section, source file name, and line
7417    number are provided by SAL.  The newly created and partially
7418    initialized breakpoint is added to the breakpoint chain and
7419    is also returned as the value of this function.
7420
7421    It is expected that the caller will complete the initialization of
7422    the newly created breakpoint struct as well as output any status
7423    information regarding the creation of a new breakpoint.  In
7424    particular, set_raw_breakpoint does NOT set the breakpoint
7425    number!  Care should be taken to not allow an error to occur
7426    prior to completing the initialization of the breakpoint.  If this
7427    should happen, a bogus breakpoint will be left on the chain.  */
7428
7429 struct breakpoint *
7430 set_raw_breakpoint (struct gdbarch *gdbarch,
7431                     struct symtab_and_line sal, enum bptype bptype,
7432                     const struct breakpoint_ops *ops)
7433 {
7434   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7435
7436   init_raw_breakpoint (b.get (), gdbarch, sal, bptype, ops);
7437   return add_to_breakpoint_chain (std::move (b));
7438 }
7439
7440 /* Call this routine when stepping and nexting to enable a breakpoint
7441    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7442    initiated the operation.  */
7443
7444 void
7445 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7446 {
7447   struct breakpoint *b, *b_tmp;
7448   int thread = tp->global_num;
7449
7450   /* To avoid having to rescan all objfile symbols at every step,
7451      we maintain a list of continually-inserted but always disabled
7452      longjmp "master" breakpoints.  Here, we simply create momentary
7453      clones of those and enable them for the requested thread.  */
7454   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7455     if (b->pspace == current_program_space
7456         && (b->type == bp_longjmp_master
7457             || b->type == bp_exception_master))
7458       {
7459         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7460         struct breakpoint *clone;
7461
7462         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7463            after their removal.  */
7464         clone = momentary_breakpoint_from_master (b, type,
7465                                                   &momentary_breakpoint_ops, 1);
7466         clone->thread = thread;
7467       }
7468
7469   tp->initiating_frame = frame;
7470 }
7471
7472 /* Delete all longjmp breakpoints from THREAD.  */
7473 void
7474 delete_longjmp_breakpoint (int thread)
7475 {
7476   struct breakpoint *b, *b_tmp;
7477
7478   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7479     if (b->type == bp_longjmp || b->type == bp_exception)
7480       {
7481         if (b->thread == thread)
7482           delete_breakpoint (b);
7483       }
7484 }
7485
7486 void
7487 delete_longjmp_breakpoint_at_next_stop (int thread)
7488 {
7489   struct breakpoint *b, *b_tmp;
7490
7491   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7492     if (b->type == bp_longjmp || b->type == bp_exception)
7493       {
7494         if (b->thread == thread)
7495           b->disposition = disp_del_at_next_stop;
7496       }
7497 }
7498
7499 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7500    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7501    pointer to any of them.  Return NULL if this system cannot place longjmp
7502    breakpoints.  */
7503
7504 struct breakpoint *
7505 set_longjmp_breakpoint_for_call_dummy (void)
7506 {
7507   struct breakpoint *b, *retval = NULL;
7508
7509   ALL_BREAKPOINTS (b)
7510     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7511       {
7512         struct breakpoint *new_b;
7513
7514         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7515                                                   &momentary_breakpoint_ops,
7516                                                   1);
7517         new_b->thread = ptid_to_global_thread_id (inferior_ptid);
7518
7519         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7520
7521         gdb_assert (new_b->related_breakpoint == new_b);
7522         if (retval == NULL)
7523           retval = new_b;
7524         new_b->related_breakpoint = retval;
7525         while (retval->related_breakpoint != new_b->related_breakpoint)
7526           retval = retval->related_breakpoint;
7527         retval->related_breakpoint = new_b;
7528       }
7529
7530   return retval;
7531 }
7532
7533 /* Verify all existing dummy frames and their associated breakpoints for
7534    TP.  Remove those which can no longer be found in the current frame
7535    stack.
7536
7537    You should call this function only at places where it is safe to currently
7538    unwind the whole stack.  Failed stack unwind would discard live dummy
7539    frames.  */
7540
7541 void
7542 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7543 {
7544   struct breakpoint *b, *b_tmp;
7545
7546   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7547     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7548       {
7549         struct breakpoint *dummy_b = b->related_breakpoint;
7550
7551         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7552           dummy_b = dummy_b->related_breakpoint;
7553         if (dummy_b->type != bp_call_dummy
7554             || frame_find_by_id (dummy_b->frame_id) != NULL)
7555           continue;
7556         
7557         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7558
7559         while (b->related_breakpoint != b)
7560           {
7561             if (b_tmp == b->related_breakpoint)
7562               b_tmp = b->related_breakpoint->next;
7563             delete_breakpoint (b->related_breakpoint);
7564           }
7565         delete_breakpoint (b);
7566       }
7567 }
7568
7569 void
7570 enable_overlay_breakpoints (void)
7571 {
7572   struct breakpoint *b;
7573
7574   ALL_BREAKPOINTS (b)
7575     if (b->type == bp_overlay_event)
7576     {
7577       b->enable_state = bp_enabled;
7578       update_global_location_list (UGLL_MAY_INSERT);
7579       overlay_events_enabled = 1;
7580     }
7581 }
7582
7583 void
7584 disable_overlay_breakpoints (void)
7585 {
7586   struct breakpoint *b;
7587
7588   ALL_BREAKPOINTS (b)
7589     if (b->type == bp_overlay_event)
7590     {
7591       b->enable_state = bp_disabled;
7592       update_global_location_list (UGLL_DONT_INSERT);
7593       overlay_events_enabled = 0;
7594     }
7595 }
7596
7597 /* Set an active std::terminate breakpoint for each std::terminate
7598    master breakpoint.  */
7599 void
7600 set_std_terminate_breakpoint (void)
7601 {
7602   struct breakpoint *b, *b_tmp;
7603
7604   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7605     if (b->pspace == current_program_space
7606         && b->type == bp_std_terminate_master)
7607       {
7608         momentary_breakpoint_from_master (b, bp_std_terminate,
7609                                           &momentary_breakpoint_ops, 1);
7610       }
7611 }
7612
7613 /* Delete all the std::terminate breakpoints.  */
7614 void
7615 delete_std_terminate_breakpoint (void)
7616 {
7617   struct breakpoint *b, *b_tmp;
7618
7619   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7620     if (b->type == bp_std_terminate)
7621       delete_breakpoint (b);
7622 }
7623
7624 struct breakpoint *
7625 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7626 {
7627   struct breakpoint *b;
7628
7629   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7630                                   &internal_breakpoint_ops);
7631
7632   b->enable_state = bp_enabled;
7633   /* location has to be used or breakpoint_re_set will delete me.  */
7634   b->location = new_address_location (b->loc->address, NULL, 0);
7635
7636   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7637
7638   return b;
7639 }
7640
7641 struct lang_and_radix
7642   {
7643     enum language lang;
7644     int radix;
7645   };
7646
7647 /* Create a breakpoint for JIT code registration and unregistration.  */
7648
7649 struct breakpoint *
7650 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7651 {
7652   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7653                                      &internal_breakpoint_ops);
7654 }
7655
7656 /* Remove JIT code registration and unregistration breakpoint(s).  */
7657
7658 void
7659 remove_jit_event_breakpoints (void)
7660 {
7661   struct breakpoint *b, *b_tmp;
7662
7663   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7664     if (b->type == bp_jit_event
7665         && b->loc->pspace == current_program_space)
7666       delete_breakpoint (b);
7667 }
7668
7669 void
7670 remove_solib_event_breakpoints (void)
7671 {
7672   struct breakpoint *b, *b_tmp;
7673
7674   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7675     if (b->type == bp_shlib_event
7676         && b->loc->pspace == current_program_space)
7677       delete_breakpoint (b);
7678 }
7679
7680 /* See breakpoint.h.  */
7681
7682 void
7683 remove_solib_event_breakpoints_at_next_stop (void)
7684 {
7685   struct breakpoint *b, *b_tmp;
7686
7687   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7688     if (b->type == bp_shlib_event
7689         && b->loc->pspace == current_program_space)
7690       b->disposition = disp_del_at_next_stop;
7691 }
7692
7693 /* Helper for create_solib_event_breakpoint /
7694    create_and_insert_solib_event_breakpoint.  Allows specifying which
7695    INSERT_MODE to pass through to update_global_location_list.  */
7696
7697 static struct breakpoint *
7698 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7699                                  enum ugll_insert_mode insert_mode)
7700 {
7701   struct breakpoint *b;
7702
7703   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7704                                   &internal_breakpoint_ops);
7705   update_global_location_list_nothrow (insert_mode);
7706   return b;
7707 }
7708
7709 struct breakpoint *
7710 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7711 {
7712   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7713 }
7714
7715 /* See breakpoint.h.  */
7716
7717 struct breakpoint *
7718 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7719 {
7720   struct breakpoint *b;
7721
7722   /* Explicitly tell update_global_location_list to insert
7723      locations.  */
7724   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7725   if (!b->loc->inserted)
7726     {
7727       delete_breakpoint (b);
7728       return NULL;
7729     }
7730   return b;
7731 }
7732
7733 /* Disable any breakpoints that are on code in shared libraries.  Only
7734    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7735
7736 void
7737 disable_breakpoints_in_shlibs (void)
7738 {
7739   struct bp_location *loc, **locp_tmp;
7740
7741   ALL_BP_LOCATIONS (loc, locp_tmp)
7742   {
7743     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7744     struct breakpoint *b = loc->owner;
7745
7746     /* We apply the check to all breakpoints, including disabled for
7747        those with loc->duplicate set.  This is so that when breakpoint
7748        becomes enabled, or the duplicate is removed, gdb will try to
7749        insert all breakpoints.  If we don't set shlib_disabled here,
7750        we'll try to insert those breakpoints and fail.  */
7751     if (((b->type == bp_breakpoint)
7752          || (b->type == bp_jit_event)
7753          || (b->type == bp_hardware_breakpoint)
7754          || (is_tracepoint (b)))
7755         && loc->pspace == current_program_space
7756         && !loc->shlib_disabled
7757         && solib_name_from_address (loc->pspace, loc->address)
7758         )
7759       {
7760         loc->shlib_disabled = 1;
7761       }
7762   }
7763 }
7764
7765 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7766    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7767    disabled ones can just stay disabled.  */
7768
7769 static void
7770 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7771 {
7772   struct bp_location *loc, **locp_tmp;
7773   int disabled_shlib_breaks = 0;
7774
7775   ALL_BP_LOCATIONS (loc, locp_tmp)
7776   {
7777     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7778     struct breakpoint *b = loc->owner;
7779
7780     if (solib->pspace == loc->pspace
7781         && !loc->shlib_disabled
7782         && (((b->type == bp_breakpoint
7783               || b->type == bp_jit_event
7784               || b->type == bp_hardware_breakpoint)
7785              && (loc->loc_type == bp_loc_hardware_breakpoint
7786                  || loc->loc_type == bp_loc_software_breakpoint))
7787             || is_tracepoint (b))
7788         && solib_contains_address_p (solib, loc->address))
7789       {
7790         loc->shlib_disabled = 1;
7791         /* At this point, we cannot rely on remove_breakpoint
7792            succeeding so we must mark the breakpoint as not inserted
7793            to prevent future errors occurring in remove_breakpoints.  */
7794         loc->inserted = 0;
7795
7796         /* This may cause duplicate notifications for the same breakpoint.  */
7797         observer_notify_breakpoint_modified (b);
7798
7799         if (!disabled_shlib_breaks)
7800           {
7801             target_terminal::ours_for_output ();
7802             warning (_("Temporarily disabling breakpoints "
7803                        "for unloaded shared library \"%s\""),
7804                      solib->so_name);
7805           }
7806         disabled_shlib_breaks = 1;
7807       }
7808   }
7809 }
7810
7811 /* Disable any breakpoints and tracepoints in OBJFILE upon
7812    notification of free_objfile.  Only apply to enabled breakpoints,
7813    disabled ones can just stay disabled.  */
7814
7815 static void
7816 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7817 {
7818   struct breakpoint *b;
7819
7820   if (objfile == NULL)
7821     return;
7822
7823   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7824      managed by the user with add-symbol-file/remove-symbol-file.
7825      Similarly to how breakpoints in shared libraries are handled in
7826      response to "nosharedlibrary", mark breakpoints in such modules
7827      shlib_disabled so they end up uninserted on the next global
7828      location list update.  Shared libraries not loaded by the user
7829      aren't handled here -- they're already handled in
7830      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7831      solib_unloaded observer.  We skip objfiles that are not
7832      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7833      main objfile).  */
7834   if ((objfile->flags & OBJF_SHARED) == 0
7835       || (objfile->flags & OBJF_USERLOADED) == 0)
7836     return;
7837
7838   ALL_BREAKPOINTS (b)
7839     {
7840       struct bp_location *loc;
7841       int bp_modified = 0;
7842
7843       if (!is_breakpoint (b) && !is_tracepoint (b))
7844         continue;
7845
7846       for (loc = b->loc; loc != NULL; loc = loc->next)
7847         {
7848           CORE_ADDR loc_addr = loc->address;
7849
7850           if (loc->loc_type != bp_loc_hardware_breakpoint
7851               && loc->loc_type != bp_loc_software_breakpoint)
7852             continue;
7853
7854           if (loc->shlib_disabled != 0)
7855             continue;
7856
7857           if (objfile->pspace != loc->pspace)
7858             continue;
7859
7860           if (loc->loc_type != bp_loc_hardware_breakpoint
7861               && loc->loc_type != bp_loc_software_breakpoint)
7862             continue;
7863
7864           if (is_addr_in_objfile (loc_addr, objfile))
7865             {
7866               loc->shlib_disabled = 1;
7867               /* At this point, we don't know whether the object was
7868                  unmapped from the inferior or not, so leave the
7869                  inserted flag alone.  We'll handle failure to
7870                  uninsert quietly, in case the object was indeed
7871                  unmapped.  */
7872
7873               mark_breakpoint_location_modified (loc);
7874
7875               bp_modified = 1;
7876             }
7877         }
7878
7879       if (bp_modified)
7880         observer_notify_breakpoint_modified (b);
7881     }
7882 }
7883
7884 /* FORK & VFORK catchpoints.  */
7885
7886 /* An instance of this type is used to represent a fork or vfork
7887    catchpoint.  A breakpoint is really of this type iff its ops pointer points
7888    to CATCH_FORK_BREAKPOINT_OPS.  */
7889
7890 struct fork_catchpoint : public breakpoint
7891 {
7892   /* Process id of a child process whose forking triggered this
7893      catchpoint.  This field is only valid immediately after this
7894      catchpoint has triggered.  */
7895   ptid_t forked_inferior_pid;
7896 };
7897
7898 /* Implement the "insert" breakpoint_ops method for fork
7899    catchpoints.  */
7900
7901 static int
7902 insert_catch_fork (struct bp_location *bl)
7903 {
7904   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7905 }
7906
7907 /* Implement the "remove" breakpoint_ops method for fork
7908    catchpoints.  */
7909
7910 static int
7911 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
7912 {
7913   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7914 }
7915
7916 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7917    catchpoints.  */
7918
7919 static int
7920 breakpoint_hit_catch_fork (const struct bp_location *bl,
7921                            struct address_space *aspace, CORE_ADDR bp_addr,
7922                            const struct target_waitstatus *ws)
7923 {
7924   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7925
7926   if (ws->kind != TARGET_WAITKIND_FORKED)
7927     return 0;
7928
7929   c->forked_inferior_pid = ws->value.related_pid;
7930   return 1;
7931 }
7932
7933 /* Implement the "print_it" breakpoint_ops method for fork
7934    catchpoints.  */
7935
7936 static enum print_stop_action
7937 print_it_catch_fork (bpstat bs)
7938 {
7939   struct ui_out *uiout = current_uiout;
7940   struct breakpoint *b = bs->breakpoint_at;
7941   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7942
7943   annotate_catchpoint (b->number);
7944   maybe_print_thread_hit_breakpoint (uiout);
7945   if (b->disposition == disp_del)
7946     uiout->text ("Temporary catchpoint ");
7947   else
7948     uiout->text ("Catchpoint ");
7949   if (uiout->is_mi_like_p ())
7950     {
7951       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
7952       uiout->field_string ("disp", bpdisp_text (b->disposition));
7953     }
7954   uiout->field_int ("bkptno", b->number);
7955   uiout->text (" (forked process ");
7956   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
7957   uiout->text ("), ");
7958   return PRINT_SRC_AND_LOC;
7959 }
7960
7961 /* Implement the "print_one" breakpoint_ops method for fork
7962    catchpoints.  */
7963
7964 static void
7965 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7966 {
7967   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7968   struct value_print_options opts;
7969   struct ui_out *uiout = current_uiout;
7970
7971   get_user_print_options (&opts);
7972
7973   /* Field 4, the address, is omitted (which makes the columns not
7974      line up too nicely with the headers, but the effect is relatively
7975      readable).  */
7976   if (opts.addressprint)
7977     uiout->field_skip ("addr");
7978   annotate_field (5);
7979   uiout->text ("fork");
7980   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7981     {
7982       uiout->text (", process ");
7983       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
7984       uiout->spaces (1);
7985     }
7986
7987   if (uiout->is_mi_like_p ())
7988     uiout->field_string ("catch-type", "fork");
7989 }
7990
7991 /* Implement the "print_mention" breakpoint_ops method for fork
7992    catchpoints.  */
7993
7994 static void
7995 print_mention_catch_fork (struct breakpoint *b)
7996 {
7997   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7998 }
7999
8000 /* Implement the "print_recreate" breakpoint_ops method for fork
8001    catchpoints.  */
8002
8003 static void
8004 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
8005 {
8006   fprintf_unfiltered (fp, "catch fork");
8007   print_recreate_thread (b, fp);
8008 }
8009
8010 /* The breakpoint_ops structure to be used in fork catchpoints.  */
8011
8012 static struct breakpoint_ops catch_fork_breakpoint_ops;
8013
8014 /* Implement the "insert" breakpoint_ops method for vfork
8015    catchpoints.  */
8016
8017 static int
8018 insert_catch_vfork (struct bp_location *bl)
8019 {
8020   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8021 }
8022
8023 /* Implement the "remove" breakpoint_ops method for vfork
8024    catchpoints.  */
8025
8026 static int
8027 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
8028 {
8029   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8030 }
8031
8032 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
8033    catchpoints.  */
8034
8035 static int
8036 breakpoint_hit_catch_vfork (const struct bp_location *bl,
8037                             struct address_space *aspace, CORE_ADDR bp_addr,
8038                             const struct target_waitstatus *ws)
8039 {
8040   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8041
8042   if (ws->kind != TARGET_WAITKIND_VFORKED)
8043     return 0;
8044
8045   c->forked_inferior_pid = ws->value.related_pid;
8046   return 1;
8047 }
8048
8049 /* Implement the "print_it" breakpoint_ops method for vfork
8050    catchpoints.  */
8051
8052 static enum print_stop_action
8053 print_it_catch_vfork (bpstat bs)
8054 {
8055   struct ui_out *uiout = current_uiout;
8056   struct breakpoint *b = bs->breakpoint_at;
8057   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8058
8059   annotate_catchpoint (b->number);
8060   maybe_print_thread_hit_breakpoint (uiout);
8061   if (b->disposition == disp_del)
8062     uiout->text ("Temporary catchpoint ");
8063   else
8064     uiout->text ("Catchpoint ");
8065   if (uiout->is_mi_like_p ())
8066     {
8067       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
8068       uiout->field_string ("disp", bpdisp_text (b->disposition));
8069     }
8070   uiout->field_int ("bkptno", b->number);
8071   uiout->text (" (vforked process ");
8072   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
8073   uiout->text ("), ");
8074   return PRINT_SRC_AND_LOC;
8075 }
8076
8077 /* Implement the "print_one" breakpoint_ops method for vfork
8078    catchpoints.  */
8079
8080 static void
8081 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
8082 {
8083   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8084   struct value_print_options opts;
8085   struct ui_out *uiout = current_uiout;
8086
8087   get_user_print_options (&opts);
8088   /* Field 4, the address, is omitted (which makes the columns not
8089      line up too nicely with the headers, but the effect is relatively
8090      readable).  */
8091   if (opts.addressprint)
8092     uiout->field_skip ("addr");
8093   annotate_field (5);
8094   uiout->text ("vfork");
8095   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8096     {
8097       uiout->text (", process ");
8098       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
8099       uiout->spaces (1);
8100     }
8101
8102   if (uiout->is_mi_like_p ())
8103     uiout->field_string ("catch-type", "vfork");
8104 }
8105
8106 /* Implement the "print_mention" breakpoint_ops method for vfork
8107    catchpoints.  */
8108
8109 static void
8110 print_mention_catch_vfork (struct breakpoint *b)
8111 {
8112   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8113 }
8114
8115 /* Implement the "print_recreate" breakpoint_ops method for vfork
8116    catchpoints.  */
8117
8118 static void
8119 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8120 {
8121   fprintf_unfiltered (fp, "catch vfork");
8122   print_recreate_thread (b, fp);
8123 }
8124
8125 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8126
8127 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8128
8129 /* An instance of this type is used to represent an solib catchpoint.
8130    A breakpoint is really of this type iff its ops pointer points to
8131    CATCH_SOLIB_BREAKPOINT_OPS.  */
8132
8133 struct solib_catchpoint : public breakpoint
8134 {
8135   ~solib_catchpoint () override;
8136
8137   /* True for "catch load", false for "catch unload".  */
8138   unsigned char is_load;
8139
8140   /* Regular expression to match, if any.  COMPILED is only valid when
8141      REGEX is non-NULL.  */
8142   char *regex;
8143   std::unique_ptr<compiled_regex> compiled;
8144 };
8145
8146 solib_catchpoint::~solib_catchpoint ()
8147 {
8148   xfree (this->regex);
8149 }
8150
8151 static int
8152 insert_catch_solib (struct bp_location *ignore)
8153 {
8154   return 0;
8155 }
8156
8157 static int
8158 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
8159 {
8160   return 0;
8161 }
8162
8163 static int
8164 breakpoint_hit_catch_solib (const struct bp_location *bl,
8165                             struct address_space *aspace,
8166                             CORE_ADDR bp_addr,
8167                             const struct target_waitstatus *ws)
8168 {
8169   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8170   struct breakpoint *other;
8171
8172   if (ws->kind == TARGET_WAITKIND_LOADED)
8173     return 1;
8174
8175   ALL_BREAKPOINTS (other)
8176   {
8177     struct bp_location *other_bl;
8178
8179     if (other == bl->owner)
8180       continue;
8181
8182     if (other->type != bp_shlib_event)
8183       continue;
8184
8185     if (self->pspace != NULL && other->pspace != self->pspace)
8186       continue;
8187
8188     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8189       {
8190         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8191           return 1;
8192       }
8193   }
8194
8195   return 0;
8196 }
8197
8198 static void
8199 check_status_catch_solib (struct bpstats *bs)
8200 {
8201   struct solib_catchpoint *self
8202     = (struct solib_catchpoint *) bs->breakpoint_at;
8203   int ix;
8204
8205   if (self->is_load)
8206     {
8207       struct so_list *iter;
8208
8209       for (ix = 0;
8210            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8211                         ix, iter);
8212            ++ix)
8213         {
8214           if (!self->regex
8215               || self->compiled->exec (iter->so_name, 0, NULL, 0) == 0)
8216             return;
8217         }
8218     }
8219   else
8220     {
8221       char *iter;
8222
8223       for (ix = 0;
8224            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8225                         ix, iter);
8226            ++ix)
8227         {
8228           if (!self->regex
8229               || self->compiled->exec (iter, 0, NULL, 0) == 0)
8230             return;
8231         }
8232     }
8233
8234   bs->stop = 0;
8235   bs->print_it = print_it_noop;
8236 }
8237
8238 static enum print_stop_action
8239 print_it_catch_solib (bpstat bs)
8240 {
8241   struct breakpoint *b = bs->breakpoint_at;
8242   struct ui_out *uiout = current_uiout;
8243
8244   annotate_catchpoint (b->number);
8245   maybe_print_thread_hit_breakpoint (uiout);
8246   if (b->disposition == disp_del)
8247     uiout->text ("Temporary catchpoint ");
8248   else
8249     uiout->text ("Catchpoint ");
8250   uiout->field_int ("bkptno", b->number);
8251   uiout->text ("\n");
8252   if (uiout->is_mi_like_p ())
8253     uiout->field_string ("disp", bpdisp_text (b->disposition));
8254   print_solib_event (1);
8255   return PRINT_SRC_AND_LOC;
8256 }
8257
8258 static void
8259 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8260 {
8261   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8262   struct value_print_options opts;
8263   struct ui_out *uiout = current_uiout;
8264   char *msg;
8265
8266   get_user_print_options (&opts);
8267   /* Field 4, the address, is omitted (which makes the columns not
8268      line up too nicely with the headers, but the effect is relatively
8269      readable).  */
8270   if (opts.addressprint)
8271     {
8272       annotate_field (4);
8273       uiout->field_skip ("addr");
8274     }
8275
8276   annotate_field (5);
8277   if (self->is_load)
8278     {
8279       if (self->regex)
8280         msg = xstrprintf (_("load of library matching %s"), self->regex);
8281       else
8282         msg = xstrdup (_("load of library"));
8283     }
8284   else
8285     {
8286       if (self->regex)
8287         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8288       else
8289         msg = xstrdup (_("unload of library"));
8290     }
8291   uiout->field_string ("what", msg);
8292   xfree (msg);
8293
8294   if (uiout->is_mi_like_p ())
8295     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8296 }
8297
8298 static void
8299 print_mention_catch_solib (struct breakpoint *b)
8300 {
8301   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8302
8303   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8304                    self->is_load ? "load" : "unload");
8305 }
8306
8307 static void
8308 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8309 {
8310   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8311
8312   fprintf_unfiltered (fp, "%s %s",
8313                       b->disposition == disp_del ? "tcatch" : "catch",
8314                       self->is_load ? "load" : "unload");
8315   if (self->regex)
8316     fprintf_unfiltered (fp, " %s", self->regex);
8317   fprintf_unfiltered (fp, "\n");
8318 }
8319
8320 static struct breakpoint_ops catch_solib_breakpoint_ops;
8321
8322 /* Shared helper function (MI and CLI) for creating and installing
8323    a shared object event catchpoint.  If IS_LOAD is non-zero then
8324    the events to be caught are load events, otherwise they are
8325    unload events.  If IS_TEMP is non-zero the catchpoint is a
8326    temporary one.  If ENABLED is non-zero the catchpoint is
8327    created in an enabled state.  */
8328
8329 void
8330 add_solib_catchpoint (const char *arg, int is_load, int is_temp, int enabled)
8331 {
8332   struct gdbarch *gdbarch = get_current_arch ();
8333
8334   if (!arg)
8335     arg = "";
8336   arg = skip_spaces (arg);
8337
8338   std::unique_ptr<solib_catchpoint> c (new solib_catchpoint ());
8339
8340   if (*arg != '\0')
8341     {
8342       c->compiled.reset (new compiled_regex (arg, REG_NOSUB,
8343                                              _("Invalid regexp")));
8344       c->regex = xstrdup (arg);
8345     }
8346
8347   c->is_load = is_load;
8348   init_catchpoint (c.get (), gdbarch, is_temp, NULL,
8349                    &catch_solib_breakpoint_ops);
8350
8351   c->enable_state = enabled ? bp_enabled : bp_disabled;
8352
8353   install_breakpoint (0, std::move (c), 1);
8354 }
8355
8356 /* A helper function that does all the work for "catch load" and
8357    "catch unload".  */
8358
8359 static void
8360 catch_load_or_unload (char *arg, int from_tty, int is_load,
8361                       struct cmd_list_element *command)
8362 {
8363   int tempflag;
8364   const int enabled = 1;
8365
8366   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8367
8368   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8369 }
8370
8371 static void
8372 catch_load_command_1 (char *arg, int from_tty,
8373                       struct cmd_list_element *command)
8374 {
8375   catch_load_or_unload (arg, from_tty, 1, command);
8376 }
8377
8378 static void
8379 catch_unload_command_1 (char *arg, int from_tty,
8380                         struct cmd_list_element *command)
8381 {
8382   catch_load_or_unload (arg, from_tty, 0, command);
8383 }
8384
8385 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8386    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8387    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8388    the breakpoint_ops structure associated to the catchpoint.  */
8389
8390 void
8391 init_catchpoint (struct breakpoint *b,
8392                  struct gdbarch *gdbarch, int tempflag,
8393                  const char *cond_string,
8394                  const struct breakpoint_ops *ops)
8395 {
8396   symtab_and_line sal;
8397   sal.pspace = current_program_space;
8398
8399   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8400
8401   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8402   b->disposition = tempflag ? disp_del : disp_donttouch;
8403 }
8404
8405 void
8406 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8407 {
8408   breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8409   set_breakpoint_number (internal, b);
8410   if (is_tracepoint (b))
8411     set_tracepoint_count (breakpoint_count);
8412   if (!internal)
8413     mention (b);
8414   observer_notify_breakpoint_created (b);
8415
8416   if (update_gll)
8417     update_global_location_list (UGLL_MAY_INSERT);
8418 }
8419
8420 static void
8421 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8422                                     int tempflag, const char *cond_string,
8423                                     const struct breakpoint_ops *ops)
8424 {
8425   std::unique_ptr<fork_catchpoint> c (new fork_catchpoint ());
8426
8427   init_catchpoint (c.get (), gdbarch, tempflag, cond_string, ops);
8428
8429   c->forked_inferior_pid = null_ptid;
8430
8431   install_breakpoint (0, std::move (c), 1);
8432 }
8433
8434 /* Exec catchpoints.  */
8435
8436 /* An instance of this type is used to represent an exec catchpoint.
8437    A breakpoint is really of this type iff its ops pointer points to
8438    CATCH_EXEC_BREAKPOINT_OPS.  */
8439
8440 struct exec_catchpoint : public breakpoint
8441 {
8442   ~exec_catchpoint () override;
8443
8444   /* Filename of a program whose exec triggered this catchpoint.
8445      This field is only valid immediately after this catchpoint has
8446      triggered.  */
8447   char *exec_pathname;
8448 };
8449
8450 /* Exec catchpoint destructor.  */
8451
8452 exec_catchpoint::~exec_catchpoint ()
8453 {
8454   xfree (this->exec_pathname);
8455 }
8456
8457 static int
8458 insert_catch_exec (struct bp_location *bl)
8459 {
8460   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8461 }
8462
8463 static int
8464 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8465 {
8466   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8467 }
8468
8469 static int
8470 breakpoint_hit_catch_exec (const struct bp_location *bl,
8471                            struct address_space *aspace, CORE_ADDR bp_addr,
8472                            const struct target_waitstatus *ws)
8473 {
8474   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8475
8476   if (ws->kind != TARGET_WAITKIND_EXECD)
8477     return 0;
8478
8479   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8480   return 1;
8481 }
8482
8483 static enum print_stop_action
8484 print_it_catch_exec (bpstat bs)
8485 {
8486   struct ui_out *uiout = current_uiout;
8487   struct breakpoint *b = bs->breakpoint_at;
8488   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8489
8490   annotate_catchpoint (b->number);
8491   maybe_print_thread_hit_breakpoint (uiout);
8492   if (b->disposition == disp_del)
8493     uiout->text ("Temporary catchpoint ");
8494   else
8495     uiout->text ("Catchpoint ");
8496   if (uiout->is_mi_like_p ())
8497     {
8498       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8499       uiout->field_string ("disp", bpdisp_text (b->disposition));
8500     }
8501   uiout->field_int ("bkptno", b->number);
8502   uiout->text (" (exec'd ");
8503   uiout->field_string ("new-exec", c->exec_pathname);
8504   uiout->text ("), ");
8505
8506   return PRINT_SRC_AND_LOC;
8507 }
8508
8509 static void
8510 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8511 {
8512   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8513   struct value_print_options opts;
8514   struct ui_out *uiout = current_uiout;
8515
8516   get_user_print_options (&opts);
8517
8518   /* Field 4, the address, is omitted (which makes the columns
8519      not line up too nicely with the headers, but the effect
8520      is relatively readable).  */
8521   if (opts.addressprint)
8522     uiout->field_skip ("addr");
8523   annotate_field (5);
8524   uiout->text ("exec");
8525   if (c->exec_pathname != NULL)
8526     {
8527       uiout->text (", program \"");
8528       uiout->field_string ("what", c->exec_pathname);
8529       uiout->text ("\" ");
8530     }
8531
8532   if (uiout->is_mi_like_p ())
8533     uiout->field_string ("catch-type", "exec");
8534 }
8535
8536 static void
8537 print_mention_catch_exec (struct breakpoint *b)
8538 {
8539   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8540 }
8541
8542 /* Implement the "print_recreate" breakpoint_ops method for exec
8543    catchpoints.  */
8544
8545 static void
8546 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8547 {
8548   fprintf_unfiltered (fp, "catch exec");
8549   print_recreate_thread (b, fp);
8550 }
8551
8552 static struct breakpoint_ops catch_exec_breakpoint_ops;
8553
8554 static int
8555 hw_breakpoint_used_count (void)
8556 {
8557   int i = 0;
8558   struct breakpoint *b;
8559   struct bp_location *bl;
8560
8561   ALL_BREAKPOINTS (b)
8562   {
8563     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8564       for (bl = b->loc; bl; bl = bl->next)
8565         {
8566           /* Special types of hardware breakpoints may use more than
8567              one register.  */
8568           i += b->ops->resources_needed (bl);
8569         }
8570   }
8571
8572   return i;
8573 }
8574
8575 /* Returns the resources B would use if it were a hardware
8576    watchpoint.  */
8577
8578 static int
8579 hw_watchpoint_use_count (struct breakpoint *b)
8580 {
8581   int i = 0;
8582   struct bp_location *bl;
8583
8584   if (!breakpoint_enabled (b))
8585     return 0;
8586
8587   for (bl = b->loc; bl; bl = bl->next)
8588     {
8589       /* Special types of hardware watchpoints may use more than
8590          one register.  */
8591       i += b->ops->resources_needed (bl);
8592     }
8593
8594   return i;
8595 }
8596
8597 /* Returns the sum the used resources of all hardware watchpoints of
8598    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8599    the sum of the used resources of all hardware watchpoints of other
8600    types _not_ TYPE.  */
8601
8602 static int
8603 hw_watchpoint_used_count_others (struct breakpoint *except,
8604                                  enum bptype type, int *other_type_used)
8605 {
8606   int i = 0;
8607   struct breakpoint *b;
8608
8609   *other_type_used = 0;
8610   ALL_BREAKPOINTS (b)
8611     {
8612       if (b == except)
8613         continue;
8614       if (!breakpoint_enabled (b))
8615         continue;
8616
8617       if (b->type == type)
8618         i += hw_watchpoint_use_count (b);
8619       else if (is_hardware_watchpoint (b))
8620         *other_type_used = 1;
8621     }
8622
8623   return i;
8624 }
8625
8626 void
8627 disable_watchpoints_before_interactive_call_start (void)
8628 {
8629   struct breakpoint *b;
8630
8631   ALL_BREAKPOINTS (b)
8632   {
8633     if (is_watchpoint (b) && breakpoint_enabled (b))
8634       {
8635         b->enable_state = bp_call_disabled;
8636         update_global_location_list (UGLL_DONT_INSERT);
8637       }
8638   }
8639 }
8640
8641 void
8642 enable_watchpoints_after_interactive_call_stop (void)
8643 {
8644   struct breakpoint *b;
8645
8646   ALL_BREAKPOINTS (b)
8647   {
8648     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8649       {
8650         b->enable_state = bp_enabled;
8651         update_global_location_list (UGLL_MAY_INSERT);
8652       }
8653   }
8654 }
8655
8656 void
8657 disable_breakpoints_before_startup (void)
8658 {
8659   current_program_space->executing_startup = 1;
8660   update_global_location_list (UGLL_DONT_INSERT);
8661 }
8662
8663 void
8664 enable_breakpoints_after_startup (void)
8665 {
8666   current_program_space->executing_startup = 0;
8667   breakpoint_re_set ();
8668 }
8669
8670 /* Create a new single-step breakpoint for thread THREAD, with no
8671    locations.  */
8672
8673 static struct breakpoint *
8674 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8675 {
8676   std::unique_ptr<breakpoint> b (new breakpoint ());
8677
8678   init_raw_breakpoint_without_location (b.get (), gdbarch, bp_single_step,
8679                                         &momentary_breakpoint_ops);
8680
8681   b->disposition = disp_donttouch;
8682   b->frame_id = null_frame_id;
8683
8684   b->thread = thread;
8685   gdb_assert (b->thread != 0);
8686
8687   return add_to_breakpoint_chain (std::move (b));
8688 }
8689
8690 /* Set a momentary breakpoint of type TYPE at address specified by
8691    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8692    frame.  */
8693
8694 struct breakpoint *
8695 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8696                           struct frame_id frame_id, enum bptype type)
8697 {
8698   struct breakpoint *b;
8699
8700   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8701      tail-called one.  */
8702   gdb_assert (!frame_id_artificial_p (frame_id));
8703
8704   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8705   b->enable_state = bp_enabled;
8706   b->disposition = disp_donttouch;
8707   b->frame_id = frame_id;
8708
8709   /* If we're debugging a multi-threaded program, then we want
8710      momentary breakpoints to be active in only a single thread of
8711      control.  */
8712   if (in_thread_list (inferior_ptid))
8713     b->thread = ptid_to_global_thread_id (inferior_ptid);
8714
8715   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8716
8717   return b;
8718 }
8719
8720 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8721    The new breakpoint will have type TYPE, use OPS as its
8722    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8723
8724 static struct breakpoint *
8725 momentary_breakpoint_from_master (struct breakpoint *orig,
8726                                   enum bptype type,
8727                                   const struct breakpoint_ops *ops,
8728                                   int loc_enabled)
8729 {
8730   struct breakpoint *copy;
8731
8732   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8733   copy->loc = allocate_bp_location (copy);
8734   set_breakpoint_location_function (copy->loc, 1);
8735
8736   copy->loc->gdbarch = orig->loc->gdbarch;
8737   copy->loc->requested_address = orig->loc->requested_address;
8738   copy->loc->address = orig->loc->address;
8739   copy->loc->section = orig->loc->section;
8740   copy->loc->pspace = orig->loc->pspace;
8741   copy->loc->probe = orig->loc->probe;
8742   copy->loc->line_number = orig->loc->line_number;
8743   copy->loc->symtab = orig->loc->symtab;
8744   copy->loc->enabled = loc_enabled;
8745   copy->frame_id = orig->frame_id;
8746   copy->thread = orig->thread;
8747   copy->pspace = orig->pspace;
8748
8749   copy->enable_state = bp_enabled;
8750   copy->disposition = disp_donttouch;
8751   copy->number = internal_breakpoint_number--;
8752
8753   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8754   return copy;
8755 }
8756
8757 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8758    ORIG is NULL.  */
8759
8760 struct breakpoint *
8761 clone_momentary_breakpoint (struct breakpoint *orig)
8762 {
8763   /* If there's nothing to clone, then return nothing.  */
8764   if (orig == NULL)
8765     return NULL;
8766
8767   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8768 }
8769
8770 struct breakpoint *
8771 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8772                                 enum bptype type)
8773 {
8774   struct symtab_and_line sal;
8775
8776   sal = find_pc_line (pc, 0);
8777   sal.pc = pc;
8778   sal.section = find_pc_overlay (pc);
8779   sal.explicit_pc = 1;
8780
8781   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8782 }
8783 \f
8784
8785 /* Tell the user we have just set a breakpoint B.  */
8786
8787 static void
8788 mention (struct breakpoint *b)
8789 {
8790   b->ops->print_mention (b);
8791   if (current_uiout->is_mi_like_p ())
8792     return;
8793   printf_filtered ("\n");
8794 }
8795 \f
8796
8797 static int bp_loc_is_permanent (struct bp_location *loc);
8798
8799 static struct bp_location *
8800 add_location_to_breakpoint (struct breakpoint *b,
8801                             const struct symtab_and_line *sal)
8802 {
8803   struct bp_location *loc, **tmp;
8804   CORE_ADDR adjusted_address;
8805   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8806
8807   if (loc_gdbarch == NULL)
8808     loc_gdbarch = b->gdbarch;
8809
8810   /* Adjust the breakpoint's address prior to allocating a location.
8811      Once we call allocate_bp_location(), that mostly uninitialized
8812      location will be placed on the location chain.  Adjustment of the
8813      breakpoint may cause target_read_memory() to be called and we do
8814      not want its scan of the location chain to find a breakpoint and
8815      location that's only been partially initialized.  */
8816   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8817                                                 sal->pc, b->type);
8818
8819   /* Sort the locations by their ADDRESS.  */
8820   loc = allocate_bp_location (b);
8821   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8822        tmp = &((*tmp)->next))
8823     ;
8824   loc->next = *tmp;
8825   *tmp = loc;
8826
8827   loc->requested_address = sal->pc;
8828   loc->address = adjusted_address;
8829   loc->pspace = sal->pspace;
8830   loc->probe.probe = sal->probe;
8831   loc->probe.objfile = sal->objfile;
8832   gdb_assert (loc->pspace != NULL);
8833   loc->section = sal->section;
8834   loc->gdbarch = loc_gdbarch;
8835   loc->line_number = sal->line;
8836   loc->symtab = sal->symtab;
8837
8838   set_breakpoint_location_function (loc,
8839                                     sal->explicit_pc || sal->explicit_line);
8840
8841   /* While by definition, permanent breakpoints are already present in the
8842      code, we don't mark the location as inserted.  Normally one would expect
8843      that GDB could rely on that breakpoint instruction to stop the program,
8844      thus removing the need to insert its own breakpoint, except that executing
8845      the breakpoint instruction can kill the target instead of reporting a
8846      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8847      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8848      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8849      breakpoint be inserted normally results in QEMU knowing about the GDB
8850      breakpoint, and thus trap before the breakpoint instruction is executed.
8851      (If GDB later needs to continue execution past the permanent breakpoint,
8852      it manually increments the PC, thus avoiding executing the breakpoint
8853      instruction.)  */
8854   if (bp_loc_is_permanent (loc))
8855     loc->permanent = 1;
8856
8857   return loc;
8858 }
8859 \f
8860
8861 /* See breakpoint.h.  */
8862
8863 int
8864 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
8865 {
8866   int len;
8867   CORE_ADDR addr;
8868   const gdb_byte *bpoint;
8869   gdb_byte *target_mem;
8870
8871   addr = address;
8872   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
8873
8874   /* Software breakpoints unsupported?  */
8875   if (bpoint == NULL)
8876     return 0;
8877
8878   target_mem = (gdb_byte *) alloca (len);
8879
8880   /* Enable the automatic memory restoration from breakpoints while
8881      we read the memory.  Otherwise we could say about our temporary
8882      breakpoints they are permanent.  */
8883   scoped_restore restore_memory
8884     = make_scoped_restore_show_memory_breakpoints (0);
8885
8886   if (target_read_memory (address, target_mem, len) == 0
8887       && memcmp (target_mem, bpoint, len) == 0)
8888     return 1;
8889
8890   return 0;
8891 }
8892
8893 /* Return 1 if LOC is pointing to a permanent breakpoint,
8894    return 0 otherwise.  */
8895
8896 static int
8897 bp_loc_is_permanent (struct bp_location *loc)
8898 {
8899   gdb_assert (loc != NULL);
8900
8901   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
8902      attempt to read from the addresses the locations of these breakpoint types
8903      point to.  program_breakpoint_here_p, below, will attempt to read
8904      memory.  */
8905   if (!breakpoint_address_is_meaningful (loc->owner))
8906     return 0;
8907
8908   scoped_restore_current_pspace_and_thread restore_pspace_thread;
8909   switch_to_program_space_and_thread (loc->pspace);
8910   return program_breakpoint_here_p (loc->gdbarch, loc->address);
8911 }
8912
8913 /* Build a command list for the dprintf corresponding to the current
8914    settings of the dprintf style options.  */
8915
8916 static void
8917 update_dprintf_command_list (struct breakpoint *b)
8918 {
8919   char *dprintf_args = b->extra_string;
8920   char *printf_line = NULL;
8921
8922   if (!dprintf_args)
8923     return;
8924
8925   dprintf_args = skip_spaces (dprintf_args);
8926
8927   /* Allow a comma, as it may have terminated a location, but don't
8928      insist on it.  */
8929   if (*dprintf_args == ',')
8930     ++dprintf_args;
8931   dprintf_args = skip_spaces (dprintf_args);
8932
8933   if (*dprintf_args != '"')
8934     error (_("Bad format string, missing '\"'."));
8935
8936   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8937     printf_line = xstrprintf ("printf %s", dprintf_args);
8938   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8939     {
8940       if (!dprintf_function)
8941         error (_("No function supplied for dprintf call"));
8942
8943       if (dprintf_channel && strlen (dprintf_channel) > 0)
8944         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8945                                   dprintf_function,
8946                                   dprintf_channel,
8947                                   dprintf_args);
8948       else
8949         printf_line = xstrprintf ("call (void) %s (%s)",
8950                                   dprintf_function,
8951                                   dprintf_args);
8952     }
8953   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8954     {
8955       if (target_can_run_breakpoint_commands ())
8956         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8957       else
8958         {
8959           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8960           printf_line = xstrprintf ("printf %s", dprintf_args);
8961         }
8962     }
8963   else
8964     internal_error (__FILE__, __LINE__,
8965                     _("Invalid dprintf style."));
8966
8967   gdb_assert (printf_line != NULL);
8968   /* Manufacture a printf sequence.  */
8969   {
8970     struct command_line *printf_cmd_line = XNEW (struct command_line);
8971
8972     printf_cmd_line->control_type = simple_control;
8973     printf_cmd_line->body_count = 0;
8974     printf_cmd_line->body_list = NULL;
8975     printf_cmd_line->next = NULL;
8976     printf_cmd_line->line = printf_line;
8977
8978     breakpoint_set_commands (b, command_line_up (printf_cmd_line));
8979   }
8980 }
8981
8982 /* Update all dprintf commands, making their command lists reflect
8983    current style settings.  */
8984
8985 static void
8986 update_dprintf_commands (char *args, int from_tty,
8987                          struct cmd_list_element *c)
8988 {
8989   struct breakpoint *b;
8990
8991   ALL_BREAKPOINTS (b)
8992     {
8993       if (b->type == bp_dprintf)
8994         update_dprintf_command_list (b);
8995     }
8996 }
8997
8998 /* Create a breakpoint with SAL as location.  Use LOCATION
8999    as a description of the location, and COND_STRING
9000    as condition expression.  If LOCATION is NULL then create an
9001    "address location" from the address in the SAL.  */
9002
9003 static void
9004 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9005                      gdb::array_view<const symtab_and_line> sals,
9006                      event_location_up &&location,
9007                      gdb::unique_xmalloc_ptr<char> filter,
9008                      gdb::unique_xmalloc_ptr<char> cond_string,
9009                      gdb::unique_xmalloc_ptr<char> extra_string,
9010                      enum bptype type, enum bpdisp disposition,
9011                      int thread, int task, int ignore_count,
9012                      const struct breakpoint_ops *ops, int from_tty,
9013                      int enabled, int internal, unsigned flags,
9014                      int display_canonical)
9015 {
9016   int i;
9017
9018   if (type == bp_hardware_breakpoint)
9019     {
9020       int target_resources_ok;
9021
9022       i = hw_breakpoint_used_count ();
9023       target_resources_ok =
9024         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9025                                             i + 1, 0);
9026       if (target_resources_ok == 0)
9027         error (_("No hardware breakpoint support in the target."));
9028       else if (target_resources_ok < 0)
9029         error (_("Hardware breakpoints used exceeds limit."));
9030     }
9031
9032   gdb_assert (!sals.empty ());
9033
9034   for (const auto &sal : sals)
9035     {
9036       struct bp_location *loc;
9037
9038       if (from_tty)
9039         {
9040           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9041           if (!loc_gdbarch)
9042             loc_gdbarch = gdbarch;
9043
9044           describe_other_breakpoints (loc_gdbarch,
9045                                       sal.pspace, sal.pc, sal.section, thread);
9046         }
9047
9048       if (&sal == &sals[0])
9049         {
9050           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9051           b->thread = thread;
9052           b->task = task;
9053
9054           b->cond_string = cond_string.release ();
9055           b->extra_string = extra_string.release ();
9056           b->ignore_count = ignore_count;
9057           b->enable_state = enabled ? bp_enabled : bp_disabled;
9058           b->disposition = disposition;
9059
9060           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9061             b->loc->inserted = 1;
9062
9063           if (type == bp_static_tracepoint)
9064             {
9065               struct tracepoint *t = (struct tracepoint *) b;
9066               struct static_tracepoint_marker marker;
9067
9068               if (strace_marker_p (b))
9069                 {
9070                   /* We already know the marker exists, otherwise, we
9071                      wouldn't see a sal for it.  */
9072                   const char *p
9073                     = &event_location_to_string (b->location.get ())[3];
9074                   const char *endp;
9075                   char *marker_str;
9076
9077                   p = skip_spaces (p);
9078
9079                   endp = skip_to_space (p);
9080
9081                   marker_str = savestring (p, endp - p);
9082                   t->static_trace_marker_id = marker_str;
9083
9084                   printf_filtered (_("Probed static tracepoint "
9085                                      "marker \"%s\"\n"),
9086                                    t->static_trace_marker_id);
9087                 }
9088               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9089                 {
9090                   t->static_trace_marker_id = xstrdup (marker.str_id);
9091                   release_static_tracepoint_marker (&marker);
9092
9093                   printf_filtered (_("Probed static tracepoint "
9094                                      "marker \"%s\"\n"),
9095                                    t->static_trace_marker_id);
9096                 }
9097               else
9098                 warning (_("Couldn't determine the static "
9099                            "tracepoint marker to probe"));
9100             }
9101
9102           loc = b->loc;
9103         }
9104       else
9105         {
9106           loc = add_location_to_breakpoint (b, &sal);
9107           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9108             loc->inserted = 1;
9109         }
9110
9111       if (b->cond_string)
9112         {
9113           const char *arg = b->cond_string;
9114
9115           loc->cond = parse_exp_1 (&arg, loc->address,
9116                                    block_for_pc (loc->address), 0);
9117           if (*arg)
9118               error (_("Garbage '%s' follows condition"), arg);
9119         }
9120
9121       /* Dynamic printf requires and uses additional arguments on the
9122          command line, otherwise it's an error.  */
9123       if (type == bp_dprintf)
9124         {
9125           if (b->extra_string)
9126             update_dprintf_command_list (b);
9127           else
9128             error (_("Format string required"));
9129         }
9130       else if (b->extra_string)
9131         error (_("Garbage '%s' at end of command"), b->extra_string);
9132     }
9133
9134   b->display_canonical = display_canonical;
9135   if (location != NULL)
9136     b->location = std::move (location);
9137   else
9138     b->location = new_address_location (b->loc->address, NULL, 0);
9139   b->filter = filter.release ();
9140 }
9141
9142 static void
9143 create_breakpoint_sal (struct gdbarch *gdbarch,
9144                        gdb::array_view<const symtab_and_line> sals,
9145                        event_location_up &&location,
9146                        gdb::unique_xmalloc_ptr<char> filter,
9147                        gdb::unique_xmalloc_ptr<char> cond_string,
9148                        gdb::unique_xmalloc_ptr<char> extra_string,
9149                        enum bptype type, enum bpdisp disposition,
9150                        int thread, int task, int ignore_count,
9151                        const struct breakpoint_ops *ops, int from_tty,
9152                        int enabled, int internal, unsigned flags,
9153                        int display_canonical)
9154 {
9155   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (type);
9156
9157   init_breakpoint_sal (b.get (), gdbarch,
9158                        sals, std::move (location),
9159                        std::move (filter),
9160                        std::move (cond_string),
9161                        std::move (extra_string),
9162                        type, disposition,
9163                        thread, task, ignore_count,
9164                        ops, from_tty,
9165                        enabled, internal, flags,
9166                        display_canonical);
9167
9168   install_breakpoint (internal, std::move (b), 0);
9169 }
9170
9171 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9172    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9173    value.  COND_STRING, if not NULL, specified the condition to be
9174    used for all breakpoints.  Essentially the only case where
9175    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9176    function.  In that case, it's still not possible to specify
9177    separate conditions for different overloaded functions, so
9178    we take just a single condition string.
9179    
9180    NOTE: If the function succeeds, the caller is expected to cleanup
9181    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9182    array contents).  If the function fails (error() is called), the
9183    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9184    COND and SALS arrays and each of those arrays contents.  */
9185
9186 static void
9187 create_breakpoints_sal (struct gdbarch *gdbarch,
9188                         struct linespec_result *canonical,
9189                         gdb::unique_xmalloc_ptr<char> cond_string,
9190                         gdb::unique_xmalloc_ptr<char> extra_string,
9191                         enum bptype type, enum bpdisp disposition,
9192                         int thread, int task, int ignore_count,
9193                         const struct breakpoint_ops *ops, int from_tty,
9194                         int enabled, int internal, unsigned flags)
9195 {
9196   if (canonical->pre_expanded)
9197     gdb_assert (canonical->lsals.size () == 1);
9198
9199   for (const auto &lsal : canonical->lsals)
9200     {
9201       /* Note that 'location' can be NULL in the case of a plain
9202          'break', without arguments.  */
9203       event_location_up location
9204         = (canonical->location != NULL
9205            ? copy_event_location (canonical->location.get ()) : NULL);
9206       gdb::unique_xmalloc_ptr<char> filter_string
9207         (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
9208
9209       create_breakpoint_sal (gdbarch, lsal.sals,
9210                              std::move (location),
9211                              std::move (filter_string),
9212                              std::move (cond_string),
9213                              std::move (extra_string),
9214                              type, disposition,
9215                              thread, task, ignore_count, ops,
9216                              from_tty, enabled, internal, flags,
9217                              canonical->special_display);
9218     }
9219 }
9220
9221 /* Parse LOCATION which is assumed to be a SAL specification possibly
9222    followed by conditionals.  On return, SALS contains an array of SAL
9223    addresses found.  LOCATION points to the end of the SAL (for
9224    linespec locations).
9225
9226    The array and the line spec strings are allocated on the heap, it is
9227    the caller's responsibility to free them.  */
9228
9229 static void
9230 parse_breakpoint_sals (const struct event_location *location,
9231                        struct linespec_result *canonical)
9232 {
9233   struct symtab_and_line cursal;
9234
9235   if (event_location_type (location) == LINESPEC_LOCATION)
9236     {
9237       const char *address = get_linespec_location (location);
9238
9239       if (address == NULL)
9240         {
9241           /* The last displayed codepoint, if it's valid, is our default
9242              breakpoint address.  */
9243           if (last_displayed_sal_is_valid ())
9244             {
9245               /* Set sal's pspace, pc, symtab, and line to the values
9246                  corresponding to the last call to print_frame_info.
9247                  Be sure to reinitialize LINE with NOTCURRENT == 0
9248                  as the breakpoint line number is inappropriate otherwise.
9249                  find_pc_line would adjust PC, re-set it back.  */
9250               symtab_and_line sal = get_last_displayed_sal ();
9251               CORE_ADDR pc = sal.pc;
9252
9253               sal = find_pc_line (pc, 0);
9254
9255               /* "break" without arguments is equivalent to "break *PC"
9256                  where PC is the last displayed codepoint's address.  So
9257                  make sure to set sal.explicit_pc to prevent GDB from
9258                  trying to expand the list of sals to include all other
9259                  instances with the same symtab and line.  */
9260               sal.pc = pc;
9261               sal.explicit_pc = 1;
9262
9263               struct linespec_sals lsal;
9264               lsal.sals = {sal};
9265               lsal.canonical = NULL;
9266
9267               canonical->lsals.push_back (std::move (lsal));
9268               return;
9269             }
9270           else
9271             error (_("No default breakpoint address now."));
9272         }
9273     }
9274
9275   /* Force almost all breakpoints to be in terms of the
9276      current_source_symtab (which is decode_line_1's default).
9277      This should produce the results we want almost all of the
9278      time while leaving default_breakpoint_* alone.
9279
9280      ObjC: However, don't match an Objective-C method name which
9281      may have a '+' or '-' succeeded by a '['.  */
9282   cursal = get_current_source_symtab_and_line ();
9283   if (last_displayed_sal_is_valid ())
9284     {
9285       const char *address = NULL;
9286
9287       if (event_location_type (location) == LINESPEC_LOCATION)
9288         address = get_linespec_location (location);
9289
9290       if (!cursal.symtab
9291           || (address != NULL
9292               && strchr ("+-", address[0]) != NULL
9293               && address[1] != '['))
9294         {
9295           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9296                             get_last_displayed_symtab (),
9297                             get_last_displayed_line (),
9298                             canonical, NULL, NULL);
9299           return;
9300         }
9301     }
9302
9303   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9304                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9305 }
9306
9307
9308 /* Convert each SAL into a real PC.  Verify that the PC can be
9309    inserted as a breakpoint.  If it can't throw an error.  */
9310
9311 static void
9312 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
9313 {    
9314   for (auto &sal : sals)
9315     resolve_sal_pc (&sal);
9316 }
9317
9318 /* Fast tracepoints may have restrictions on valid locations.  For
9319    instance, a fast tracepoint using a jump instead of a trap will
9320    likely have to overwrite more bytes than a trap would, and so can
9321    only be placed where the instruction is longer than the jump, or a
9322    multi-instruction sequence does not have a jump into the middle of
9323    it, etc.  */
9324
9325 static void
9326 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9327                             gdb::array_view<const symtab_and_line> sals)
9328 {
9329   int rslt;
9330   char *msg;
9331   struct cleanup *old_chain;
9332
9333   for (const auto &sal : sals)
9334     {
9335       struct gdbarch *sarch;
9336
9337       sarch = get_sal_arch (sal);
9338       /* We fall back to GDBARCH if there is no architecture
9339          associated with SAL.  */
9340       if (sarch == NULL)
9341         sarch = gdbarch;
9342       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg);
9343       old_chain = make_cleanup (xfree, msg);
9344
9345       if (!rslt)
9346         error (_("May not have a fast tracepoint at %s%s"),
9347                paddress (sarch, sal.pc), (msg ? msg : ""));
9348
9349       do_cleanups (old_chain);
9350     }
9351 }
9352
9353 /* Given TOK, a string specification of condition and thread, as
9354    accepted by the 'break' command, extract the condition
9355    string and thread number and set *COND_STRING and *THREAD.
9356    PC identifies the context at which the condition should be parsed.
9357    If no condition is found, *COND_STRING is set to NULL.
9358    If no thread is found, *THREAD is set to -1.  */
9359
9360 static void
9361 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9362                            char **cond_string, int *thread, int *task,
9363                            char **rest)
9364 {
9365   *cond_string = NULL;
9366   *thread = -1;
9367   *task = 0;
9368   *rest = NULL;
9369
9370   while (tok && *tok)
9371     {
9372       const char *end_tok;
9373       int toklen;
9374       const char *cond_start = NULL;
9375       const char *cond_end = NULL;
9376
9377       tok = skip_spaces (tok);
9378
9379       if ((*tok == '"' || *tok == ',') && rest)
9380         {
9381           *rest = savestring (tok, strlen (tok));
9382           return;
9383         }
9384
9385       end_tok = skip_to_space (tok);
9386
9387       toklen = end_tok - tok;
9388
9389       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9390         {
9391           tok = cond_start = end_tok + 1;
9392           parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9393           cond_end = tok;
9394           *cond_string = savestring (cond_start, cond_end - cond_start);
9395         }
9396       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9397         {
9398           const char *tmptok;
9399           struct thread_info *thr;
9400
9401           tok = end_tok + 1;
9402           thr = parse_thread_id (tok, &tmptok);
9403           if (tok == tmptok)
9404             error (_("Junk after thread keyword."));
9405           *thread = thr->global_num;
9406           tok = tmptok;
9407         }
9408       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9409         {
9410           char *tmptok;
9411
9412           tok = end_tok + 1;
9413           *task = strtol (tok, &tmptok, 0);
9414           if (tok == tmptok)
9415             error (_("Junk after task keyword."));
9416           if (!valid_task_id (*task))
9417             error (_("Unknown task %d."), *task);
9418           tok = tmptok;
9419         }
9420       else if (rest)
9421         {
9422           *rest = savestring (tok, strlen (tok));
9423           return;
9424         }
9425       else
9426         error (_("Junk at end of arguments."));
9427     }
9428 }
9429
9430 /* Decode a static tracepoint marker spec.  */
9431
9432 static std::vector<symtab_and_line>
9433 decode_static_tracepoint_spec (const char **arg_p)
9434 {
9435   VEC(static_tracepoint_marker_p) *markers = NULL;
9436   struct cleanup *old_chain;
9437   const char *p = &(*arg_p)[3];
9438   const char *endp;
9439   char *marker_str;
9440   int i;
9441
9442   p = skip_spaces (p);
9443
9444   endp = skip_to_space (p);
9445
9446   marker_str = savestring (p, endp - p);
9447   old_chain = make_cleanup (xfree, marker_str);
9448
9449   markers = target_static_tracepoint_markers_by_strid (marker_str);
9450   if (VEC_empty(static_tracepoint_marker_p, markers))
9451     error (_("No known static tracepoint marker named %s"), marker_str);
9452
9453   std::vector<symtab_and_line> sals;
9454   sals.reserve (VEC_length(static_tracepoint_marker_p, markers));
9455
9456   for (i = 0; i < VEC_length(static_tracepoint_marker_p, markers); i++)
9457     {
9458       struct static_tracepoint_marker *marker;
9459
9460       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9461
9462       symtab_and_line sal = find_pc_line (marker->address, 0);
9463       sal.pc = marker->address;
9464       sals.push_back (sal);
9465
9466       release_static_tracepoint_marker (marker);
9467     }
9468
9469   do_cleanups (old_chain);
9470
9471   *arg_p = endp;
9472   return sals;
9473 }
9474
9475 /* See breakpoint.h.  */
9476
9477 int
9478 create_breakpoint (struct gdbarch *gdbarch,
9479                    const struct event_location *location,
9480                    const char *cond_string,
9481                    int thread, const char *extra_string,
9482                    int parse_extra,
9483                    int tempflag, enum bptype type_wanted,
9484                    int ignore_count,
9485                    enum auto_boolean pending_break_support,
9486                    const struct breakpoint_ops *ops,
9487                    int from_tty, int enabled, int internal,
9488                    unsigned flags)
9489 {
9490   struct linespec_result canonical;
9491   struct cleanup *bkpt_chain = NULL;
9492   int pending = 0;
9493   int task = 0;
9494   int prev_bkpt_count = breakpoint_count;
9495
9496   gdb_assert (ops != NULL);
9497
9498   /* If extra_string isn't useful, set it to NULL.  */
9499   if (extra_string != NULL && *extra_string == '\0')
9500     extra_string = NULL;
9501
9502   TRY
9503     {
9504       ops->create_sals_from_location (location, &canonical, type_wanted);
9505     }
9506   CATCH (e, RETURN_MASK_ERROR)
9507     {
9508       /* If caller is interested in rc value from parse, set
9509          value.  */
9510       if (e.error == NOT_FOUND_ERROR)
9511         {
9512           /* If pending breakpoint support is turned off, throw
9513              error.  */
9514
9515           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9516             throw_exception (e);
9517
9518           exception_print (gdb_stderr, e);
9519
9520           /* If pending breakpoint support is auto query and the user
9521              selects no, then simply return the error code.  */
9522           if (pending_break_support == AUTO_BOOLEAN_AUTO
9523               && !nquery (_("Make %s pending on future shared library load? "),
9524                           bptype_string (type_wanted)))
9525             return 0;
9526
9527           /* At this point, either the user was queried about setting
9528              a pending breakpoint and selected yes, or pending
9529              breakpoint behavior is on and thus a pending breakpoint
9530              is defaulted on behalf of the user.  */
9531           pending = 1;
9532         }
9533       else
9534         throw_exception (e);
9535     }
9536   END_CATCH
9537
9538   if (!pending && canonical.lsals.empty ())
9539     return 0;
9540
9541   /* ----------------------------- SNIP -----------------------------
9542      Anything added to the cleanup chain beyond this point is assumed
9543      to be part of a breakpoint.  If the breakpoint create succeeds
9544      then the memory is not reclaimed.  */
9545   bkpt_chain = make_cleanup (null_cleanup, 0);
9546
9547   /* Resolve all line numbers to PC's and verify that the addresses
9548      are ok for the target.  */
9549   if (!pending)
9550     {
9551       for (auto &lsal : canonical.lsals)
9552         breakpoint_sals_to_pc (lsal.sals);
9553     }
9554
9555   /* Fast tracepoints may have additional restrictions on location.  */
9556   if (!pending && type_wanted == bp_fast_tracepoint)
9557     {
9558       for (const auto &lsal : canonical.lsals)
9559         check_fast_tracepoint_sals (gdbarch, lsal.sals);
9560     }
9561
9562   /* Verify that condition can be parsed, before setting any
9563      breakpoints.  Allocate a separate condition expression for each
9564      breakpoint.  */
9565   if (!pending)
9566     {
9567       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9568       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9569
9570       if (parse_extra)
9571         {
9572           char *rest;
9573           char *cond;
9574
9575           const linespec_sals &lsal = canonical.lsals[0];
9576
9577           /* Here we only parse 'arg' to separate condition
9578              from thread number, so parsing in context of first
9579              sal is OK.  When setting the breakpoint we'll
9580              re-parse it in context of each sal.  */
9581
9582           find_condition_and_thread (extra_string, lsal.sals[0].pc,
9583                                      &cond, &thread, &task, &rest);
9584           cond_string_copy.reset (cond);
9585           extra_string_copy.reset (rest);
9586         }
9587       else
9588         {
9589           if (type_wanted != bp_dprintf
9590               && extra_string != NULL && *extra_string != '\0')
9591                 error (_("Garbage '%s' at end of location"), extra_string);
9592
9593           /* Create a private copy of condition string.  */
9594           if (cond_string)
9595             cond_string_copy.reset (xstrdup (cond_string));
9596           /* Create a private copy of any extra string.  */
9597           if (extra_string)
9598             extra_string_copy.reset (xstrdup (extra_string));
9599         }
9600
9601       ops->create_breakpoints_sal (gdbarch, &canonical,
9602                                    std::move (cond_string_copy),
9603                                    std::move (extra_string_copy),
9604                                    type_wanted,
9605                                    tempflag ? disp_del : disp_donttouch,
9606                                    thread, task, ignore_count, ops,
9607                                    from_tty, enabled, internal, flags);
9608     }
9609   else
9610     {
9611       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (type_wanted);
9612
9613       init_raw_breakpoint_without_location (b.get (), gdbarch, type_wanted, ops);
9614       b->location = copy_event_location (location);
9615
9616       if (parse_extra)
9617         b->cond_string = NULL;
9618       else
9619         {
9620           /* Create a private copy of condition string.  */
9621           b->cond_string = cond_string != NULL ? xstrdup (cond_string) : NULL;
9622           b->thread = thread;
9623         }
9624
9625       /* Create a private copy of any extra string.  */
9626       b->extra_string = extra_string != NULL ? xstrdup (extra_string) : NULL;
9627       b->ignore_count = ignore_count;
9628       b->disposition = tempflag ? disp_del : disp_donttouch;
9629       b->condition_not_parsed = 1;
9630       b->enable_state = enabled ? bp_enabled : bp_disabled;
9631       if ((type_wanted != bp_breakpoint
9632            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9633         b->pspace = current_program_space;
9634
9635       install_breakpoint (internal, std::move (b), 0);
9636     }
9637   
9638   if (canonical.lsals.size () > 1)
9639     {
9640       warning (_("Multiple breakpoints were set.\nUse the "
9641                  "\"delete\" command to delete unwanted breakpoints."));
9642       prev_breakpoint_count = prev_bkpt_count;
9643     }
9644
9645   /* That's it.  Discard the cleanups for data inserted into the
9646      breakpoint.  */
9647   discard_cleanups (bkpt_chain);
9648
9649   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9650   update_global_location_list (UGLL_MAY_INSERT);
9651
9652   return 1;
9653 }
9654
9655 /* Set a breakpoint.
9656    ARG is a string describing breakpoint address,
9657    condition, and thread.
9658    FLAG specifies if a breakpoint is hardware on,
9659    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9660    and BP_TEMPFLAG.  */
9661
9662 static void
9663 break_command_1 (const char *arg, int flag, int from_tty)
9664 {
9665   int tempflag = flag & BP_TEMPFLAG;
9666   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9667                              ? bp_hardware_breakpoint
9668                              : bp_breakpoint);
9669   struct breakpoint_ops *ops;
9670
9671   event_location_up location = string_to_event_location (&arg, current_language);
9672
9673   /* Matching breakpoints on probes.  */
9674   if (location != NULL
9675       && event_location_type (location.get ()) == PROBE_LOCATION)
9676     ops = &bkpt_probe_breakpoint_ops;
9677   else
9678     ops = &bkpt_breakpoint_ops;
9679
9680   create_breakpoint (get_current_arch (),
9681                      location.get (),
9682                      NULL, 0, arg, 1 /* parse arg */,
9683                      tempflag, type_wanted,
9684                      0 /* Ignore count */,
9685                      pending_break_support,
9686                      ops,
9687                      from_tty,
9688                      1 /* enabled */,
9689                      0 /* internal */,
9690                      0);
9691 }
9692
9693 /* Helper function for break_command_1 and disassemble_command.  */
9694
9695 void
9696 resolve_sal_pc (struct symtab_and_line *sal)
9697 {
9698   CORE_ADDR pc;
9699
9700   if (sal->pc == 0 && sal->symtab != NULL)
9701     {
9702       if (!find_line_pc (sal->symtab, sal->line, &pc))
9703         error (_("No line %d in file \"%s\"."),
9704                sal->line, symtab_to_filename_for_display (sal->symtab));
9705       sal->pc = pc;
9706
9707       /* If this SAL corresponds to a breakpoint inserted using a line
9708          number, then skip the function prologue if necessary.  */
9709       if (sal->explicit_line)
9710         skip_prologue_sal (sal);
9711     }
9712
9713   if (sal->section == 0 && sal->symtab != NULL)
9714     {
9715       const struct blockvector *bv;
9716       const struct block *b;
9717       struct symbol *sym;
9718
9719       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9720                                     SYMTAB_COMPUNIT (sal->symtab));
9721       if (bv != NULL)
9722         {
9723           sym = block_linkage_function (b);
9724           if (sym != NULL)
9725             {
9726               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9727               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9728                                                  sym);
9729             }
9730           else
9731             {
9732               /* It really is worthwhile to have the section, so we'll
9733                  just have to look harder. This case can be executed
9734                  if we have line numbers but no functions (as can
9735                  happen in assembly source).  */
9736
9737               scoped_restore_current_pspace_and_thread restore_pspace_thread;
9738               switch_to_program_space_and_thread (sal->pspace);
9739
9740               bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9741               if (msym.minsym)
9742                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9743             }
9744         }
9745     }
9746 }
9747
9748 void
9749 break_command (char *arg, int from_tty)
9750 {
9751   break_command_1 (arg, 0, from_tty);
9752 }
9753
9754 void
9755 tbreak_command (char *arg, int from_tty)
9756 {
9757   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9758 }
9759
9760 static void
9761 hbreak_command (char *arg, int from_tty)
9762 {
9763   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9764 }
9765
9766 static void
9767 thbreak_command (char *arg, int from_tty)
9768 {
9769   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9770 }
9771
9772 static void
9773 stop_command (char *arg, int from_tty)
9774 {
9775   printf_filtered (_("Specify the type of breakpoint to set.\n\
9776 Usage: stop in <function | address>\n\
9777        stop at <line>\n"));
9778 }
9779
9780 static void
9781 stopin_command (const char *arg, int from_tty)
9782 {
9783   int badInput = 0;
9784
9785   if (arg == (char *) NULL)
9786     badInput = 1;
9787   else if (*arg != '*')
9788     {
9789       const char *argptr = arg;
9790       int hasColon = 0;
9791
9792       /* Look for a ':'.  If this is a line number specification, then
9793          say it is bad, otherwise, it should be an address or
9794          function/method name.  */
9795       while (*argptr && !hasColon)
9796         {
9797           hasColon = (*argptr == ':');
9798           argptr++;
9799         }
9800
9801       if (hasColon)
9802         badInput = (*argptr != ':');    /* Not a class::method */
9803       else
9804         badInput = isdigit (*arg);      /* a simple line number */
9805     }
9806
9807   if (badInput)
9808     printf_filtered (_("Usage: stop in <function | address>\n"));
9809   else
9810     break_command_1 (arg, 0, from_tty);
9811 }
9812
9813 static void
9814 stopat_command (const char *arg, int from_tty)
9815 {
9816   int badInput = 0;
9817
9818   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9819     badInput = 1;
9820   else
9821     {
9822       const char *argptr = arg;
9823       int hasColon = 0;
9824
9825       /* Look for a ':'.  If there is a '::' then get out, otherwise
9826          it is probably a line number.  */
9827       while (*argptr && !hasColon)
9828         {
9829           hasColon = (*argptr == ':');
9830           argptr++;
9831         }
9832
9833       if (hasColon)
9834         badInput = (*argptr == ':');    /* we have class::method */
9835       else
9836         badInput = !isdigit (*arg);     /* not a line number */
9837     }
9838
9839   if (badInput)
9840     printf_filtered (_("Usage: stop at <line>\n"));
9841   else
9842     break_command_1 (arg, 0, from_tty);
9843 }
9844
9845 /* The dynamic printf command is mostly like a regular breakpoint, but
9846    with a prewired command list consisting of a single output command,
9847    built from extra arguments supplied on the dprintf command
9848    line.  */
9849
9850 static void
9851 dprintf_command (char *arg_in, int from_tty)
9852 {
9853   const char *arg = arg_in;
9854   event_location_up location = string_to_event_location (&arg, current_language);
9855
9856   /* If non-NULL, ARG should have been advanced past the location;
9857      the next character must be ','.  */
9858   if (arg != NULL)
9859     {
9860       if (arg[0] != ',' || arg[1] == '\0')
9861         error (_("Format string required"));
9862       else
9863         {
9864           /* Skip the comma.  */
9865           ++arg;
9866         }
9867     }
9868
9869   create_breakpoint (get_current_arch (),
9870                      location.get (),
9871                      NULL, 0, arg, 1 /* parse arg */,
9872                      0, bp_dprintf,
9873                      0 /* Ignore count */,
9874                      pending_break_support,
9875                      &dprintf_breakpoint_ops,
9876                      from_tty,
9877                      1 /* enabled */,
9878                      0 /* internal */,
9879                      0);
9880 }
9881
9882 static void
9883 agent_printf_command (char *arg, int from_tty)
9884 {
9885   error (_("May only run agent-printf on the target"));
9886 }
9887
9888 /* Implement the "breakpoint_hit" breakpoint_ops method for
9889    ranged breakpoints.  */
9890
9891 static int
9892 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9893                                   struct address_space *aspace,
9894                                   CORE_ADDR bp_addr,
9895                                   const struct target_waitstatus *ws)
9896 {
9897   if (ws->kind != TARGET_WAITKIND_STOPPED
9898       || ws->value.sig != GDB_SIGNAL_TRAP)
9899     return 0;
9900
9901   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9902                                          bl->length, aspace, bp_addr);
9903 }
9904
9905 /* Implement the "resources_needed" breakpoint_ops method for
9906    ranged breakpoints.  */
9907
9908 static int
9909 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9910 {
9911   return target_ranged_break_num_registers ();
9912 }
9913
9914 /* Implement the "print_it" breakpoint_ops method for
9915    ranged breakpoints.  */
9916
9917 static enum print_stop_action
9918 print_it_ranged_breakpoint (bpstat bs)
9919 {
9920   struct breakpoint *b = bs->breakpoint_at;
9921   struct bp_location *bl = b->loc;
9922   struct ui_out *uiout = current_uiout;
9923
9924   gdb_assert (b->type == bp_hardware_breakpoint);
9925
9926   /* Ranged breakpoints have only one location.  */
9927   gdb_assert (bl && bl->next == NULL);
9928
9929   annotate_breakpoint (b->number);
9930
9931   maybe_print_thread_hit_breakpoint (uiout);
9932
9933   if (b->disposition == disp_del)
9934     uiout->text ("Temporary ranged breakpoint ");
9935   else
9936     uiout->text ("Ranged breakpoint ");
9937   if (uiout->is_mi_like_p ())
9938     {
9939       uiout->field_string ("reason",
9940                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9941       uiout->field_string ("disp", bpdisp_text (b->disposition));
9942     }
9943   uiout->field_int ("bkptno", b->number);
9944   uiout->text (", ");
9945
9946   return PRINT_SRC_AND_LOC;
9947 }
9948
9949 /* Implement the "print_one" breakpoint_ops method for
9950    ranged breakpoints.  */
9951
9952 static void
9953 print_one_ranged_breakpoint (struct breakpoint *b,
9954                              struct bp_location **last_loc)
9955 {
9956   struct bp_location *bl = b->loc;
9957   struct value_print_options opts;
9958   struct ui_out *uiout = current_uiout;
9959
9960   /* Ranged breakpoints have only one location.  */
9961   gdb_assert (bl && bl->next == NULL);
9962
9963   get_user_print_options (&opts);
9964
9965   if (opts.addressprint)
9966     /* We don't print the address range here, it will be printed later
9967        by print_one_detail_ranged_breakpoint.  */
9968     uiout->field_skip ("addr");
9969   annotate_field (5);
9970   print_breakpoint_location (b, bl);
9971   *last_loc = bl;
9972 }
9973
9974 /* Implement the "print_one_detail" breakpoint_ops method for
9975    ranged breakpoints.  */
9976
9977 static void
9978 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9979                                     struct ui_out *uiout)
9980 {
9981   CORE_ADDR address_start, address_end;
9982   struct bp_location *bl = b->loc;
9983   string_file stb;
9984
9985   gdb_assert (bl);
9986
9987   address_start = bl->address;
9988   address_end = address_start + bl->length - 1;
9989
9990   uiout->text ("\taddress range: ");
9991   stb.printf ("[%s, %s]",
9992               print_core_address (bl->gdbarch, address_start),
9993               print_core_address (bl->gdbarch, address_end));
9994   uiout->field_stream ("addr", stb);
9995   uiout->text ("\n");
9996 }
9997
9998 /* Implement the "print_mention" breakpoint_ops method for
9999    ranged breakpoints.  */
10000
10001 static void
10002 print_mention_ranged_breakpoint (struct breakpoint *b)
10003 {
10004   struct bp_location *bl = b->loc;
10005   struct ui_out *uiout = current_uiout;
10006
10007   gdb_assert (bl);
10008   gdb_assert (b->type == bp_hardware_breakpoint);
10009
10010   if (uiout->is_mi_like_p ())
10011     return;
10012
10013   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10014                    b->number, paddress (bl->gdbarch, bl->address),
10015                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10016 }
10017
10018 /* Implement the "print_recreate" breakpoint_ops method for
10019    ranged breakpoints.  */
10020
10021 static void
10022 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10023 {
10024   fprintf_unfiltered (fp, "break-range %s, %s",
10025                       event_location_to_string (b->location.get ()),
10026                       event_location_to_string (b->location_range_end.get ()));
10027   print_recreate_thread (b, fp);
10028 }
10029
10030 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10031
10032 static struct breakpoint_ops ranged_breakpoint_ops;
10033
10034 /* Find the address where the end of the breakpoint range should be
10035    placed, given the SAL of the end of the range.  This is so that if
10036    the user provides a line number, the end of the range is set to the
10037    last instruction of the given line.  */
10038
10039 static CORE_ADDR
10040 find_breakpoint_range_end (struct symtab_and_line sal)
10041 {
10042   CORE_ADDR end;
10043
10044   /* If the user provided a PC value, use it.  Otherwise,
10045      find the address of the end of the given location.  */
10046   if (sal.explicit_pc)
10047     end = sal.pc;
10048   else
10049     {
10050       int ret;
10051       CORE_ADDR start;
10052
10053       ret = find_line_pc_range (sal, &start, &end);
10054       if (!ret)
10055         error (_("Could not find location of the end of the range."));
10056
10057       /* find_line_pc_range returns the start of the next line.  */
10058       end--;
10059     }
10060
10061   return end;
10062 }
10063
10064 /* Implement the "break-range" CLI command.  */
10065
10066 static void
10067 break_range_command (char *arg_in, int from_tty)
10068 {
10069   const char *arg = arg_in;
10070   const char *arg_start;
10071   char *addr_string_start;
10072   struct linespec_result canonical_start, canonical_end;
10073   int bp_count, can_use_bp, length;
10074   CORE_ADDR end;
10075   struct breakpoint *b;
10076   struct cleanup *cleanup_bkpt;
10077
10078   /* We don't support software ranged breakpoints.  */
10079   if (target_ranged_break_num_registers () < 0)
10080     error (_("This target does not support hardware ranged breakpoints."));
10081
10082   bp_count = hw_breakpoint_used_count ();
10083   bp_count += target_ranged_break_num_registers ();
10084   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10085                                                    bp_count, 0);
10086   if (can_use_bp < 0)
10087     error (_("Hardware breakpoints used exceeds limit."));
10088
10089   arg = skip_spaces (arg);
10090   if (arg == NULL || arg[0] == '\0')
10091     error(_("No address range specified."));
10092
10093   arg_start = arg;
10094   event_location_up start_location = string_to_event_location (&arg,
10095                                                                current_language);
10096   parse_breakpoint_sals (start_location.get (), &canonical_start);
10097
10098   if (arg[0] != ',')
10099     error (_("Too few arguments."));
10100   else if (canonical_start.lsals.empty ())
10101     error (_("Could not find location of the beginning of the range."));
10102
10103   const linespec_sals &lsal_start = canonical_start.lsals[0];
10104
10105   if (canonical_start.lsals.size () > 1
10106       || lsal_start.sals.size () != 1)
10107     error (_("Cannot create a ranged breakpoint with multiple locations."));
10108
10109   const symtab_and_line &sal_start = lsal_start.sals[0];
10110   addr_string_start = savestring (arg_start, arg - arg_start);
10111   cleanup_bkpt = make_cleanup (xfree, addr_string_start);
10112
10113   arg++;        /* Skip the comma.  */
10114   arg = skip_spaces (arg);
10115
10116   /* Parse the end location.  */
10117
10118   arg_start = arg;
10119
10120   /* We call decode_line_full directly here instead of using
10121      parse_breakpoint_sals because we need to specify the start location's
10122      symtab and line as the default symtab and line for the end of the
10123      range.  This makes it possible to have ranges like "foo.c:27, +14",
10124      where +14 means 14 lines from the start location.  */
10125   event_location_up end_location = string_to_event_location (&arg,
10126                                                              current_language);
10127   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
10128                     sal_start.symtab, sal_start.line,
10129                     &canonical_end, NULL, NULL);
10130
10131   if (canonical_end.lsals.empty ())
10132     error (_("Could not find location of the end of the range."));
10133
10134   const linespec_sals &lsal_end = canonical_end.lsals[0];
10135   if (canonical_end.lsals.size () > 1
10136       || lsal_end.sals.size () != 1)
10137     error (_("Cannot create a ranged breakpoint with multiple locations."));
10138
10139   const symtab_and_line &sal_end = lsal_end.sals[0];
10140
10141   end = find_breakpoint_range_end (sal_end);
10142   if (sal_start.pc > end)
10143     error (_("Invalid address range, end precedes start."));
10144
10145   length = end - sal_start.pc + 1;
10146   if (length < 0)
10147     /* Length overflowed.  */
10148     error (_("Address range too large."));
10149   else if (length == 1)
10150     {
10151       /* This range is simple enough to be handled by
10152          the `hbreak' command.  */
10153       hbreak_command (addr_string_start, 1);
10154
10155       do_cleanups (cleanup_bkpt);
10156
10157       return;
10158     }
10159
10160   /* Now set up the breakpoint.  */
10161   b = set_raw_breakpoint (get_current_arch (), sal_start,
10162                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10163   set_breakpoint_count (breakpoint_count + 1);
10164   b->number = breakpoint_count;
10165   b->disposition = disp_donttouch;
10166   b->location = std::move (start_location);
10167   b->location_range_end = std::move (end_location);
10168   b->loc->length = length;
10169
10170   do_cleanups (cleanup_bkpt);
10171
10172   mention (b);
10173   observer_notify_breakpoint_created (b);
10174   update_global_location_list (UGLL_MAY_INSERT);
10175 }
10176
10177 /*  Return non-zero if EXP is verified as constant.  Returned zero
10178     means EXP is variable.  Also the constant detection may fail for
10179     some constant expressions and in such case still falsely return
10180     zero.  */
10181
10182 static int
10183 watchpoint_exp_is_const (const struct expression *exp)
10184 {
10185   int i = exp->nelts;
10186
10187   while (i > 0)
10188     {
10189       int oplenp, argsp;
10190
10191       /* We are only interested in the descriptor of each element.  */
10192       operator_length (exp, i, &oplenp, &argsp);
10193       i -= oplenp;
10194
10195       switch (exp->elts[i].opcode)
10196         {
10197         case BINOP_ADD:
10198         case BINOP_SUB:
10199         case BINOP_MUL:
10200         case BINOP_DIV:
10201         case BINOP_REM:
10202         case BINOP_MOD:
10203         case BINOP_LSH:
10204         case BINOP_RSH:
10205         case BINOP_LOGICAL_AND:
10206         case BINOP_LOGICAL_OR:
10207         case BINOP_BITWISE_AND:
10208         case BINOP_BITWISE_IOR:
10209         case BINOP_BITWISE_XOR:
10210         case BINOP_EQUAL:
10211         case BINOP_NOTEQUAL:
10212         case BINOP_LESS:
10213         case BINOP_GTR:
10214         case BINOP_LEQ:
10215         case BINOP_GEQ:
10216         case BINOP_REPEAT:
10217         case BINOP_COMMA:
10218         case BINOP_EXP:
10219         case BINOP_MIN:
10220         case BINOP_MAX:
10221         case BINOP_INTDIV:
10222         case BINOP_CONCAT:
10223         case TERNOP_COND:
10224         case TERNOP_SLICE:
10225
10226         case OP_LONG:
10227         case OP_DOUBLE:
10228         case OP_DECFLOAT:
10229         case OP_LAST:
10230         case OP_COMPLEX:
10231         case OP_STRING:
10232         case OP_ARRAY:
10233         case OP_TYPE:
10234         case OP_TYPEOF:
10235         case OP_DECLTYPE:
10236         case OP_TYPEID:
10237         case OP_NAME:
10238         case OP_OBJC_NSSTRING:
10239
10240         case UNOP_NEG:
10241         case UNOP_LOGICAL_NOT:
10242         case UNOP_COMPLEMENT:
10243         case UNOP_ADDR:
10244         case UNOP_HIGH:
10245         case UNOP_CAST:
10246
10247         case UNOP_CAST_TYPE:
10248         case UNOP_REINTERPRET_CAST:
10249         case UNOP_DYNAMIC_CAST:
10250           /* Unary, binary and ternary operators: We have to check
10251              their operands.  If they are constant, then so is the
10252              result of that operation.  For instance, if A and B are
10253              determined to be constants, then so is "A + B".
10254
10255              UNOP_IND is one exception to the rule above, because the
10256              value of *ADDR is not necessarily a constant, even when
10257              ADDR is.  */
10258           break;
10259
10260         case OP_VAR_VALUE:
10261           /* Check whether the associated symbol is a constant.
10262
10263              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10264              possible that a buggy compiler could mark a variable as
10265              constant even when it is not, and TYPE_CONST would return
10266              true in this case, while SYMBOL_CLASS wouldn't.
10267
10268              We also have to check for function symbols because they
10269              are always constant.  */
10270           {
10271             struct symbol *s = exp->elts[i + 2].symbol;
10272
10273             if (SYMBOL_CLASS (s) != LOC_BLOCK
10274                 && SYMBOL_CLASS (s) != LOC_CONST
10275                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10276               return 0;
10277             break;
10278           }
10279
10280         /* The default action is to return 0 because we are using
10281            the optimistic approach here: If we don't know something,
10282            then it is not a constant.  */
10283         default:
10284           return 0;
10285         }
10286     }
10287
10288   return 1;
10289 }
10290
10291 /* Watchpoint destructor.  */
10292
10293 watchpoint::~watchpoint ()
10294 {
10295   xfree (this->exp_string);
10296   xfree (this->exp_string_reparse);
10297   value_free (this->val);
10298 }
10299
10300 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10301
10302 static void
10303 re_set_watchpoint (struct breakpoint *b)
10304 {
10305   struct watchpoint *w = (struct watchpoint *) b;
10306
10307   /* Watchpoint can be either on expression using entirely global
10308      variables, or it can be on local variables.
10309
10310      Watchpoints of the first kind are never auto-deleted, and even
10311      persist across program restarts.  Since they can use variables
10312      from shared libraries, we need to reparse expression as libraries
10313      are loaded and unloaded.
10314
10315      Watchpoints on local variables can also change meaning as result
10316      of solib event.  For example, if a watchpoint uses both a local
10317      and a global variables in expression, it's a local watchpoint,
10318      but unloading of a shared library will make the expression
10319      invalid.  This is not a very common use case, but we still
10320      re-evaluate expression, to avoid surprises to the user.
10321
10322      Note that for local watchpoints, we re-evaluate it only if
10323      watchpoints frame id is still valid.  If it's not, it means the
10324      watchpoint is out of scope and will be deleted soon.  In fact,
10325      I'm not sure we'll ever be called in this case.
10326
10327      If a local watchpoint's frame id is still valid, then
10328      w->exp_valid_block is likewise valid, and we can safely use it.
10329
10330      Don't do anything about disabled watchpoints, since they will be
10331      reevaluated again when enabled.  */
10332   update_watchpoint (w, 1 /* reparse */);
10333 }
10334
10335 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10336
10337 static int
10338 insert_watchpoint (struct bp_location *bl)
10339 {
10340   struct watchpoint *w = (struct watchpoint *) bl->owner;
10341   int length = w->exact ? 1 : bl->length;
10342
10343   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10344                                    w->cond_exp.get ());
10345 }
10346
10347 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10348
10349 static int
10350 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10351 {
10352   struct watchpoint *w = (struct watchpoint *) bl->owner;
10353   int length = w->exact ? 1 : bl->length;
10354
10355   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10356                                    w->cond_exp.get ());
10357 }
10358
10359 static int
10360 breakpoint_hit_watchpoint (const struct bp_location *bl,
10361                            struct address_space *aspace, CORE_ADDR bp_addr,
10362                            const struct target_waitstatus *ws)
10363 {
10364   struct breakpoint *b = bl->owner;
10365   struct watchpoint *w = (struct watchpoint *) b;
10366
10367   /* Continuable hardware watchpoints are treated as non-existent if the
10368      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10369      some data address).  Otherwise gdb won't stop on a break instruction
10370      in the code (not from a breakpoint) when a hardware watchpoint has
10371      been defined.  Also skip watchpoints which we know did not trigger
10372      (did not match the data address).  */
10373   if (is_hardware_watchpoint (b)
10374       && w->watchpoint_triggered == watch_triggered_no)
10375     return 0;
10376
10377   return 1;
10378 }
10379
10380 static void
10381 check_status_watchpoint (bpstat bs)
10382 {
10383   gdb_assert (is_watchpoint (bs->breakpoint_at));
10384
10385   bpstat_check_watchpoint (bs);
10386 }
10387
10388 /* Implement the "resources_needed" breakpoint_ops method for
10389    hardware watchpoints.  */
10390
10391 static int
10392 resources_needed_watchpoint (const struct bp_location *bl)
10393 {
10394   struct watchpoint *w = (struct watchpoint *) bl->owner;
10395   int length = w->exact? 1 : bl->length;
10396
10397   return target_region_ok_for_hw_watchpoint (bl->address, length);
10398 }
10399
10400 /* Implement the "works_in_software_mode" breakpoint_ops method for
10401    hardware watchpoints.  */
10402
10403 static int
10404 works_in_software_mode_watchpoint (const struct breakpoint *b)
10405 {
10406   /* Read and access watchpoints only work with hardware support.  */
10407   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10408 }
10409
10410 static enum print_stop_action
10411 print_it_watchpoint (bpstat bs)
10412 {
10413   struct breakpoint *b;
10414   enum print_stop_action result;
10415   struct watchpoint *w;
10416   struct ui_out *uiout = current_uiout;
10417
10418   gdb_assert (bs->bp_location_at != NULL);
10419
10420   b = bs->breakpoint_at;
10421   w = (struct watchpoint *) b;
10422
10423   annotate_watchpoint (b->number);
10424   maybe_print_thread_hit_breakpoint (uiout);
10425
10426   string_file stb;
10427
10428   gdb::optional<ui_out_emit_tuple> tuple_emitter;
10429   switch (b->type)
10430     {
10431     case bp_watchpoint:
10432     case bp_hardware_watchpoint:
10433       if (uiout->is_mi_like_p ())
10434         uiout->field_string
10435           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10436       mention (b);
10437       tuple_emitter.emplace (uiout, "value");
10438       uiout->text ("\nOld value = ");
10439       watchpoint_value_print (bs->old_val, &stb);
10440       uiout->field_stream ("old", stb);
10441       uiout->text ("\nNew value = ");
10442       watchpoint_value_print (w->val, &stb);
10443       uiout->field_stream ("new", stb);
10444       uiout->text ("\n");
10445       /* More than one watchpoint may have been triggered.  */
10446       result = PRINT_UNKNOWN;
10447       break;
10448
10449     case bp_read_watchpoint:
10450       if (uiout->is_mi_like_p ())
10451         uiout->field_string
10452           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10453       mention (b);
10454       tuple_emitter.emplace (uiout, "value");
10455       uiout->text ("\nValue = ");
10456       watchpoint_value_print (w->val, &stb);
10457       uiout->field_stream ("value", stb);
10458       uiout->text ("\n");
10459       result = PRINT_UNKNOWN;
10460       break;
10461
10462     case bp_access_watchpoint:
10463       if (bs->old_val != NULL)
10464         {
10465           if (uiout->is_mi_like_p ())
10466             uiout->field_string
10467               ("reason",
10468                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10469           mention (b);
10470           tuple_emitter.emplace (uiout, "value");
10471           uiout->text ("\nOld value = ");
10472           watchpoint_value_print (bs->old_val, &stb);
10473           uiout->field_stream ("old", stb);
10474           uiout->text ("\nNew value = ");
10475         }
10476       else
10477         {
10478           mention (b);
10479           if (uiout->is_mi_like_p ())
10480             uiout->field_string
10481               ("reason",
10482                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10483           tuple_emitter.emplace (uiout, "value");
10484           uiout->text ("\nValue = ");
10485         }
10486       watchpoint_value_print (w->val, &stb);
10487       uiout->field_stream ("new", stb);
10488       uiout->text ("\n");
10489       result = PRINT_UNKNOWN;
10490       break;
10491     default:
10492       result = PRINT_UNKNOWN;
10493     }
10494
10495   return result;
10496 }
10497
10498 /* Implement the "print_mention" breakpoint_ops method for hardware
10499    watchpoints.  */
10500
10501 static void
10502 print_mention_watchpoint (struct breakpoint *b)
10503 {
10504   struct watchpoint *w = (struct watchpoint *) b;
10505   struct ui_out *uiout = current_uiout;
10506   const char *tuple_name;
10507
10508   switch (b->type)
10509     {
10510     case bp_watchpoint:
10511       uiout->text ("Watchpoint ");
10512       tuple_name = "wpt";
10513       break;
10514     case bp_hardware_watchpoint:
10515       uiout->text ("Hardware watchpoint ");
10516       tuple_name = "wpt";
10517       break;
10518     case bp_read_watchpoint:
10519       uiout->text ("Hardware read watchpoint ");
10520       tuple_name = "hw-rwpt";
10521       break;
10522     case bp_access_watchpoint:
10523       uiout->text ("Hardware access (read/write) watchpoint ");
10524       tuple_name = "hw-awpt";
10525       break;
10526     default:
10527       internal_error (__FILE__, __LINE__,
10528                       _("Invalid hardware watchpoint type."));
10529     }
10530
10531   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10532   uiout->field_int ("number", b->number);
10533   uiout->text (": ");
10534   uiout->field_string ("exp", w->exp_string);
10535 }
10536
10537 /* Implement the "print_recreate" breakpoint_ops method for
10538    watchpoints.  */
10539
10540 static void
10541 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10542 {
10543   struct watchpoint *w = (struct watchpoint *) b;
10544
10545   switch (b->type)
10546     {
10547     case bp_watchpoint:
10548     case bp_hardware_watchpoint:
10549       fprintf_unfiltered (fp, "watch");
10550       break;
10551     case bp_read_watchpoint:
10552       fprintf_unfiltered (fp, "rwatch");
10553       break;
10554     case bp_access_watchpoint:
10555       fprintf_unfiltered (fp, "awatch");
10556       break;
10557     default:
10558       internal_error (__FILE__, __LINE__,
10559                       _("Invalid watchpoint type."));
10560     }
10561
10562   fprintf_unfiltered (fp, " %s", w->exp_string);
10563   print_recreate_thread (b, fp);
10564 }
10565
10566 /* Implement the "explains_signal" breakpoint_ops method for
10567    watchpoints.  */
10568
10569 static int
10570 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10571 {
10572   /* A software watchpoint cannot cause a signal other than
10573      GDB_SIGNAL_TRAP.  */
10574   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10575     return 0;
10576
10577   return 1;
10578 }
10579
10580 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10581
10582 static struct breakpoint_ops watchpoint_breakpoint_ops;
10583
10584 /* Implement the "insert" breakpoint_ops method for
10585    masked hardware watchpoints.  */
10586
10587 static int
10588 insert_masked_watchpoint (struct bp_location *bl)
10589 {
10590   struct watchpoint *w = (struct watchpoint *) bl->owner;
10591
10592   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10593                                         bl->watchpoint_type);
10594 }
10595
10596 /* Implement the "remove" breakpoint_ops method for
10597    masked hardware watchpoints.  */
10598
10599 static int
10600 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10601 {
10602   struct watchpoint *w = (struct watchpoint *) bl->owner;
10603
10604   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10605                                         bl->watchpoint_type);
10606 }
10607
10608 /* Implement the "resources_needed" breakpoint_ops method for
10609    masked hardware watchpoints.  */
10610
10611 static int
10612 resources_needed_masked_watchpoint (const struct bp_location *bl)
10613 {
10614   struct watchpoint *w = (struct watchpoint *) bl->owner;
10615
10616   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10617 }
10618
10619 /* Implement the "works_in_software_mode" breakpoint_ops method for
10620    masked hardware watchpoints.  */
10621
10622 static int
10623 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10624 {
10625   return 0;
10626 }
10627
10628 /* Implement the "print_it" breakpoint_ops method for
10629    masked hardware watchpoints.  */
10630
10631 static enum print_stop_action
10632 print_it_masked_watchpoint (bpstat bs)
10633 {
10634   struct breakpoint *b = bs->breakpoint_at;
10635   struct ui_out *uiout = current_uiout;
10636
10637   /* Masked watchpoints have only one location.  */
10638   gdb_assert (b->loc && b->loc->next == NULL);
10639
10640   annotate_watchpoint (b->number);
10641   maybe_print_thread_hit_breakpoint (uiout);
10642
10643   switch (b->type)
10644     {
10645     case bp_hardware_watchpoint:
10646       if (uiout->is_mi_like_p ())
10647         uiout->field_string
10648           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10649       break;
10650
10651     case bp_read_watchpoint:
10652       if (uiout->is_mi_like_p ())
10653         uiout->field_string
10654           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10655       break;
10656
10657     case bp_access_watchpoint:
10658       if (uiout->is_mi_like_p ())
10659         uiout->field_string
10660           ("reason",
10661            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10662       break;
10663     default:
10664       internal_error (__FILE__, __LINE__,
10665                       _("Invalid hardware watchpoint type."));
10666     }
10667
10668   mention (b);
10669   uiout->text (_("\n\
10670 Check the underlying instruction at PC for the memory\n\
10671 address and value which triggered this watchpoint.\n"));
10672   uiout->text ("\n");
10673
10674   /* More than one watchpoint may have been triggered.  */
10675   return PRINT_UNKNOWN;
10676 }
10677
10678 /* Implement the "print_one_detail" breakpoint_ops method for
10679    masked hardware watchpoints.  */
10680
10681 static void
10682 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10683                                     struct ui_out *uiout)
10684 {
10685   struct watchpoint *w = (struct watchpoint *) b;
10686
10687   /* Masked watchpoints have only one location.  */
10688   gdb_assert (b->loc && b->loc->next == NULL);
10689
10690   uiout->text ("\tmask ");
10691   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10692   uiout->text ("\n");
10693 }
10694
10695 /* Implement the "print_mention" breakpoint_ops method for
10696    masked hardware watchpoints.  */
10697
10698 static void
10699 print_mention_masked_watchpoint (struct breakpoint *b)
10700 {
10701   struct watchpoint *w = (struct watchpoint *) b;
10702   struct ui_out *uiout = current_uiout;
10703   const char *tuple_name;
10704
10705   switch (b->type)
10706     {
10707     case bp_hardware_watchpoint:
10708       uiout->text ("Masked hardware watchpoint ");
10709       tuple_name = "wpt";
10710       break;
10711     case bp_read_watchpoint:
10712       uiout->text ("Masked hardware read watchpoint ");
10713       tuple_name = "hw-rwpt";
10714       break;
10715     case bp_access_watchpoint:
10716       uiout->text ("Masked hardware access (read/write) watchpoint ");
10717       tuple_name = "hw-awpt";
10718       break;
10719     default:
10720       internal_error (__FILE__, __LINE__,
10721                       _("Invalid hardware watchpoint type."));
10722     }
10723
10724   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10725   uiout->field_int ("number", b->number);
10726   uiout->text (": ");
10727   uiout->field_string ("exp", w->exp_string);
10728 }
10729
10730 /* Implement the "print_recreate" breakpoint_ops method for
10731    masked hardware watchpoints.  */
10732
10733 static void
10734 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10735 {
10736   struct watchpoint *w = (struct watchpoint *) b;
10737   char tmp[40];
10738
10739   switch (b->type)
10740     {
10741     case bp_hardware_watchpoint:
10742       fprintf_unfiltered (fp, "watch");
10743       break;
10744     case bp_read_watchpoint:
10745       fprintf_unfiltered (fp, "rwatch");
10746       break;
10747     case bp_access_watchpoint:
10748       fprintf_unfiltered (fp, "awatch");
10749       break;
10750     default:
10751       internal_error (__FILE__, __LINE__,
10752                       _("Invalid hardware watchpoint type."));
10753     }
10754
10755   sprintf_vma (tmp, w->hw_wp_mask);
10756   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10757   print_recreate_thread (b, fp);
10758 }
10759
10760 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10761
10762 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10763
10764 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10765
10766 static int
10767 is_masked_watchpoint (const struct breakpoint *b)
10768 {
10769   return b->ops == &masked_watchpoint_breakpoint_ops;
10770 }
10771
10772 /* accessflag:  hw_write:  watch write, 
10773                 hw_read:   watch read, 
10774                 hw_access: watch access (read or write) */
10775 static void
10776 watch_command_1 (const char *arg, int accessflag, int from_tty,
10777                  int just_location, int internal)
10778 {
10779   struct breakpoint *scope_breakpoint = NULL;
10780   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10781   struct value *val, *mark, *result;
10782   int saved_bitpos = 0, saved_bitsize = 0;
10783   const char *exp_start = NULL;
10784   const char *exp_end = NULL;
10785   const char *tok, *end_tok;
10786   int toklen = -1;
10787   const char *cond_start = NULL;
10788   const char *cond_end = NULL;
10789   enum bptype bp_type;
10790   int thread = -1;
10791   int pc = 0;
10792   /* Flag to indicate whether we are going to use masks for
10793      the hardware watchpoint.  */
10794   int use_mask = 0;
10795   CORE_ADDR mask = 0;
10796   char *expression;
10797   struct cleanup *back_to;
10798
10799   /* Make sure that we actually have parameters to parse.  */
10800   if (arg != NULL && arg[0] != '\0')
10801     {
10802       const char *value_start;
10803
10804       exp_end = arg + strlen (arg);
10805
10806       /* Look for "parameter value" pairs at the end
10807          of the arguments string.  */
10808       for (tok = exp_end - 1; tok > arg; tok--)
10809         {
10810           /* Skip whitespace at the end of the argument list.  */
10811           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10812             tok--;
10813
10814           /* Find the beginning of the last token.
10815              This is the value of the parameter.  */
10816           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10817             tok--;
10818           value_start = tok + 1;
10819
10820           /* Skip whitespace.  */
10821           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10822             tok--;
10823
10824           end_tok = tok;
10825
10826           /* Find the beginning of the second to last token.
10827              This is the parameter itself.  */
10828           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10829             tok--;
10830           tok++;
10831           toklen = end_tok - tok + 1;
10832
10833           if (toklen == 6 && startswith (tok, "thread"))
10834             {
10835               struct thread_info *thr;
10836               /* At this point we've found a "thread" token, which means
10837                  the user is trying to set a watchpoint that triggers
10838                  only in a specific thread.  */
10839               const char *endp;
10840
10841               if (thread != -1)
10842                 error(_("You can specify only one thread."));
10843
10844               /* Extract the thread ID from the next token.  */
10845               thr = parse_thread_id (value_start, &endp);
10846
10847               /* Check if the user provided a valid thread ID.  */
10848               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10849                 invalid_thread_id_error (value_start);
10850
10851               thread = thr->global_num;
10852             }
10853           else if (toklen == 4 && startswith (tok, "mask"))
10854             {
10855               /* We've found a "mask" token, which means the user wants to
10856                  create a hardware watchpoint that is going to have the mask
10857                  facility.  */
10858               struct value *mask_value, *mark;
10859
10860               if (use_mask)
10861                 error(_("You can specify only one mask."));
10862
10863               use_mask = just_location = 1;
10864
10865               mark = value_mark ();
10866               mask_value = parse_to_comma_and_eval (&value_start);
10867               mask = value_as_address (mask_value);
10868               value_free_to_mark (mark);
10869             }
10870           else
10871             /* We didn't recognize what we found.  We should stop here.  */
10872             break;
10873
10874           /* Truncate the string and get rid of the "parameter value" pair before
10875              the arguments string is parsed by the parse_exp_1 function.  */
10876           exp_end = tok;
10877         }
10878     }
10879   else
10880     exp_end = arg;
10881
10882   /* Parse the rest of the arguments.  From here on out, everything
10883      is in terms of a newly allocated string instead of the original
10884      ARG.  */
10885   innermost_block = NULL;
10886   expression = savestring (arg, exp_end - arg);
10887   back_to = make_cleanup (xfree, expression);
10888   exp_start = arg = expression;
10889   expression_up exp = parse_exp_1 (&arg, 0, 0, 0);
10890   exp_end = arg;
10891   /* Remove trailing whitespace from the expression before saving it.
10892      This makes the eventual display of the expression string a bit
10893      prettier.  */
10894   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10895     --exp_end;
10896
10897   /* Checking if the expression is not constant.  */
10898   if (watchpoint_exp_is_const (exp.get ()))
10899     {
10900       int len;
10901
10902       len = exp_end - exp_start;
10903       while (len > 0 && isspace (exp_start[len - 1]))
10904         len--;
10905       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10906     }
10907
10908   exp_valid_block = innermost_block;
10909   mark = value_mark ();
10910   fetch_subexp_value (exp.get (), &pc, &val, &result, NULL, just_location);
10911
10912   if (val != NULL && just_location)
10913     {
10914       saved_bitpos = value_bitpos (val);
10915       saved_bitsize = value_bitsize (val);
10916     }
10917
10918   if (just_location)
10919     {
10920       int ret;
10921
10922       exp_valid_block = NULL;
10923       val = value_addr (result);
10924       release_value (val);
10925       value_free_to_mark (mark);
10926
10927       if (use_mask)
10928         {
10929           ret = target_masked_watch_num_registers (value_as_address (val),
10930                                                    mask);
10931           if (ret == -1)
10932             error (_("This target does not support masked watchpoints."));
10933           else if (ret == -2)
10934             error (_("Invalid mask or memory region."));
10935         }
10936     }
10937   else if (val != NULL)
10938     release_value (val);
10939
10940   tok = skip_spaces (arg);
10941   end_tok = skip_to_space (tok);
10942
10943   toklen = end_tok - tok;
10944   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10945     {
10946       innermost_block = NULL;
10947       tok = cond_start = end_tok + 1;
10948       parse_exp_1 (&tok, 0, 0, 0);
10949
10950       /* The watchpoint expression may not be local, but the condition
10951          may still be.  E.g.: `watch global if local > 0'.  */
10952       cond_exp_valid_block = innermost_block;
10953
10954       cond_end = tok;
10955     }
10956   if (*tok)
10957     error (_("Junk at end of command."));
10958
10959   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
10960
10961   /* Save this because create_internal_breakpoint below invalidates
10962      'wp_frame'.  */
10963   frame_id watchpoint_frame = get_frame_id (wp_frame);
10964
10965   /* If the expression is "local", then set up a "watchpoint scope"
10966      breakpoint at the point where we've left the scope of the watchpoint
10967      expression.  Create the scope breakpoint before the watchpoint, so
10968      that we will encounter it first in bpstat_stop_status.  */
10969   if (exp_valid_block != NULL && wp_frame != NULL)
10970     {
10971       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10972
10973       if (frame_id_p (caller_frame_id))
10974         {
10975           gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10976           CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10977
10978           scope_breakpoint
10979             = create_internal_breakpoint (caller_arch, caller_pc,
10980                                           bp_watchpoint_scope,
10981                                           &momentary_breakpoint_ops);
10982
10983           /* create_internal_breakpoint could invalidate WP_FRAME.  */
10984           wp_frame = NULL;
10985
10986           scope_breakpoint->enable_state = bp_enabled;
10987
10988           /* Automatically delete the breakpoint when it hits.  */
10989           scope_breakpoint->disposition = disp_del;
10990
10991           /* Only break in the proper frame (help with recursion).  */
10992           scope_breakpoint->frame_id = caller_frame_id;
10993
10994           /* Set the address at which we will stop.  */
10995           scope_breakpoint->loc->gdbarch = caller_arch;
10996           scope_breakpoint->loc->requested_address = caller_pc;
10997           scope_breakpoint->loc->address
10998             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10999                                          scope_breakpoint->loc->requested_address,
11000                                          scope_breakpoint->type);
11001         }
11002     }
11003
11004   /* Now set up the breakpoint.  We create all watchpoints as hardware
11005      watchpoints here even if hardware watchpoints are turned off, a call
11006      to update_watchpoint later in this function will cause the type to
11007      drop back to bp_watchpoint (software watchpoint) if required.  */
11008
11009   if (accessflag == hw_read)
11010     bp_type = bp_read_watchpoint;
11011   else if (accessflag == hw_access)
11012     bp_type = bp_access_watchpoint;
11013   else
11014     bp_type = bp_hardware_watchpoint;
11015
11016   std::unique_ptr<watchpoint> w (new watchpoint ());
11017
11018   if (use_mask)
11019     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
11020                                           &masked_watchpoint_breakpoint_ops);
11021   else
11022     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
11023                                           &watchpoint_breakpoint_ops);
11024   w->thread = thread;
11025   w->disposition = disp_donttouch;
11026   w->pspace = current_program_space;
11027   w->exp = std::move (exp);
11028   w->exp_valid_block = exp_valid_block;
11029   w->cond_exp_valid_block = cond_exp_valid_block;
11030   if (just_location)
11031     {
11032       struct type *t = value_type (val);
11033       CORE_ADDR addr = value_as_address (val);
11034
11035       w->exp_string_reparse
11036         = current_language->la_watch_location_expression (t, addr).release ();
11037
11038       w->exp_string = xstrprintf ("-location %.*s",
11039                                   (int) (exp_end - exp_start), exp_start);
11040     }
11041   else
11042     w->exp_string = savestring (exp_start, exp_end - exp_start);
11043
11044   if (use_mask)
11045     {
11046       w->hw_wp_mask = mask;
11047     }
11048   else
11049     {
11050       w->val = val;
11051       w->val_bitpos = saved_bitpos;
11052       w->val_bitsize = saved_bitsize;
11053       w->val_valid = 1;
11054     }
11055
11056   if (cond_start)
11057     w->cond_string = savestring (cond_start, cond_end - cond_start);
11058   else
11059     w->cond_string = 0;
11060
11061   if (frame_id_p (watchpoint_frame))
11062     {
11063       w->watchpoint_frame = watchpoint_frame;
11064       w->watchpoint_thread = inferior_ptid;
11065     }
11066   else
11067     {
11068       w->watchpoint_frame = null_frame_id;
11069       w->watchpoint_thread = null_ptid;
11070     }
11071
11072   if (scope_breakpoint != NULL)
11073     {
11074       /* The scope breakpoint is related to the watchpoint.  We will
11075          need to act on them together.  */
11076       w->related_breakpoint = scope_breakpoint;
11077       scope_breakpoint->related_breakpoint = w.get ();
11078     }
11079
11080   if (!just_location)
11081     value_free_to_mark (mark);
11082
11083   /* Finally update the new watchpoint.  This creates the locations
11084      that should be inserted.  */
11085   update_watchpoint (w.get (), 1);
11086
11087   install_breakpoint (internal, std::move (w), 1);
11088   do_cleanups (back_to);
11089 }
11090
11091 /* Return count of debug registers needed to watch the given expression.
11092    If the watchpoint cannot be handled in hardware return zero.  */
11093
11094 static int
11095 can_use_hardware_watchpoint (struct value *v)
11096 {
11097   int found_memory_cnt = 0;
11098   struct value *head = v;
11099
11100   /* Did the user specifically forbid us to use hardware watchpoints? */
11101   if (!can_use_hw_watchpoints)
11102     return 0;
11103
11104   /* Make sure that the value of the expression depends only upon
11105      memory contents, and values computed from them within GDB.  If we
11106      find any register references or function calls, we can't use a
11107      hardware watchpoint.
11108
11109      The idea here is that evaluating an expression generates a series
11110      of values, one holding the value of every subexpression.  (The
11111      expression a*b+c has five subexpressions: a, b, a*b, c, and
11112      a*b+c.)  GDB's values hold almost enough information to establish
11113      the criteria given above --- they identify memory lvalues,
11114      register lvalues, computed values, etcetera.  So we can evaluate
11115      the expression, and then scan the chain of values that leaves
11116      behind to decide whether we can detect any possible change to the
11117      expression's final value using only hardware watchpoints.
11118
11119      However, I don't think that the values returned by inferior
11120      function calls are special in any way.  So this function may not
11121      notice that an expression involving an inferior function call
11122      can't be watched with hardware watchpoints.  FIXME.  */
11123   for (; v; v = value_next (v))
11124     {
11125       if (VALUE_LVAL (v) == lval_memory)
11126         {
11127           if (v != head && value_lazy (v))
11128             /* A lazy memory lvalue in the chain is one that GDB never
11129                needed to fetch; we either just used its address (e.g.,
11130                `a' in `a.b') or we never needed it at all (e.g., `a'
11131                in `a,b').  This doesn't apply to HEAD; if that is
11132                lazy then it was not readable, but watch it anyway.  */
11133             ;
11134           else
11135             {
11136               /* Ahh, memory we actually used!  Check if we can cover
11137                  it with hardware watchpoints.  */
11138               struct type *vtype = check_typedef (value_type (v));
11139
11140               /* We only watch structs and arrays if user asked for it
11141                  explicitly, never if they just happen to appear in a
11142                  middle of some value chain.  */
11143               if (v == head
11144                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11145                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11146                 {
11147                   CORE_ADDR vaddr = value_address (v);
11148                   int len;
11149                   int num_regs;
11150
11151                   len = (target_exact_watchpoints
11152                          && is_scalar_type_recursive (vtype))?
11153                     1 : TYPE_LENGTH (value_type (v));
11154
11155                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11156                   if (!num_regs)
11157                     return 0;
11158                   else
11159                     found_memory_cnt += num_regs;
11160                 }
11161             }
11162         }
11163       else if (VALUE_LVAL (v) != not_lval
11164                && deprecated_value_modifiable (v) == 0)
11165         return 0;       /* These are values from the history (e.g., $1).  */
11166       else if (VALUE_LVAL (v) == lval_register)
11167         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11168     }
11169
11170   /* The expression itself looks suitable for using a hardware
11171      watchpoint, but give the target machine a chance to reject it.  */
11172   return found_memory_cnt;
11173 }
11174
11175 void
11176 watch_command_wrapper (const char *arg, int from_tty, int internal)
11177 {
11178   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11179 }
11180
11181 /* A helper function that looks for the "-location" argument and then
11182    calls watch_command_1.  */
11183
11184 static void
11185 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11186 {
11187   int just_location = 0;
11188
11189   if (arg
11190       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11191           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11192     {
11193       arg = skip_spaces (arg);
11194       just_location = 1;
11195     }
11196
11197   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11198 }
11199
11200 static void
11201 watch_command (char *arg, int from_tty)
11202 {
11203   watch_maybe_just_location (arg, hw_write, from_tty);
11204 }
11205
11206 void
11207 rwatch_command_wrapper (const char *arg, int from_tty, int internal)
11208 {
11209   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11210 }
11211
11212 static void
11213 rwatch_command (char *arg, int from_tty)
11214 {
11215   watch_maybe_just_location (arg, hw_read, from_tty);
11216 }
11217
11218 void
11219 awatch_command_wrapper (const char *arg, int from_tty, int internal)
11220 {
11221   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11222 }
11223
11224 static void
11225 awatch_command (char *arg, int from_tty)
11226 {
11227   watch_maybe_just_location (arg, hw_access, from_tty);
11228 }
11229 \f
11230
11231 /* Data for the FSM that manages the until(location)/advance commands
11232    in infcmd.c.  Here because it uses the mechanisms of
11233    breakpoints.  */
11234
11235 struct until_break_fsm
11236 {
11237   /* The base class.  */
11238   struct thread_fsm thread_fsm;
11239
11240   /* The thread that as current when the command was executed.  */
11241   int thread;
11242
11243   /* The breakpoint set at the destination location.  */
11244   struct breakpoint *location_breakpoint;
11245
11246   /* Breakpoint set at the return address in the caller frame.  May be
11247      NULL.  */
11248   struct breakpoint *caller_breakpoint;
11249 };
11250
11251 static void until_break_fsm_clean_up (struct thread_fsm *self,
11252                                       struct thread_info *thread);
11253 static int until_break_fsm_should_stop (struct thread_fsm *self,
11254                                         struct thread_info *thread);
11255 static enum async_reply_reason
11256   until_break_fsm_async_reply_reason (struct thread_fsm *self);
11257
11258 /* until_break_fsm's vtable.  */
11259
11260 static struct thread_fsm_ops until_break_fsm_ops =
11261 {
11262   NULL, /* dtor */
11263   until_break_fsm_clean_up,
11264   until_break_fsm_should_stop,
11265   NULL, /* return_value */
11266   until_break_fsm_async_reply_reason,
11267 };
11268
11269 /* Allocate a new until_break_command_fsm.  */
11270
11271 static struct until_break_fsm *
11272 new_until_break_fsm (struct interp *cmd_interp, int thread,
11273                      struct breakpoint *location_breakpoint,
11274                      struct breakpoint *caller_breakpoint)
11275 {
11276   struct until_break_fsm *sm;
11277
11278   sm = XCNEW (struct until_break_fsm);
11279   thread_fsm_ctor (&sm->thread_fsm, &until_break_fsm_ops, cmd_interp);
11280
11281   sm->thread = thread;
11282   sm->location_breakpoint = location_breakpoint;
11283   sm->caller_breakpoint = caller_breakpoint;
11284
11285   return sm;
11286 }
11287
11288 /* Implementation of the 'should_stop' FSM method for the
11289    until(location)/advance commands.  */
11290
11291 static int
11292 until_break_fsm_should_stop (struct thread_fsm *self,
11293                              struct thread_info *tp)
11294 {
11295   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11296
11297   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11298                               sm->location_breakpoint) != NULL
11299       || (sm->caller_breakpoint != NULL
11300           && bpstat_find_breakpoint (tp->control.stop_bpstat,
11301                                      sm->caller_breakpoint) != NULL))
11302     thread_fsm_set_finished (self);
11303
11304   return 1;
11305 }
11306
11307 /* Implementation of the 'clean_up' FSM method for the
11308    until(location)/advance commands.  */
11309
11310 static void
11311 until_break_fsm_clean_up (struct thread_fsm *self,
11312                           struct thread_info *thread)
11313 {
11314   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11315
11316   /* Clean up our temporary breakpoints.  */
11317   if (sm->location_breakpoint != NULL)
11318     {
11319       delete_breakpoint (sm->location_breakpoint);
11320       sm->location_breakpoint = NULL;
11321     }
11322   if (sm->caller_breakpoint != NULL)
11323     {
11324       delete_breakpoint (sm->caller_breakpoint);
11325       sm->caller_breakpoint = NULL;
11326     }
11327   delete_longjmp_breakpoint (sm->thread);
11328 }
11329
11330 /* Implementation of the 'async_reply_reason' FSM method for the
11331    until(location)/advance commands.  */
11332
11333 static enum async_reply_reason
11334 until_break_fsm_async_reply_reason (struct thread_fsm *self)
11335 {
11336   return EXEC_ASYNC_LOCATION_REACHED;
11337 }
11338
11339 void
11340 until_break_command (const char *arg, int from_tty, int anywhere)
11341 {
11342   struct frame_info *frame;
11343   struct gdbarch *frame_gdbarch;
11344   struct frame_id stack_frame_id;
11345   struct frame_id caller_frame_id;
11346   struct breakpoint *location_breakpoint;
11347   struct breakpoint *caller_breakpoint = NULL;
11348   struct cleanup *old_chain;
11349   int thread;
11350   struct thread_info *tp;
11351   struct until_break_fsm *sm;
11352
11353   clear_proceed_status (0);
11354
11355   /* Set a breakpoint where the user wants it and at return from
11356      this function.  */
11357
11358   event_location_up location = string_to_event_location (&arg, current_language);
11359
11360   std::vector<symtab_and_line> sals
11361     = (last_displayed_sal_is_valid ()
11362        ? decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
11363                         get_last_displayed_symtab (),
11364                         get_last_displayed_line ())
11365        : decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
11366                         NULL, (struct symtab *) NULL, 0));
11367
11368   if (sals.size () != 1)
11369     error (_("Couldn't get information on specified line."));
11370
11371   symtab_and_line &sal = sals[0];
11372
11373   if (*arg)
11374     error (_("Junk at end of arguments."));
11375
11376   resolve_sal_pc (&sal);
11377
11378   tp = inferior_thread ();
11379   thread = tp->global_num;
11380
11381   old_chain = make_cleanup (null_cleanup, NULL);
11382
11383   /* Note linespec handling above invalidates the frame chain.
11384      Installing a breakpoint also invalidates the frame chain (as it
11385      may need to switch threads), so do any frame handling before
11386      that.  */
11387
11388   frame = get_selected_frame (NULL);
11389   frame_gdbarch = get_frame_arch (frame);
11390   stack_frame_id = get_stack_frame_id (frame);
11391   caller_frame_id = frame_unwind_caller_id (frame);
11392
11393   /* Keep within the current frame, or in frames called by the current
11394      one.  */
11395
11396   if (frame_id_p (caller_frame_id))
11397     {
11398       struct symtab_and_line sal2;
11399       struct gdbarch *caller_gdbarch;
11400
11401       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11402       sal2.pc = frame_unwind_caller_pc (frame);
11403       caller_gdbarch = frame_unwind_caller_arch (frame);
11404       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11405                                                     sal2,
11406                                                     caller_frame_id,
11407                                                     bp_until);
11408       make_cleanup_delete_breakpoint (caller_breakpoint);
11409
11410       set_longjmp_breakpoint (tp, caller_frame_id);
11411       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11412     }
11413
11414   /* set_momentary_breakpoint could invalidate FRAME.  */
11415   frame = NULL;
11416
11417   if (anywhere)
11418     /* If the user told us to continue until a specified location,
11419        we don't specify a frame at which we need to stop.  */
11420     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11421                                                     null_frame_id, bp_until);
11422   else
11423     /* Otherwise, specify the selected frame, because we want to stop
11424        only at the very same frame.  */
11425     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11426                                                     stack_frame_id, bp_until);
11427   make_cleanup_delete_breakpoint (location_breakpoint);
11428
11429   sm = new_until_break_fsm (command_interp (), tp->global_num,
11430                             location_breakpoint, caller_breakpoint);
11431   tp->thread_fsm = &sm->thread_fsm;
11432
11433   discard_cleanups (old_chain);
11434
11435   proceed (-1, GDB_SIGNAL_DEFAULT);
11436 }
11437
11438 /* This function attempts to parse an optional "if <cond>" clause
11439    from the arg string.  If one is not found, it returns NULL.
11440
11441    Else, it returns a pointer to the condition string.  (It does not
11442    attempt to evaluate the string against a particular block.)  And,
11443    it updates arg to point to the first character following the parsed
11444    if clause in the arg string.  */
11445
11446 const char *
11447 ep_parse_optional_if_clause (const char **arg)
11448 {
11449   const char *cond_string;
11450
11451   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11452     return NULL;
11453
11454   /* Skip the "if" keyword.  */
11455   (*arg) += 2;
11456
11457   /* Skip any extra leading whitespace, and record the start of the
11458      condition string.  */
11459   *arg = skip_spaces (*arg);
11460   cond_string = *arg;
11461
11462   /* Assume that the condition occupies the remainder of the arg
11463      string.  */
11464   (*arg) += strlen (cond_string);
11465
11466   return cond_string;
11467 }
11468
11469 /* Commands to deal with catching events, such as signals, exceptions,
11470    process start/exit, etc.  */
11471
11472 typedef enum
11473 {
11474   catch_fork_temporary, catch_vfork_temporary,
11475   catch_fork_permanent, catch_vfork_permanent
11476 }
11477 catch_fork_kind;
11478
11479 static void
11480 catch_fork_command_1 (char *arg_entry, int from_tty,
11481                       struct cmd_list_element *command)
11482 {
11483   const char *arg = arg_entry;
11484   struct gdbarch *gdbarch = get_current_arch ();
11485   const char *cond_string = NULL;
11486   catch_fork_kind fork_kind;
11487   int tempflag;
11488
11489   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11490   tempflag = (fork_kind == catch_fork_temporary
11491               || fork_kind == catch_vfork_temporary);
11492
11493   if (!arg)
11494     arg = "";
11495   arg = skip_spaces (arg);
11496
11497   /* The allowed syntax is:
11498      catch [v]fork
11499      catch [v]fork if <cond>
11500
11501      First, check if there's an if clause.  */
11502   cond_string = ep_parse_optional_if_clause (&arg);
11503
11504   if ((*arg != '\0') && !isspace (*arg))
11505     error (_("Junk at end of arguments."));
11506
11507   /* If this target supports it, create a fork or vfork catchpoint
11508      and enable reporting of such events.  */
11509   switch (fork_kind)
11510     {
11511     case catch_fork_temporary:
11512     case catch_fork_permanent:
11513       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11514                                           &catch_fork_breakpoint_ops);
11515       break;
11516     case catch_vfork_temporary:
11517     case catch_vfork_permanent:
11518       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11519                                           &catch_vfork_breakpoint_ops);
11520       break;
11521     default:
11522       error (_("unsupported or unknown fork kind; cannot catch it"));
11523       break;
11524     }
11525 }
11526
11527 static void
11528 catch_exec_command_1 (char *arg_entry, int from_tty,
11529                       struct cmd_list_element *command)
11530 {
11531   const char *arg = arg_entry;
11532   struct gdbarch *gdbarch = get_current_arch ();
11533   int tempflag;
11534   const char *cond_string = NULL;
11535
11536   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11537
11538   if (!arg)
11539     arg = "";
11540   arg = skip_spaces (arg);
11541
11542   /* The allowed syntax is:
11543      catch exec
11544      catch exec if <cond>
11545
11546      First, check if there's an if clause.  */
11547   cond_string = ep_parse_optional_if_clause (&arg);
11548
11549   if ((*arg != '\0') && !isspace (*arg))
11550     error (_("Junk at end of arguments."));
11551
11552   std::unique_ptr<exec_catchpoint> c (new exec_catchpoint ());
11553   init_catchpoint (c.get (), gdbarch, tempflag, cond_string,
11554                    &catch_exec_breakpoint_ops);
11555   c->exec_pathname = NULL;
11556
11557   install_breakpoint (0, std::move (c), 1);
11558 }
11559
11560 void
11561 init_ada_exception_breakpoint (struct breakpoint *b,
11562                                struct gdbarch *gdbarch,
11563                                struct symtab_and_line sal,
11564                                const char *addr_string,
11565                                const struct breakpoint_ops *ops,
11566                                int tempflag,
11567                                int enabled,
11568                                int from_tty)
11569 {
11570   if (from_tty)
11571     {
11572       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11573       if (!loc_gdbarch)
11574         loc_gdbarch = gdbarch;
11575
11576       describe_other_breakpoints (loc_gdbarch,
11577                                   sal.pspace, sal.pc, sal.section, -1);
11578       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11579          version for exception catchpoints, because two catchpoints
11580          used for different exception names will use the same address.
11581          In this case, a "breakpoint ... also set at..." warning is
11582          unproductive.  Besides, the warning phrasing is also a bit
11583          inappropriate, we should use the word catchpoint, and tell
11584          the user what type of catchpoint it is.  The above is good
11585          enough for now, though.  */
11586     }
11587
11588   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11589
11590   b->enable_state = enabled ? bp_enabled : bp_disabled;
11591   b->disposition = tempflag ? disp_del : disp_donttouch;
11592   b->location = string_to_event_location (&addr_string,
11593                                           language_def (language_ada));
11594   b->language = language_ada;
11595 }
11596
11597 static void
11598 catch_command (char *arg, int from_tty)
11599 {
11600   error (_("Catch requires an event name."));
11601 }
11602 \f
11603
11604 static void
11605 tcatch_command (char *arg, int from_tty)
11606 {
11607   error (_("Catch requires an event name."));
11608 }
11609
11610 /* A qsort comparison function that sorts breakpoints in order.  */
11611
11612 static int
11613 compare_breakpoints (const void *a, const void *b)
11614 {
11615   const breakpoint_p *ba = (const breakpoint_p *) a;
11616   uintptr_t ua = (uintptr_t) *ba;
11617   const breakpoint_p *bb = (const breakpoint_p *) b;
11618   uintptr_t ub = (uintptr_t) *bb;
11619
11620   if ((*ba)->number < (*bb)->number)
11621     return -1;
11622   else if ((*ba)->number > (*bb)->number)
11623     return 1;
11624
11625   /* Now sort by address, in case we see, e..g, two breakpoints with
11626      the number 0.  */
11627   if (ua < ub)
11628     return -1;
11629   return ua > ub ? 1 : 0;
11630 }
11631
11632 /* Delete breakpoints by address or line.  */
11633
11634 static void
11635 clear_command (char *arg, int from_tty)
11636 {
11637   struct breakpoint *b, *prev;
11638   VEC(breakpoint_p) *found = 0;
11639   int ix;
11640   int default_match;
11641   int i;
11642   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11643
11644   std::vector<symtab_and_line> decoded_sals;
11645   symtab_and_line last_sal;
11646   gdb::array_view<symtab_and_line> sals;
11647   if (arg)
11648     {
11649       decoded_sals
11650         = decode_line_with_current_source (arg,
11651                                            (DECODE_LINE_FUNFIRSTLINE
11652                                             | DECODE_LINE_LIST_MODE));
11653       default_match = 0;
11654       sals = decoded_sals;
11655     }
11656   else
11657     {
11658       /* Set sal's line, symtab, pc, and pspace to the values
11659          corresponding to the last call to print_frame_info.  If the
11660          codepoint is not valid, this will set all the fields to 0.  */
11661       last_sal = get_last_displayed_sal ();
11662       if (last_sal.symtab == 0)
11663         error (_("No source file specified."));
11664
11665       default_match = 1;
11666       sals = last_sal;
11667     }
11668
11669   /* We don't call resolve_sal_pc here.  That's not as bad as it
11670      seems, because all existing breakpoints typically have both
11671      file/line and pc set.  So, if clear is given file/line, we can
11672      match this to existing breakpoint without obtaining pc at all.
11673
11674      We only support clearing given the address explicitly 
11675      present in breakpoint table.  Say, we've set breakpoint 
11676      at file:line.  There were several PC values for that file:line,
11677      due to optimization, all in one block.
11678
11679      We've picked one PC value.  If "clear" is issued with another
11680      PC corresponding to the same file:line, the breakpoint won't
11681      be cleared.  We probably can still clear the breakpoint, but 
11682      since the other PC value is never presented to user, user
11683      can only find it by guessing, and it does not seem important
11684      to support that.  */
11685
11686   /* For each line spec given, delete bps which correspond to it.  Do
11687      it in two passes, solely to preserve the current behavior that
11688      from_tty is forced true if we delete more than one
11689      breakpoint.  */
11690
11691   found = NULL;
11692   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11693   for (const auto &sal : sals)
11694     {
11695       const char *sal_fullname;
11696
11697       /* If exact pc given, clear bpts at that pc.
11698          If line given (pc == 0), clear all bpts on specified line.
11699          If defaulting, clear all bpts on default line
11700          or at default pc.
11701
11702          defaulting    sal.pc != 0    tests to do
11703
11704          0              1             pc
11705          1              1             pc _and_ line
11706          0              0             line
11707          1              0             <can't happen> */
11708
11709       sal_fullname = (sal.symtab == NULL
11710                       ? NULL : symtab_to_fullname (sal.symtab));
11711
11712       /* Find all matching breakpoints and add them to 'found'.  */
11713       ALL_BREAKPOINTS (b)
11714         {
11715           int match = 0;
11716           /* Are we going to delete b?  */
11717           if (b->type != bp_none && !is_watchpoint (b))
11718             {
11719               struct bp_location *loc = b->loc;
11720               for (; loc; loc = loc->next)
11721                 {
11722                   /* If the user specified file:line, don't allow a PC
11723                      match.  This matches historical gdb behavior.  */
11724                   int pc_match = (!sal.explicit_line
11725                                   && sal.pc
11726                                   && (loc->pspace == sal.pspace)
11727                                   && (loc->address == sal.pc)
11728                                   && (!section_is_overlay (loc->section)
11729                                       || loc->section == sal.section));
11730                   int line_match = 0;
11731
11732                   if ((default_match || sal.explicit_line)
11733                       && loc->symtab != NULL
11734                       && sal_fullname != NULL
11735                       && sal.pspace == loc->pspace
11736                       && loc->line_number == sal.line
11737                       && filename_cmp (symtab_to_fullname (loc->symtab),
11738                                        sal_fullname) == 0)
11739                     line_match = 1;
11740
11741                   if (pc_match || line_match)
11742                     {
11743                       match = 1;
11744                       break;
11745                     }
11746                 }
11747             }
11748
11749           if (match)
11750             VEC_safe_push(breakpoint_p, found, b);
11751         }
11752     }
11753
11754   /* Now go thru the 'found' chain and delete them.  */
11755   if (VEC_empty(breakpoint_p, found))
11756     {
11757       if (arg)
11758         error (_("No breakpoint at %s."), arg);
11759       else
11760         error (_("No breakpoint at this line."));
11761     }
11762
11763   /* Remove duplicates from the vec.  */
11764   qsort (VEC_address (breakpoint_p, found),
11765          VEC_length (breakpoint_p, found),
11766          sizeof (breakpoint_p),
11767          compare_breakpoints);
11768   prev = VEC_index (breakpoint_p, found, 0);
11769   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
11770     {
11771       if (b == prev)
11772         {
11773           VEC_ordered_remove (breakpoint_p, found, ix);
11774           --ix;
11775         }
11776     }
11777
11778   if (VEC_length(breakpoint_p, found) > 1)
11779     from_tty = 1;       /* Always report if deleted more than one.  */
11780   if (from_tty)
11781     {
11782       if (VEC_length(breakpoint_p, found) == 1)
11783         printf_unfiltered (_("Deleted breakpoint "));
11784       else
11785         printf_unfiltered (_("Deleted breakpoints "));
11786     }
11787
11788   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
11789     {
11790       if (from_tty)
11791         printf_unfiltered ("%d ", b->number);
11792       delete_breakpoint (b);
11793     }
11794   if (from_tty)
11795     putchar_unfiltered ('\n');
11796
11797   do_cleanups (cleanups);
11798 }
11799 \f
11800 /* Delete breakpoint in BS if they are `delete' breakpoints and
11801    all breakpoints that are marked for deletion, whether hit or not.
11802    This is called after any breakpoint is hit, or after errors.  */
11803
11804 void
11805 breakpoint_auto_delete (bpstat bs)
11806 {
11807   struct breakpoint *b, *b_tmp;
11808
11809   for (; bs; bs = bs->next)
11810     if (bs->breakpoint_at
11811         && bs->breakpoint_at->disposition == disp_del
11812         && bs->stop)
11813       delete_breakpoint (bs->breakpoint_at);
11814
11815   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11816   {
11817     if (b->disposition == disp_del_at_next_stop)
11818       delete_breakpoint (b);
11819   }
11820 }
11821
11822 /* A comparison function for bp_location AP and BP being interfaced to
11823    qsort.  Sort elements primarily by their ADDRESS (no matter what
11824    does breakpoint_address_is_meaningful say for its OWNER),
11825    secondarily by ordering first permanent elements and
11826    terciarily just ensuring the array is sorted stable way despite
11827    qsort being an unstable algorithm.  */
11828
11829 static int
11830 bp_locations_compare (const void *ap, const void *bp)
11831 {
11832   const struct bp_location *a = *(const struct bp_location **) ap;
11833   const struct bp_location *b = *(const struct bp_location **) bp;
11834
11835   if (a->address != b->address)
11836     return (a->address > b->address) - (a->address < b->address);
11837
11838   /* Sort locations at the same address by their pspace number, keeping
11839      locations of the same inferior (in a multi-inferior environment)
11840      grouped.  */
11841
11842   if (a->pspace->num != b->pspace->num)
11843     return ((a->pspace->num > b->pspace->num)
11844             - (a->pspace->num < b->pspace->num));
11845
11846   /* Sort permanent breakpoints first.  */
11847   if (a->permanent != b->permanent)
11848     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
11849
11850   /* Make the internal GDB representation stable across GDB runs
11851      where A and B memory inside GDB can differ.  Breakpoint locations of
11852      the same type at the same address can be sorted in arbitrary order.  */
11853
11854   if (a->owner->number != b->owner->number)
11855     return ((a->owner->number > b->owner->number)
11856             - (a->owner->number < b->owner->number));
11857
11858   return (a > b) - (a < b);
11859 }
11860
11861 /* Set bp_locations_placed_address_before_address_max and
11862    bp_locations_shadow_len_after_address_max according to the current
11863    content of the bp_locations array.  */
11864
11865 static void
11866 bp_locations_target_extensions_update (void)
11867 {
11868   struct bp_location *bl, **blp_tmp;
11869
11870   bp_locations_placed_address_before_address_max = 0;
11871   bp_locations_shadow_len_after_address_max = 0;
11872
11873   ALL_BP_LOCATIONS (bl, blp_tmp)
11874     {
11875       CORE_ADDR start, end, addr;
11876
11877       if (!bp_location_has_shadow (bl))
11878         continue;
11879
11880       start = bl->target_info.placed_address;
11881       end = start + bl->target_info.shadow_len;
11882
11883       gdb_assert (bl->address >= start);
11884       addr = bl->address - start;
11885       if (addr > bp_locations_placed_address_before_address_max)
11886         bp_locations_placed_address_before_address_max = addr;
11887
11888       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11889
11890       gdb_assert (bl->address < end);
11891       addr = end - bl->address;
11892       if (addr > bp_locations_shadow_len_after_address_max)
11893         bp_locations_shadow_len_after_address_max = addr;
11894     }
11895 }
11896
11897 /* Download tracepoint locations if they haven't been.  */
11898
11899 static void
11900 download_tracepoint_locations (void)
11901 {
11902   struct breakpoint *b;
11903   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11904
11905   scoped_restore_current_pspace_and_thread restore_pspace_thread;
11906
11907   ALL_TRACEPOINTS (b)
11908     {
11909       struct bp_location *bl;
11910       struct tracepoint *t;
11911       int bp_location_downloaded = 0;
11912
11913       if ((b->type == bp_fast_tracepoint
11914            ? !may_insert_fast_tracepoints
11915            : !may_insert_tracepoints))
11916         continue;
11917
11918       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11919         {
11920           if (target_can_download_tracepoint ())
11921             can_download_tracepoint = TRIBOOL_TRUE;
11922           else
11923             can_download_tracepoint = TRIBOOL_FALSE;
11924         }
11925
11926       if (can_download_tracepoint == TRIBOOL_FALSE)
11927         break;
11928
11929       for (bl = b->loc; bl; bl = bl->next)
11930         {
11931           /* In tracepoint, locations are _never_ duplicated, so
11932              should_be_inserted is equivalent to
11933              unduplicated_should_be_inserted.  */
11934           if (!should_be_inserted (bl) || bl->inserted)
11935             continue;
11936
11937           switch_to_program_space_and_thread (bl->pspace);
11938
11939           target_download_tracepoint (bl);
11940
11941           bl->inserted = 1;
11942           bp_location_downloaded = 1;
11943         }
11944       t = (struct tracepoint *) b;
11945       t->number_on_target = b->number;
11946       if (bp_location_downloaded)
11947         observer_notify_breakpoint_modified (b);
11948     }
11949 }
11950
11951 /* Swap the insertion/duplication state between two locations.  */
11952
11953 static void
11954 swap_insertion (struct bp_location *left, struct bp_location *right)
11955 {
11956   const int left_inserted = left->inserted;
11957   const int left_duplicate = left->duplicate;
11958   const int left_needs_update = left->needs_update;
11959   const struct bp_target_info left_target_info = left->target_info;
11960
11961   /* Locations of tracepoints can never be duplicated.  */
11962   if (is_tracepoint (left->owner))
11963     gdb_assert (!left->duplicate);
11964   if (is_tracepoint (right->owner))
11965     gdb_assert (!right->duplicate);
11966
11967   left->inserted = right->inserted;
11968   left->duplicate = right->duplicate;
11969   left->needs_update = right->needs_update;
11970   left->target_info = right->target_info;
11971   right->inserted = left_inserted;
11972   right->duplicate = left_duplicate;
11973   right->needs_update = left_needs_update;
11974   right->target_info = left_target_info;
11975 }
11976
11977 /* Force the re-insertion of the locations at ADDRESS.  This is called
11978    once a new/deleted/modified duplicate location is found and we are evaluating
11979    conditions on the target's side.  Such conditions need to be updated on
11980    the target.  */
11981
11982 static void
11983 force_breakpoint_reinsertion (struct bp_location *bl)
11984 {
11985   struct bp_location **locp = NULL, **loc2p;
11986   struct bp_location *loc;
11987   CORE_ADDR address = 0;
11988   int pspace_num;
11989
11990   address = bl->address;
11991   pspace_num = bl->pspace->num;
11992
11993   /* This is only meaningful if the target is
11994      evaluating conditions and if the user has
11995      opted for condition evaluation on the target's
11996      side.  */
11997   if (gdb_evaluates_breakpoint_condition_p ()
11998       || !target_supports_evaluation_of_breakpoint_conditions ())
11999     return;
12000
12001   /* Flag all breakpoint locations with this address and
12002      the same program space as the location
12003      as "its condition has changed".  We need to
12004      update the conditions on the target's side.  */
12005   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12006     {
12007       loc = *loc2p;
12008
12009       if (!is_breakpoint (loc->owner)
12010           || pspace_num != loc->pspace->num)
12011         continue;
12012
12013       /* Flag the location appropriately.  We use a different state to
12014          let everyone know that we already updated the set of locations
12015          with addr bl->address and program space bl->pspace.  This is so
12016          we don't have to keep calling these functions just to mark locations
12017          that have already been marked.  */
12018       loc->condition_changed = condition_updated;
12019
12020       /* Free the agent expression bytecode as well.  We will compute
12021          it later on.  */
12022       loc->cond_bytecode.reset ();
12023     }
12024 }
12025 /* Called whether new breakpoints are created, or existing breakpoints
12026    deleted, to update the global location list and recompute which
12027    locations are duplicate of which.
12028
12029    The INSERT_MODE flag determines whether locations may not, may, or
12030    shall be inserted now.  See 'enum ugll_insert_mode' for more
12031    info.  */
12032
12033 static void
12034 update_global_location_list (enum ugll_insert_mode insert_mode)
12035 {
12036   struct breakpoint *b;
12037   struct bp_location **locp, *loc;
12038   struct cleanup *cleanups;
12039   /* Last breakpoint location address that was marked for update.  */
12040   CORE_ADDR last_addr = 0;
12041   /* Last breakpoint location program space that was marked for update.  */
12042   int last_pspace_num = -1;
12043
12044   /* Used in the duplicates detection below.  When iterating over all
12045      bp_locations, points to the first bp_location of a given address.
12046      Breakpoints and watchpoints of different types are never
12047      duplicates of each other.  Keep one pointer for each type of
12048      breakpoint/watchpoint, so we only need to loop over all locations
12049      once.  */
12050   struct bp_location *bp_loc_first;  /* breakpoint */
12051   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12052   struct bp_location *awp_loc_first; /* access watchpoint */
12053   struct bp_location *rwp_loc_first; /* read watchpoint */
12054
12055   /* Saved former bp_locations array which we compare against the newly
12056      built bp_locations from the current state of ALL_BREAKPOINTS.  */
12057   struct bp_location **old_locations, **old_locp;
12058   unsigned old_locations_count;
12059
12060   old_locations = bp_locations;
12061   old_locations_count = bp_locations_count;
12062   bp_locations = NULL;
12063   bp_locations_count = 0;
12064   cleanups = make_cleanup (xfree, old_locations);
12065
12066   ALL_BREAKPOINTS (b)
12067     for (loc = b->loc; loc; loc = loc->next)
12068       bp_locations_count++;
12069
12070   bp_locations = XNEWVEC (struct bp_location *, bp_locations_count);
12071   locp = bp_locations;
12072   ALL_BREAKPOINTS (b)
12073     for (loc = b->loc; loc; loc = loc->next)
12074       *locp++ = loc;
12075   qsort (bp_locations, bp_locations_count, sizeof (*bp_locations),
12076          bp_locations_compare);
12077
12078   bp_locations_target_extensions_update ();
12079
12080   /* Identify bp_location instances that are no longer present in the
12081      new list, and therefore should be freed.  Note that it's not
12082      necessary that those locations should be removed from inferior --
12083      if there's another location at the same address (previously
12084      marked as duplicate), we don't need to remove/insert the
12085      location.
12086      
12087      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12088      and former bp_location array state respectively.  */
12089
12090   locp = bp_locations;
12091   for (old_locp = old_locations;
12092        old_locp < old_locations + old_locations_count;
12093        old_locp++)
12094     {
12095       struct bp_location *old_loc = *old_locp;
12096       struct bp_location **loc2p;
12097
12098       /* Tells if 'old_loc' is found among the new locations.  If
12099          not, we have to free it.  */
12100       int found_object = 0;
12101       /* Tells if the location should remain inserted in the target.  */
12102       int keep_in_target = 0;
12103       int removed = 0;
12104
12105       /* Skip LOCP entries which will definitely never be needed.
12106          Stop either at or being the one matching OLD_LOC.  */
12107       while (locp < bp_locations + bp_locations_count
12108              && (*locp)->address < old_loc->address)
12109         locp++;
12110
12111       for (loc2p = locp;
12112            (loc2p < bp_locations + bp_locations_count
12113             && (*loc2p)->address == old_loc->address);
12114            loc2p++)
12115         {
12116           /* Check if this is a new/duplicated location or a duplicated
12117              location that had its condition modified.  If so, we want to send
12118              its condition to the target if evaluation of conditions is taking
12119              place there.  */
12120           if ((*loc2p)->condition_changed == condition_modified
12121               && (last_addr != old_loc->address
12122                   || last_pspace_num != old_loc->pspace->num))
12123             {
12124               force_breakpoint_reinsertion (*loc2p);
12125               last_pspace_num = old_loc->pspace->num;
12126             }
12127
12128           if (*loc2p == old_loc)
12129             found_object = 1;
12130         }
12131
12132       /* We have already handled this address, update it so that we don't
12133          have to go through updates again.  */
12134       last_addr = old_loc->address;
12135
12136       /* Target-side condition evaluation: Handle deleted locations.  */
12137       if (!found_object)
12138         force_breakpoint_reinsertion (old_loc);
12139
12140       /* If this location is no longer present, and inserted, look if
12141          there's maybe a new location at the same address.  If so,
12142          mark that one inserted, and don't remove this one.  This is
12143          needed so that we don't have a time window where a breakpoint
12144          at certain location is not inserted.  */
12145
12146       if (old_loc->inserted)
12147         {
12148           /* If the location is inserted now, we might have to remove
12149              it.  */
12150
12151           if (found_object && should_be_inserted (old_loc))
12152             {
12153               /* The location is still present in the location list,
12154                  and still should be inserted.  Don't do anything.  */
12155               keep_in_target = 1;
12156             }
12157           else
12158             {
12159               /* This location still exists, but it won't be kept in the
12160                  target since it may have been disabled.  We proceed to
12161                  remove its target-side condition.  */
12162
12163               /* The location is either no longer present, or got
12164                  disabled.  See if there's another location at the
12165                  same address, in which case we don't need to remove
12166                  this one from the target.  */
12167
12168               /* OLD_LOC comes from existing struct breakpoint.  */
12169               if (breakpoint_address_is_meaningful (old_loc->owner))
12170                 {
12171                   for (loc2p = locp;
12172                        (loc2p < bp_locations + bp_locations_count
12173                         && (*loc2p)->address == old_loc->address);
12174                        loc2p++)
12175                     {
12176                       struct bp_location *loc2 = *loc2p;
12177
12178                       if (breakpoint_locations_match (loc2, old_loc))
12179                         {
12180                           /* Read watchpoint locations are switched to
12181                              access watchpoints, if the former are not
12182                              supported, but the latter are.  */
12183                           if (is_hardware_watchpoint (old_loc->owner))
12184                             {
12185                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12186                               loc2->watchpoint_type = old_loc->watchpoint_type;
12187                             }
12188
12189                           /* loc2 is a duplicated location. We need to check
12190                              if it should be inserted in case it will be
12191                              unduplicated.  */
12192                           if (loc2 != old_loc
12193                               && unduplicated_should_be_inserted (loc2))
12194                             {
12195                               swap_insertion (old_loc, loc2);
12196                               keep_in_target = 1;
12197                               break;
12198                             }
12199                         }
12200                     }
12201                 }
12202             }
12203
12204           if (!keep_in_target)
12205             {
12206               if (remove_breakpoint (old_loc))
12207                 {
12208                   /* This is just about all we can do.  We could keep
12209                      this location on the global list, and try to
12210                      remove it next time, but there's no particular
12211                      reason why we will succeed next time.
12212                      
12213                      Note that at this point, old_loc->owner is still
12214                      valid, as delete_breakpoint frees the breakpoint
12215                      only after calling us.  */
12216                   printf_filtered (_("warning: Error removing "
12217                                      "breakpoint %d\n"), 
12218                                    old_loc->owner->number);
12219                 }
12220               removed = 1;
12221             }
12222         }
12223
12224       if (!found_object)
12225         {
12226           if (removed && target_is_non_stop_p ()
12227               && need_moribund_for_location_type (old_loc))
12228             {
12229               /* This location was removed from the target.  In
12230                  non-stop mode, a race condition is possible where
12231                  we've removed a breakpoint, but stop events for that
12232                  breakpoint are already queued and will arrive later.
12233                  We apply an heuristic to be able to distinguish such
12234                  SIGTRAPs from other random SIGTRAPs: we keep this
12235                  breakpoint location for a bit, and will retire it
12236                  after we see some number of events.  The theory here
12237                  is that reporting of events should, "on the average",
12238                  be fair, so after a while we'll see events from all
12239                  threads that have anything of interest, and no longer
12240                  need to keep this breakpoint location around.  We
12241                  don't hold locations forever so to reduce chances of
12242                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12243                  SIGTRAP.
12244
12245                  The heuristic failing can be disastrous on
12246                  decr_pc_after_break targets.
12247
12248                  On decr_pc_after_break targets, like e.g., x86-linux,
12249                  if we fail to recognize a late breakpoint SIGTRAP,
12250                  because events_till_retirement has reached 0 too
12251                  soon, we'll fail to do the PC adjustment, and report
12252                  a random SIGTRAP to the user.  When the user resumes
12253                  the inferior, it will most likely immediately crash
12254                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12255                  corrupted, because of being resumed e.g., in the
12256                  middle of a multi-byte instruction, or skipped a
12257                  one-byte instruction.  This was actually seen happen
12258                  on native x86-linux, and should be less rare on
12259                  targets that do not support new thread events, like
12260                  remote, due to the heuristic depending on
12261                  thread_count.
12262
12263                  Mistaking a random SIGTRAP for a breakpoint trap
12264                  causes similar symptoms (PC adjustment applied when
12265                  it shouldn't), but then again, playing with SIGTRAPs
12266                  behind the debugger's back is asking for trouble.
12267
12268                  Since hardware watchpoint traps are always
12269                  distinguishable from other traps, so we don't need to
12270                  apply keep hardware watchpoint moribund locations
12271                  around.  We simply always ignore hardware watchpoint
12272                  traps we can no longer explain.  */
12273
12274               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12275               old_loc->owner = NULL;
12276
12277               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12278             }
12279           else
12280             {
12281               old_loc->owner = NULL;
12282               decref_bp_location (&old_loc);
12283             }
12284         }
12285     }
12286
12287   /* Rescan breakpoints at the same address and section, marking the
12288      first one as "first" and any others as "duplicates".  This is so
12289      that the bpt instruction is only inserted once.  If we have a
12290      permanent breakpoint at the same place as BPT, make that one the
12291      official one, and the rest as duplicates.  Permanent breakpoints
12292      are sorted first for the same address.
12293
12294      Do the same for hardware watchpoints, but also considering the
12295      watchpoint's type (regular/access/read) and length.  */
12296
12297   bp_loc_first = NULL;
12298   wp_loc_first = NULL;
12299   awp_loc_first = NULL;
12300   rwp_loc_first = NULL;
12301   ALL_BP_LOCATIONS (loc, locp)
12302     {
12303       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12304          non-NULL.  */
12305       struct bp_location **loc_first_p;
12306       b = loc->owner;
12307
12308       if (!unduplicated_should_be_inserted (loc)
12309           || !breakpoint_address_is_meaningful (b)
12310           /* Don't detect duplicate for tracepoint locations because they are
12311            never duplicated.  See the comments in field `duplicate' of
12312            `struct bp_location'.  */
12313           || is_tracepoint (b))
12314         {
12315           /* Clear the condition modification flag.  */
12316           loc->condition_changed = condition_unchanged;
12317           continue;
12318         }
12319
12320       if (b->type == bp_hardware_watchpoint)
12321         loc_first_p = &wp_loc_first;
12322       else if (b->type == bp_read_watchpoint)
12323         loc_first_p = &rwp_loc_first;
12324       else if (b->type == bp_access_watchpoint)
12325         loc_first_p = &awp_loc_first;
12326       else
12327         loc_first_p = &bp_loc_first;
12328
12329       if (*loc_first_p == NULL
12330           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12331           || !breakpoint_locations_match (loc, *loc_first_p))
12332         {
12333           *loc_first_p = loc;
12334           loc->duplicate = 0;
12335
12336           if (is_breakpoint (loc->owner) && loc->condition_changed)
12337             {
12338               loc->needs_update = 1;
12339               /* Clear the condition modification flag.  */
12340               loc->condition_changed = condition_unchanged;
12341             }
12342           continue;
12343         }
12344
12345
12346       /* This and the above ensure the invariant that the first location
12347          is not duplicated, and is the inserted one.
12348          All following are marked as duplicated, and are not inserted.  */
12349       if (loc->inserted)
12350         swap_insertion (loc, *loc_first_p);
12351       loc->duplicate = 1;
12352
12353       /* Clear the condition modification flag.  */
12354       loc->condition_changed = condition_unchanged;
12355     }
12356
12357   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12358     {
12359       if (insert_mode != UGLL_DONT_INSERT)
12360         insert_breakpoint_locations ();
12361       else
12362         {
12363           /* Even though the caller told us to not insert new
12364              locations, we may still need to update conditions on the
12365              target's side of breakpoints that were already inserted
12366              if the target is evaluating breakpoint conditions.  We
12367              only update conditions for locations that are marked
12368              "needs_update".  */
12369           update_inserted_breakpoint_locations ();
12370         }
12371     }
12372
12373   if (insert_mode != UGLL_DONT_INSERT)
12374     download_tracepoint_locations ();
12375
12376   do_cleanups (cleanups);
12377 }
12378
12379 void
12380 breakpoint_retire_moribund (void)
12381 {
12382   struct bp_location *loc;
12383   int ix;
12384
12385   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12386     if (--(loc->events_till_retirement) == 0)
12387       {
12388         decref_bp_location (&loc);
12389         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12390         --ix;
12391       }
12392 }
12393
12394 static void
12395 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12396 {
12397
12398   TRY
12399     {
12400       update_global_location_list (insert_mode);
12401     }
12402   CATCH (e, RETURN_MASK_ERROR)
12403     {
12404     }
12405   END_CATCH
12406 }
12407
12408 /* Clear BKP from a BPS.  */
12409
12410 static void
12411 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12412 {
12413   bpstat bs;
12414
12415   for (bs = bps; bs; bs = bs->next)
12416     if (bs->breakpoint_at == bpt)
12417       {
12418         bs->breakpoint_at = NULL;
12419         bs->old_val = NULL;
12420         /* bs->commands will be freed later.  */
12421       }
12422 }
12423
12424 /* Callback for iterate_over_threads.  */
12425 static int
12426 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12427 {
12428   struct breakpoint *bpt = (struct breakpoint *) data;
12429
12430   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12431   return 0;
12432 }
12433
12434 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12435    callbacks.  */
12436
12437 static void
12438 say_where (struct breakpoint *b)
12439 {
12440   struct value_print_options opts;
12441
12442   get_user_print_options (&opts);
12443
12444   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12445      single string.  */
12446   if (b->loc == NULL)
12447     {
12448       /* For pending locations, the output differs slightly based
12449          on b->extra_string.  If this is non-NULL, it contains either
12450          a condition or dprintf arguments.  */
12451       if (b->extra_string == NULL)
12452         {
12453           printf_filtered (_(" (%s) pending."),
12454                            event_location_to_string (b->location.get ()));
12455         }
12456       else if (b->type == bp_dprintf)
12457         {
12458           printf_filtered (_(" (%s,%s) pending."),
12459                            event_location_to_string (b->location.get ()),
12460                            b->extra_string);
12461         }
12462       else
12463         {
12464           printf_filtered (_(" (%s %s) pending."),
12465                            event_location_to_string (b->location.get ()),
12466                            b->extra_string);
12467         }
12468     }
12469   else
12470     {
12471       if (opts.addressprint || b->loc->symtab == NULL)
12472         {
12473           printf_filtered (" at ");
12474           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12475                           gdb_stdout);
12476         }
12477       if (b->loc->symtab != NULL)
12478         {
12479           /* If there is a single location, we can print the location
12480              more nicely.  */
12481           if (b->loc->next == NULL)
12482             printf_filtered (": file %s, line %d.",
12483                              symtab_to_filename_for_display (b->loc->symtab),
12484                              b->loc->line_number);
12485           else
12486             /* This is not ideal, but each location may have a
12487                different file name, and this at least reflects the
12488                real situation somewhat.  */
12489             printf_filtered (": %s.",
12490                              event_location_to_string (b->location.get ()));
12491         }
12492
12493       if (b->loc->next)
12494         {
12495           struct bp_location *loc = b->loc;
12496           int n = 0;
12497           for (; loc; loc = loc->next)
12498             ++n;
12499           printf_filtered (" (%d locations)", n);
12500         }
12501     }
12502 }
12503
12504 /* Default bp_location_ops methods.  */
12505
12506 static void
12507 bp_location_dtor (struct bp_location *self)
12508 {
12509   xfree (self->function_name);
12510 }
12511
12512 static const struct bp_location_ops bp_location_ops =
12513 {
12514   bp_location_dtor
12515 };
12516
12517 /* Destructor for the breakpoint base class.  */
12518
12519 breakpoint::~breakpoint ()
12520 {
12521   xfree (this->cond_string);
12522   xfree (this->extra_string);
12523   xfree (this->filter);
12524 }
12525
12526 static struct bp_location *
12527 base_breakpoint_allocate_location (struct breakpoint *self)
12528 {
12529   return new bp_location (&bp_location_ops, self);
12530 }
12531
12532 static void
12533 base_breakpoint_re_set (struct breakpoint *b)
12534 {
12535   /* Nothing to re-set. */
12536 }
12537
12538 #define internal_error_pure_virtual_called() \
12539   gdb_assert_not_reached ("pure virtual function called")
12540
12541 static int
12542 base_breakpoint_insert_location (struct bp_location *bl)
12543 {
12544   internal_error_pure_virtual_called ();
12545 }
12546
12547 static int
12548 base_breakpoint_remove_location (struct bp_location *bl,
12549                                  enum remove_bp_reason reason)
12550 {
12551   internal_error_pure_virtual_called ();
12552 }
12553
12554 static int
12555 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12556                                 struct address_space *aspace,
12557                                 CORE_ADDR bp_addr,
12558                                 const struct target_waitstatus *ws)
12559 {
12560   internal_error_pure_virtual_called ();
12561 }
12562
12563 static void
12564 base_breakpoint_check_status (bpstat bs)
12565 {
12566   /* Always stop.   */
12567 }
12568
12569 /* A "works_in_software_mode" breakpoint_ops method that just internal
12570    errors.  */
12571
12572 static int
12573 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12574 {
12575   internal_error_pure_virtual_called ();
12576 }
12577
12578 /* A "resources_needed" breakpoint_ops method that just internal
12579    errors.  */
12580
12581 static int
12582 base_breakpoint_resources_needed (const struct bp_location *bl)
12583 {
12584   internal_error_pure_virtual_called ();
12585 }
12586
12587 static enum print_stop_action
12588 base_breakpoint_print_it (bpstat bs)
12589 {
12590   internal_error_pure_virtual_called ();
12591 }
12592
12593 static void
12594 base_breakpoint_print_one_detail (const struct breakpoint *self,
12595                                   struct ui_out *uiout)
12596 {
12597   /* nothing */
12598 }
12599
12600 static void
12601 base_breakpoint_print_mention (struct breakpoint *b)
12602 {
12603   internal_error_pure_virtual_called ();
12604 }
12605
12606 static void
12607 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12608 {
12609   internal_error_pure_virtual_called ();
12610 }
12611
12612 static void
12613 base_breakpoint_create_sals_from_location
12614   (const struct event_location *location,
12615    struct linespec_result *canonical,
12616    enum bptype type_wanted)
12617 {
12618   internal_error_pure_virtual_called ();
12619 }
12620
12621 static void
12622 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12623                                         struct linespec_result *c,
12624                                         gdb::unique_xmalloc_ptr<char> cond_string,
12625                                         gdb::unique_xmalloc_ptr<char> extra_string,
12626                                         enum bptype type_wanted,
12627                                         enum bpdisp disposition,
12628                                         int thread,
12629                                         int task, int ignore_count,
12630                                         const struct breakpoint_ops *o,
12631                                         int from_tty, int enabled,
12632                                         int internal, unsigned flags)
12633 {
12634   internal_error_pure_virtual_called ();
12635 }
12636
12637 static std::vector<symtab_and_line>
12638 base_breakpoint_decode_location (struct breakpoint *b,
12639                                  const struct event_location *location,
12640                                  struct program_space *search_pspace)
12641 {
12642   internal_error_pure_virtual_called ();
12643 }
12644
12645 /* The default 'explains_signal' method.  */
12646
12647 static int
12648 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12649 {
12650   return 1;
12651 }
12652
12653 /* The default "after_condition_true" method.  */
12654
12655 static void
12656 base_breakpoint_after_condition_true (struct bpstats *bs)
12657 {
12658   /* Nothing to do.   */
12659 }
12660
12661 struct breakpoint_ops base_breakpoint_ops =
12662 {
12663   base_breakpoint_allocate_location,
12664   base_breakpoint_re_set,
12665   base_breakpoint_insert_location,
12666   base_breakpoint_remove_location,
12667   base_breakpoint_breakpoint_hit,
12668   base_breakpoint_check_status,
12669   base_breakpoint_resources_needed,
12670   base_breakpoint_works_in_software_mode,
12671   base_breakpoint_print_it,
12672   NULL,
12673   base_breakpoint_print_one_detail,
12674   base_breakpoint_print_mention,
12675   base_breakpoint_print_recreate,
12676   base_breakpoint_create_sals_from_location,
12677   base_breakpoint_create_breakpoints_sal,
12678   base_breakpoint_decode_location,
12679   base_breakpoint_explains_signal,
12680   base_breakpoint_after_condition_true,
12681 };
12682
12683 /* Default breakpoint_ops methods.  */
12684
12685 static void
12686 bkpt_re_set (struct breakpoint *b)
12687 {
12688   /* FIXME: is this still reachable?  */
12689   if (breakpoint_event_location_empty_p (b))
12690     {
12691       /* Anything without a location can't be re-set.  */
12692       delete_breakpoint (b);
12693       return;
12694     }
12695
12696   breakpoint_re_set_default (b);
12697 }
12698
12699 static int
12700 bkpt_insert_location (struct bp_location *bl)
12701 {
12702   CORE_ADDR addr = bl->target_info.reqstd_address;
12703
12704   bl->target_info.kind = breakpoint_kind (bl, &addr);
12705   bl->target_info.placed_address = addr;
12706
12707   if (bl->loc_type == bp_loc_hardware_breakpoint)
12708     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12709   else
12710     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12711 }
12712
12713 static int
12714 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
12715 {
12716   if (bl->loc_type == bp_loc_hardware_breakpoint)
12717     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12718   else
12719     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12720 }
12721
12722 static int
12723 bkpt_breakpoint_hit (const struct bp_location *bl,
12724                      struct address_space *aspace, CORE_ADDR bp_addr,
12725                      const struct target_waitstatus *ws)
12726 {
12727   if (ws->kind != TARGET_WAITKIND_STOPPED
12728       || ws->value.sig != GDB_SIGNAL_TRAP)
12729     return 0;
12730
12731   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12732                                  aspace, bp_addr))
12733     return 0;
12734
12735   if (overlay_debugging         /* unmapped overlay section */
12736       && section_is_overlay (bl->section)
12737       && !section_is_mapped (bl->section))
12738     return 0;
12739
12740   return 1;
12741 }
12742
12743 static int
12744 dprintf_breakpoint_hit (const struct bp_location *bl,
12745                         struct address_space *aspace, CORE_ADDR bp_addr,
12746                         const struct target_waitstatus *ws)
12747 {
12748   if (dprintf_style == dprintf_style_agent
12749       && target_can_run_breakpoint_commands ())
12750     {
12751       /* An agent-style dprintf never causes a stop.  If we see a trap
12752          for this address it must be for a breakpoint that happens to
12753          be set at the same address.  */
12754       return 0;
12755     }
12756
12757   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12758 }
12759
12760 static int
12761 bkpt_resources_needed (const struct bp_location *bl)
12762 {
12763   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12764
12765   return 1;
12766 }
12767
12768 static enum print_stop_action
12769 bkpt_print_it (bpstat bs)
12770 {
12771   struct breakpoint *b;
12772   const struct bp_location *bl;
12773   int bp_temp;
12774   struct ui_out *uiout = current_uiout;
12775
12776   gdb_assert (bs->bp_location_at != NULL);
12777
12778   bl = bs->bp_location_at;
12779   b = bs->breakpoint_at;
12780
12781   bp_temp = b->disposition == disp_del;
12782   if (bl->address != bl->requested_address)
12783     breakpoint_adjustment_warning (bl->requested_address,
12784                                    bl->address,
12785                                    b->number, 1);
12786   annotate_breakpoint (b->number);
12787   maybe_print_thread_hit_breakpoint (uiout);
12788
12789   if (bp_temp)
12790     uiout->text ("Temporary breakpoint ");
12791   else
12792     uiout->text ("Breakpoint ");
12793   if (uiout->is_mi_like_p ())
12794     {
12795       uiout->field_string ("reason",
12796                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12797       uiout->field_string ("disp", bpdisp_text (b->disposition));
12798     }
12799   uiout->field_int ("bkptno", b->number);
12800   uiout->text (", ");
12801
12802   return PRINT_SRC_AND_LOC;
12803 }
12804
12805 static void
12806 bkpt_print_mention (struct breakpoint *b)
12807 {
12808   if (current_uiout->is_mi_like_p ())
12809     return;
12810
12811   switch (b->type)
12812     {
12813     case bp_breakpoint:
12814     case bp_gnu_ifunc_resolver:
12815       if (b->disposition == disp_del)
12816         printf_filtered (_("Temporary breakpoint"));
12817       else
12818         printf_filtered (_("Breakpoint"));
12819       printf_filtered (_(" %d"), b->number);
12820       if (b->type == bp_gnu_ifunc_resolver)
12821         printf_filtered (_(" at gnu-indirect-function resolver"));
12822       break;
12823     case bp_hardware_breakpoint:
12824       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12825       break;
12826     case bp_dprintf:
12827       printf_filtered (_("Dprintf %d"), b->number);
12828       break;
12829     }
12830
12831   say_where (b);
12832 }
12833
12834 static void
12835 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12836 {
12837   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12838     fprintf_unfiltered (fp, "tbreak");
12839   else if (tp->type == bp_breakpoint)
12840     fprintf_unfiltered (fp, "break");
12841   else if (tp->type == bp_hardware_breakpoint
12842            && tp->disposition == disp_del)
12843     fprintf_unfiltered (fp, "thbreak");
12844   else if (tp->type == bp_hardware_breakpoint)
12845     fprintf_unfiltered (fp, "hbreak");
12846   else
12847     internal_error (__FILE__, __LINE__,
12848                     _("unhandled breakpoint type %d"), (int) tp->type);
12849
12850   fprintf_unfiltered (fp, " %s",
12851                       event_location_to_string (tp->location.get ()));
12852
12853   /* Print out extra_string if this breakpoint is pending.  It might
12854      contain, for example, conditions that were set by the user.  */
12855   if (tp->loc == NULL && tp->extra_string != NULL)
12856     fprintf_unfiltered (fp, " %s", tp->extra_string);
12857
12858   print_recreate_thread (tp, fp);
12859 }
12860
12861 static void
12862 bkpt_create_sals_from_location (const struct event_location *location,
12863                                 struct linespec_result *canonical,
12864                                 enum bptype type_wanted)
12865 {
12866   create_sals_from_location_default (location, canonical, type_wanted);
12867 }
12868
12869 static void
12870 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12871                              struct linespec_result *canonical,
12872                              gdb::unique_xmalloc_ptr<char> cond_string,
12873                              gdb::unique_xmalloc_ptr<char> extra_string,
12874                              enum bptype type_wanted,
12875                              enum bpdisp disposition,
12876                              int thread,
12877                              int task, int ignore_count,
12878                              const struct breakpoint_ops *ops,
12879                              int from_tty, int enabled,
12880                              int internal, unsigned flags)
12881 {
12882   create_breakpoints_sal_default (gdbarch, canonical,
12883                                   std::move (cond_string),
12884                                   std::move (extra_string),
12885                                   type_wanted,
12886                                   disposition, thread, task,
12887                                   ignore_count, ops, from_tty,
12888                                   enabled, internal, flags);
12889 }
12890
12891 static std::vector<symtab_and_line>
12892 bkpt_decode_location (struct breakpoint *b,
12893                       const struct event_location *location,
12894                       struct program_space *search_pspace)
12895 {
12896   return decode_location_default (b, location, search_pspace);
12897 }
12898
12899 /* Virtual table for internal breakpoints.  */
12900
12901 static void
12902 internal_bkpt_re_set (struct breakpoint *b)
12903 {
12904   switch (b->type)
12905     {
12906       /* Delete overlay event and longjmp master breakpoints; they
12907          will be reset later by breakpoint_re_set.  */
12908     case bp_overlay_event:
12909     case bp_longjmp_master:
12910     case bp_std_terminate_master:
12911     case bp_exception_master:
12912       delete_breakpoint (b);
12913       break;
12914
12915       /* This breakpoint is special, it's set up when the inferior
12916          starts and we really don't want to touch it.  */
12917     case bp_shlib_event:
12918
12919       /* Like bp_shlib_event, this breakpoint type is special.  Once
12920          it is set up, we do not want to touch it.  */
12921     case bp_thread_event:
12922       break;
12923     }
12924 }
12925
12926 static void
12927 internal_bkpt_check_status (bpstat bs)
12928 {
12929   if (bs->breakpoint_at->type == bp_shlib_event)
12930     {
12931       /* If requested, stop when the dynamic linker notifies GDB of
12932          events.  This allows the user to get control and place
12933          breakpoints in initializer routines for dynamically loaded
12934          objects (among other things).  */
12935       bs->stop = stop_on_solib_events;
12936       bs->print = stop_on_solib_events;
12937     }
12938   else
12939     bs->stop = 0;
12940 }
12941
12942 static enum print_stop_action
12943 internal_bkpt_print_it (bpstat bs)
12944 {
12945   struct breakpoint *b;
12946
12947   b = bs->breakpoint_at;
12948
12949   switch (b->type)
12950     {
12951     case bp_shlib_event:
12952       /* Did we stop because the user set the stop_on_solib_events
12953          variable?  (If so, we report this as a generic, "Stopped due
12954          to shlib event" message.) */
12955       print_solib_event (0);
12956       break;
12957
12958     case bp_thread_event:
12959       /* Not sure how we will get here.
12960          GDB should not stop for these breakpoints.  */
12961       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12962       break;
12963
12964     case bp_overlay_event:
12965       /* By analogy with the thread event, GDB should not stop for these.  */
12966       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12967       break;
12968
12969     case bp_longjmp_master:
12970       /* These should never be enabled.  */
12971       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12972       break;
12973
12974     case bp_std_terminate_master:
12975       /* These should never be enabled.  */
12976       printf_filtered (_("std::terminate Master Breakpoint: "
12977                          "gdb should not stop!\n"));
12978       break;
12979
12980     case bp_exception_master:
12981       /* These should never be enabled.  */
12982       printf_filtered (_("Exception Master Breakpoint: "
12983                          "gdb should not stop!\n"));
12984       break;
12985     }
12986
12987   return PRINT_NOTHING;
12988 }
12989
12990 static void
12991 internal_bkpt_print_mention (struct breakpoint *b)
12992 {
12993   /* Nothing to mention.  These breakpoints are internal.  */
12994 }
12995
12996 /* Virtual table for momentary breakpoints  */
12997
12998 static void
12999 momentary_bkpt_re_set (struct breakpoint *b)
13000 {
13001   /* Keep temporary breakpoints, which can be encountered when we step
13002      over a dlopen call and solib_add is resetting the breakpoints.
13003      Otherwise these should have been blown away via the cleanup chain
13004      or by breakpoint_init_inferior when we rerun the executable.  */
13005 }
13006
13007 static void
13008 momentary_bkpt_check_status (bpstat bs)
13009 {
13010   /* Nothing.  The point of these breakpoints is causing a stop.  */
13011 }
13012
13013 static enum print_stop_action
13014 momentary_bkpt_print_it (bpstat bs)
13015 {
13016   return PRINT_UNKNOWN;
13017 }
13018
13019 static void
13020 momentary_bkpt_print_mention (struct breakpoint *b)
13021 {
13022   /* Nothing to mention.  These breakpoints are internal.  */
13023 }
13024
13025 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13026
13027    It gets cleared already on the removal of the first one of such placed
13028    breakpoints.  This is OK as they get all removed altogether.  */
13029
13030 longjmp_breakpoint::~longjmp_breakpoint ()
13031 {
13032   thread_info *tp = find_thread_global_id (this->thread);
13033
13034   if (tp != NULL)
13035     tp->initiating_frame = null_frame_id;
13036 }
13037
13038 /* Specific methods for probe breakpoints.  */
13039
13040 static int
13041 bkpt_probe_insert_location (struct bp_location *bl)
13042 {
13043   int v = bkpt_insert_location (bl);
13044
13045   if (v == 0)
13046     {
13047       /* The insertion was successful, now let's set the probe's semaphore
13048          if needed.  */
13049       if (bl->probe.probe->pops->set_semaphore != NULL)
13050         bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13051                                               bl->probe.objfile,
13052                                               bl->gdbarch);
13053     }
13054
13055   return v;
13056 }
13057
13058 static int
13059 bkpt_probe_remove_location (struct bp_location *bl,
13060                             enum remove_bp_reason reason)
13061 {
13062   /* Let's clear the semaphore before removing the location.  */
13063   if (bl->probe.probe->pops->clear_semaphore != NULL)
13064     bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13065                                             bl->probe.objfile,
13066                                             bl->gdbarch);
13067
13068   return bkpt_remove_location (bl, reason);
13069 }
13070
13071 static void
13072 bkpt_probe_create_sals_from_location (const struct event_location *location,
13073                                       struct linespec_result *canonical,
13074                                       enum bptype type_wanted)
13075 {
13076   struct linespec_sals lsal;
13077
13078   lsal.sals = parse_probes (location, NULL, canonical);
13079   lsal.canonical
13080     = xstrdup (event_location_to_string (canonical->location.get ()));
13081   canonical->lsals.push_back (std::move (lsal));
13082 }
13083
13084 static std::vector<symtab_and_line>
13085 bkpt_probe_decode_location (struct breakpoint *b,
13086                             const struct event_location *location,
13087                             struct program_space *search_pspace)
13088 {
13089   std::vector<symtab_and_line> sals = parse_probes (location, search_pspace, NULL);
13090   if (sals.empty ())
13091     error (_("probe not found"));
13092   return sals;
13093 }
13094
13095 /* The breakpoint_ops structure to be used in tracepoints.  */
13096
13097 static void
13098 tracepoint_re_set (struct breakpoint *b)
13099 {
13100   breakpoint_re_set_default (b);
13101 }
13102
13103 static int
13104 tracepoint_breakpoint_hit (const struct bp_location *bl,
13105                            struct address_space *aspace, CORE_ADDR bp_addr,
13106                            const struct target_waitstatus *ws)
13107 {
13108   /* By definition, the inferior does not report stops at
13109      tracepoints.  */
13110   return 0;
13111 }
13112
13113 static void
13114 tracepoint_print_one_detail (const struct breakpoint *self,
13115                              struct ui_out *uiout)
13116 {
13117   struct tracepoint *tp = (struct tracepoint *) self;
13118   if (tp->static_trace_marker_id)
13119     {
13120       gdb_assert (self->type == bp_static_tracepoint);
13121
13122       uiout->text ("\tmarker id is ");
13123       uiout->field_string ("static-tracepoint-marker-string-id",
13124                            tp->static_trace_marker_id);
13125       uiout->text ("\n");
13126     }
13127 }
13128
13129 static void
13130 tracepoint_print_mention (struct breakpoint *b)
13131 {
13132   if (current_uiout->is_mi_like_p ())
13133     return;
13134
13135   switch (b->type)
13136     {
13137     case bp_tracepoint:
13138       printf_filtered (_("Tracepoint"));
13139       printf_filtered (_(" %d"), b->number);
13140       break;
13141     case bp_fast_tracepoint:
13142       printf_filtered (_("Fast tracepoint"));
13143       printf_filtered (_(" %d"), b->number);
13144       break;
13145     case bp_static_tracepoint:
13146       printf_filtered (_("Static tracepoint"));
13147       printf_filtered (_(" %d"), b->number);
13148       break;
13149     default:
13150       internal_error (__FILE__, __LINE__,
13151                       _("unhandled tracepoint type %d"), (int) b->type);
13152     }
13153
13154   say_where (b);
13155 }
13156
13157 static void
13158 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13159 {
13160   struct tracepoint *tp = (struct tracepoint *) self;
13161
13162   if (self->type == bp_fast_tracepoint)
13163     fprintf_unfiltered (fp, "ftrace");
13164   else if (self->type == bp_static_tracepoint)
13165     fprintf_unfiltered (fp, "strace");
13166   else if (self->type == bp_tracepoint)
13167     fprintf_unfiltered (fp, "trace");
13168   else
13169     internal_error (__FILE__, __LINE__,
13170                     _("unhandled tracepoint type %d"), (int) self->type);
13171
13172   fprintf_unfiltered (fp, " %s",
13173                       event_location_to_string (self->location.get ()));
13174   print_recreate_thread (self, fp);
13175
13176   if (tp->pass_count)
13177     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13178 }
13179
13180 static void
13181 tracepoint_create_sals_from_location (const struct event_location *location,
13182                                       struct linespec_result *canonical,
13183                                       enum bptype type_wanted)
13184 {
13185   create_sals_from_location_default (location, canonical, type_wanted);
13186 }
13187
13188 static void
13189 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13190                                    struct linespec_result *canonical,
13191                                    gdb::unique_xmalloc_ptr<char> cond_string,
13192                                    gdb::unique_xmalloc_ptr<char> extra_string,
13193                                    enum bptype type_wanted,
13194                                    enum bpdisp disposition,
13195                                    int thread,
13196                                    int task, int ignore_count,
13197                                    const struct breakpoint_ops *ops,
13198                                    int from_tty, int enabled,
13199                                    int internal, unsigned flags)
13200 {
13201   create_breakpoints_sal_default (gdbarch, canonical,
13202                                   std::move (cond_string),
13203                                   std::move (extra_string),
13204                                   type_wanted,
13205                                   disposition, thread, task,
13206                                   ignore_count, ops, from_tty,
13207                                   enabled, internal, flags);
13208 }
13209
13210 static std::vector<symtab_and_line>
13211 tracepoint_decode_location (struct breakpoint *b,
13212                             const struct event_location *location,
13213                             struct program_space *search_pspace)
13214 {
13215   return decode_location_default (b, location, search_pspace);
13216 }
13217
13218 struct breakpoint_ops tracepoint_breakpoint_ops;
13219
13220 /* The breakpoint_ops structure to be use on tracepoints placed in a
13221    static probe.  */
13222
13223 static void
13224 tracepoint_probe_create_sals_from_location
13225   (const struct event_location *location,
13226    struct linespec_result *canonical,
13227    enum bptype type_wanted)
13228 {
13229   /* We use the same method for breakpoint on probes.  */
13230   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
13231 }
13232
13233 static std::vector<symtab_and_line>
13234 tracepoint_probe_decode_location (struct breakpoint *b,
13235                                   const struct event_location *location,
13236                                   struct program_space *search_pspace)
13237 {
13238   /* We use the same method for breakpoint on probes.  */
13239   return bkpt_probe_decode_location (b, location, search_pspace);
13240 }
13241
13242 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13243
13244 /* Dprintf breakpoint_ops methods.  */
13245
13246 static void
13247 dprintf_re_set (struct breakpoint *b)
13248 {
13249   breakpoint_re_set_default (b);
13250
13251   /* extra_string should never be non-NULL for dprintf.  */
13252   gdb_assert (b->extra_string != NULL);
13253
13254   /* 1 - connect to target 1, that can run breakpoint commands.
13255      2 - create a dprintf, which resolves fine.
13256      3 - disconnect from target 1
13257      4 - connect to target 2, that can NOT run breakpoint commands.
13258
13259      After steps #3/#4, you'll want the dprintf command list to
13260      be updated, because target 1 and 2 may well return different
13261      answers for target_can_run_breakpoint_commands().
13262      Given absence of finer grained resetting, we get to do
13263      it all the time.  */
13264   if (b->extra_string != NULL)
13265     update_dprintf_command_list (b);
13266 }
13267
13268 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13269
13270 static void
13271 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13272 {
13273   fprintf_unfiltered (fp, "dprintf %s,%s",
13274                       event_location_to_string (tp->location.get ()),
13275                       tp->extra_string);
13276   print_recreate_thread (tp, fp);
13277 }
13278
13279 /* Implement the "after_condition_true" breakpoint_ops method for
13280    dprintf.
13281
13282    dprintf's are implemented with regular commands in their command
13283    list, but we run the commands here instead of before presenting the
13284    stop to the user, as dprintf's don't actually cause a stop.  This
13285    also makes it so that the commands of multiple dprintfs at the same
13286    address are all handled.  */
13287
13288 static void
13289 dprintf_after_condition_true (struct bpstats *bs)
13290 {
13291   struct bpstats tmp_bs;
13292   struct bpstats *tmp_bs_p = &tmp_bs;
13293
13294   /* dprintf's never cause a stop.  This wasn't set in the
13295      check_status hook instead because that would make the dprintf's
13296      condition not be evaluated.  */
13297   bs->stop = 0;
13298
13299   /* Run the command list here.  Take ownership of it instead of
13300      copying.  We never want these commands to run later in
13301      bpstat_do_actions, if a breakpoint that causes a stop happens to
13302      be set at same address as this dprintf, or even if running the
13303      commands here throws.  */
13304   tmp_bs.commands = bs->commands;
13305   bs->commands = NULL;
13306
13307   bpstat_do_actions_1 (&tmp_bs_p);
13308
13309   /* 'tmp_bs.commands' will usually be NULL by now, but
13310      bpstat_do_actions_1 may return early without processing the whole
13311      list.  */
13312 }
13313
13314 /* The breakpoint_ops structure to be used on static tracepoints with
13315    markers (`-m').  */
13316
13317 static void
13318 strace_marker_create_sals_from_location (const struct event_location *location,
13319                                          struct linespec_result *canonical,
13320                                          enum bptype type_wanted)
13321 {
13322   struct linespec_sals lsal;
13323   const char *arg_start, *arg;
13324
13325   arg = arg_start = get_linespec_location (location);
13326   lsal.sals = decode_static_tracepoint_spec (&arg);
13327
13328   std::string str (arg_start, arg - arg_start);
13329   const char *ptr = str.c_str ();
13330   canonical->location = new_linespec_location (&ptr);
13331
13332   lsal.canonical
13333     = xstrdup (event_location_to_string (canonical->location.get ()));
13334   canonical->lsals.push_back (std::move (lsal));
13335 }
13336
13337 static void
13338 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13339                                       struct linespec_result *canonical,
13340                                       gdb::unique_xmalloc_ptr<char> cond_string,
13341                                       gdb::unique_xmalloc_ptr<char> extra_string,
13342                                       enum bptype type_wanted,
13343                                       enum bpdisp disposition,
13344                                       int thread,
13345                                       int task, int ignore_count,
13346                                       const struct breakpoint_ops *ops,
13347                                       int from_tty, int enabled,
13348                                       int internal, unsigned flags)
13349 {
13350   const linespec_sals &lsal = canonical->lsals[0];
13351
13352   /* If the user is creating a static tracepoint by marker id
13353      (strace -m MARKER_ID), then store the sals index, so that
13354      breakpoint_re_set can try to match up which of the newly
13355      found markers corresponds to this one, and, don't try to
13356      expand multiple locations for each sal, given than SALS
13357      already should contain all sals for MARKER_ID.  */
13358
13359   for (size_t i = 0; i < lsal.sals.size (); i++)
13360     {
13361       event_location_up location
13362         = copy_event_location (canonical->location.get ());
13363
13364       std::unique_ptr<tracepoint> tp (new tracepoint ());
13365       init_breakpoint_sal (tp.get (), gdbarch, lsal.sals[i],
13366                            std::move (location), NULL,
13367                            std::move (cond_string),
13368                            std::move (extra_string),
13369                            type_wanted, disposition,
13370                            thread, task, ignore_count, ops,
13371                            from_tty, enabled, internal, flags,
13372                            canonical->special_display);
13373       /* Given that its possible to have multiple markers with
13374          the same string id, if the user is creating a static
13375          tracepoint by marker id ("strace -m MARKER_ID"), then
13376          store the sals index, so that breakpoint_re_set can
13377          try to match up which of the newly found markers
13378          corresponds to this one  */
13379       tp->static_trace_marker_id_idx = i;
13380
13381       install_breakpoint (internal, std::move (tp), 0);
13382     }
13383 }
13384
13385 static std::vector<symtab_and_line>
13386 strace_marker_decode_location (struct breakpoint *b,
13387                                const struct event_location *location,
13388                                struct program_space *search_pspace)
13389 {
13390   struct tracepoint *tp = (struct tracepoint *) b;
13391   const char *s = get_linespec_location (location);
13392
13393   std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
13394   if (sals.size () > tp->static_trace_marker_id_idx)
13395     {
13396       sals[0] = sals[tp->static_trace_marker_id_idx];
13397       sals.resize (1);
13398       return sals;
13399     }
13400   else
13401     error (_("marker %s not found"), tp->static_trace_marker_id);
13402 }
13403
13404 static struct breakpoint_ops strace_marker_breakpoint_ops;
13405
13406 static int
13407 strace_marker_p (struct breakpoint *b)
13408 {
13409   return b->ops == &strace_marker_breakpoint_ops;
13410 }
13411
13412 /* Delete a breakpoint and clean up all traces of it in the data
13413    structures.  */
13414
13415 void
13416 delete_breakpoint (struct breakpoint *bpt)
13417 {
13418   struct breakpoint *b;
13419
13420   gdb_assert (bpt != NULL);
13421
13422   /* Has this bp already been deleted?  This can happen because
13423      multiple lists can hold pointers to bp's.  bpstat lists are
13424      especial culprits.
13425
13426      One example of this happening is a watchpoint's scope bp.  When
13427      the scope bp triggers, we notice that the watchpoint is out of
13428      scope, and delete it.  We also delete its scope bp.  But the
13429      scope bp is marked "auto-deleting", and is already on a bpstat.
13430      That bpstat is then checked for auto-deleting bp's, which are
13431      deleted.
13432
13433      A real solution to this problem might involve reference counts in
13434      bp's, and/or giving them pointers back to their referencing
13435      bpstat's, and teaching delete_breakpoint to only free a bp's
13436      storage when no more references were extent.  A cheaper bandaid
13437      was chosen.  */
13438   if (bpt->type == bp_none)
13439     return;
13440
13441   /* At least avoid this stale reference until the reference counting
13442      of breakpoints gets resolved.  */
13443   if (bpt->related_breakpoint != bpt)
13444     {
13445       struct breakpoint *related;
13446       struct watchpoint *w;
13447
13448       if (bpt->type == bp_watchpoint_scope)
13449         w = (struct watchpoint *) bpt->related_breakpoint;
13450       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13451         w = (struct watchpoint *) bpt;
13452       else
13453         w = NULL;
13454       if (w != NULL)
13455         watchpoint_del_at_next_stop (w);
13456
13457       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13458       for (related = bpt; related->related_breakpoint != bpt;
13459            related = related->related_breakpoint);
13460       related->related_breakpoint = bpt->related_breakpoint;
13461       bpt->related_breakpoint = bpt;
13462     }
13463
13464   /* watch_command_1 creates a watchpoint but only sets its number if
13465      update_watchpoint succeeds in creating its bp_locations.  If there's
13466      a problem in that process, we'll be asked to delete the half-created
13467      watchpoint.  In that case, don't announce the deletion.  */
13468   if (bpt->number)
13469     observer_notify_breakpoint_deleted (bpt);
13470
13471   if (breakpoint_chain == bpt)
13472     breakpoint_chain = bpt->next;
13473
13474   ALL_BREAKPOINTS (b)
13475     if (b->next == bpt)
13476     {
13477       b->next = bpt->next;
13478       break;
13479     }
13480
13481   /* Be sure no bpstat's are pointing at the breakpoint after it's
13482      been freed.  */
13483   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13484      in all threads for now.  Note that we cannot just remove bpstats
13485      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13486      commands are associated with the bpstat; if we remove it here,
13487      then the later call to bpstat_do_actions (&stop_bpstat); in
13488      event-top.c won't do anything, and temporary breakpoints with
13489      commands won't work.  */
13490
13491   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13492
13493   /* Now that breakpoint is removed from breakpoint list, update the
13494      global location list.  This will remove locations that used to
13495      belong to this breakpoint.  Do this before freeing the breakpoint
13496      itself, since remove_breakpoint looks at location's owner.  It
13497      might be better design to have location completely
13498      self-contained, but it's not the case now.  */
13499   update_global_location_list (UGLL_DONT_INSERT);
13500
13501   /* On the chance that someone will soon try again to delete this
13502      same bp, we mark it as deleted before freeing its storage.  */
13503   bpt->type = bp_none;
13504   delete bpt;
13505 }
13506
13507 static void
13508 do_delete_breakpoint_cleanup (void *b)
13509 {
13510   delete_breakpoint ((struct breakpoint *) b);
13511 }
13512
13513 struct cleanup *
13514 make_cleanup_delete_breakpoint (struct breakpoint *b)
13515 {
13516   return make_cleanup (do_delete_breakpoint_cleanup, b);
13517 }
13518
13519 /* Iterator function to call a user-provided callback function once
13520    for each of B and its related breakpoints.  */
13521
13522 static void
13523 iterate_over_related_breakpoints (struct breakpoint *b,
13524                                   gdb::function_view<void (breakpoint *)> function)
13525 {
13526   struct breakpoint *related;
13527
13528   related = b;
13529   do
13530     {
13531       struct breakpoint *next;
13532
13533       /* FUNCTION may delete RELATED.  */
13534       next = related->related_breakpoint;
13535
13536       if (next == related)
13537         {
13538           /* RELATED is the last ring entry.  */
13539           function (related);
13540
13541           /* FUNCTION may have deleted it, so we'd never reach back to
13542              B.  There's nothing left to do anyway, so just break
13543              out.  */
13544           break;
13545         }
13546       else
13547         function (related);
13548
13549       related = next;
13550     }
13551   while (related != b);
13552 }
13553
13554 static void
13555 delete_command (char *arg, int from_tty)
13556 {
13557   struct breakpoint *b, *b_tmp;
13558
13559   dont_repeat ();
13560
13561   if (arg == 0)
13562     {
13563       int breaks_to_delete = 0;
13564
13565       /* Delete all breakpoints if no argument.  Do not delete
13566          internal breakpoints, these have to be deleted with an
13567          explicit breakpoint number argument.  */
13568       ALL_BREAKPOINTS (b)
13569         if (user_breakpoint_p (b))
13570           {
13571             breaks_to_delete = 1;
13572             break;
13573           }
13574
13575       /* Ask user only if there are some breakpoints to delete.  */
13576       if (!from_tty
13577           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13578         {
13579           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13580             if (user_breakpoint_p (b))
13581               delete_breakpoint (b);
13582         }
13583     }
13584   else
13585     map_breakpoint_numbers
13586       (arg, [&] (breakpoint *b)
13587        {
13588          iterate_over_related_breakpoints (b, delete_breakpoint);
13589        });
13590 }
13591
13592 /* Return true if all locations of B bound to PSPACE are pending.  If
13593    PSPACE is NULL, all locations of all program spaces are
13594    considered.  */
13595
13596 static int
13597 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13598 {
13599   struct bp_location *loc;
13600
13601   for (loc = b->loc; loc != NULL; loc = loc->next)
13602     if ((pspace == NULL
13603          || loc->pspace == pspace)
13604         && !loc->shlib_disabled
13605         && !loc->pspace->executing_startup)
13606       return 0;
13607   return 1;
13608 }
13609
13610 /* Subroutine of update_breakpoint_locations to simplify it.
13611    Return non-zero if multiple fns in list LOC have the same name.
13612    Null names are ignored.  */
13613
13614 static int
13615 ambiguous_names_p (struct bp_location *loc)
13616 {
13617   struct bp_location *l;
13618   htab_t htab = htab_create_alloc (13, htab_hash_string,
13619                                    (int (*) (const void *, 
13620                                              const void *)) streq,
13621                                    NULL, xcalloc, xfree);
13622
13623   for (l = loc; l != NULL; l = l->next)
13624     {
13625       const char **slot;
13626       const char *name = l->function_name;
13627
13628       /* Allow for some names to be NULL, ignore them.  */
13629       if (name == NULL)
13630         continue;
13631
13632       slot = (const char **) htab_find_slot (htab, (const void *) name,
13633                                              INSERT);
13634       /* NOTE: We can assume slot != NULL here because xcalloc never
13635          returns NULL.  */
13636       if (*slot != NULL)
13637         {
13638           htab_delete (htab);
13639           return 1;
13640         }
13641       *slot = name;
13642     }
13643
13644   htab_delete (htab);
13645   return 0;
13646 }
13647
13648 /* When symbols change, it probably means the sources changed as well,
13649    and it might mean the static tracepoint markers are no longer at
13650    the same address or line numbers they used to be at last we
13651    checked.  Losing your static tracepoints whenever you rebuild is
13652    undesirable.  This function tries to resync/rematch gdb static
13653    tracepoints with the markers on the target, for static tracepoints
13654    that have not been set by marker id.  Static tracepoint that have
13655    been set by marker id are reset by marker id in breakpoint_re_set.
13656    The heuristic is:
13657
13658    1) For a tracepoint set at a specific address, look for a marker at
13659    the old PC.  If one is found there, assume to be the same marker.
13660    If the name / string id of the marker found is different from the
13661    previous known name, assume that means the user renamed the marker
13662    in the sources, and output a warning.
13663
13664    2) For a tracepoint set at a given line number, look for a marker
13665    at the new address of the old line number.  If one is found there,
13666    assume to be the same marker.  If the name / string id of the
13667    marker found is different from the previous known name, assume that
13668    means the user renamed the marker in the sources, and output a
13669    warning.
13670
13671    3) If a marker is no longer found at the same address or line, it
13672    may mean the marker no longer exists.  But it may also just mean
13673    the code changed a bit.  Maybe the user added a few lines of code
13674    that made the marker move up or down (in line number terms).  Ask
13675    the target for info about the marker with the string id as we knew
13676    it.  If found, update line number and address in the matching
13677    static tracepoint.  This will get confused if there's more than one
13678    marker with the same ID (possible in UST, although unadvised
13679    precisely because it confuses tools).  */
13680
13681 static struct symtab_and_line
13682 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13683 {
13684   struct tracepoint *tp = (struct tracepoint *) b;
13685   struct static_tracepoint_marker marker;
13686   CORE_ADDR pc;
13687
13688   pc = sal.pc;
13689   if (sal.line)
13690     find_line_pc (sal.symtab, sal.line, &pc);
13691
13692   if (target_static_tracepoint_marker_at (pc, &marker))
13693     {
13694       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13695         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13696                  b->number,
13697                  tp->static_trace_marker_id, marker.str_id);
13698
13699       xfree (tp->static_trace_marker_id);
13700       tp->static_trace_marker_id = xstrdup (marker.str_id);
13701       release_static_tracepoint_marker (&marker);
13702
13703       return sal;
13704     }
13705
13706   /* Old marker wasn't found on target at lineno.  Try looking it up
13707      by string ID.  */
13708   if (!sal.explicit_pc
13709       && sal.line != 0
13710       && sal.symtab != NULL
13711       && tp->static_trace_marker_id != NULL)
13712     {
13713       VEC(static_tracepoint_marker_p) *markers;
13714
13715       markers
13716         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13717
13718       if (!VEC_empty(static_tracepoint_marker_p, markers))
13719         {
13720           struct symbol *sym;
13721           struct static_tracepoint_marker *tpmarker;
13722           struct ui_out *uiout = current_uiout;
13723           struct explicit_location explicit_loc;
13724
13725           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13726
13727           xfree (tp->static_trace_marker_id);
13728           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13729
13730           warning (_("marker for static tracepoint %d (%s) not "
13731                      "found at previous line number"),
13732                    b->number, tp->static_trace_marker_id);
13733
13734           symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
13735           sym = find_pc_sect_function (tpmarker->address, NULL);
13736           uiout->text ("Now in ");
13737           if (sym)
13738             {
13739               uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
13740               uiout->text (" at ");
13741             }
13742           uiout->field_string ("file",
13743                                symtab_to_filename_for_display (sal2.symtab));
13744           uiout->text (":");
13745
13746           if (uiout->is_mi_like_p ())
13747             {
13748               const char *fullname = symtab_to_fullname (sal2.symtab);
13749
13750               uiout->field_string ("fullname", fullname);
13751             }
13752
13753           uiout->field_int ("line", sal2.line);
13754           uiout->text ("\n");
13755
13756           b->loc->line_number = sal2.line;
13757           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13758
13759           b->location.reset (NULL);
13760           initialize_explicit_location (&explicit_loc);
13761           explicit_loc.source_filename
13762             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
13763           explicit_loc.line_offset.offset = b->loc->line_number;
13764           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
13765           b->location = new_explicit_location (&explicit_loc);
13766
13767           /* Might be nice to check if function changed, and warn if
13768              so.  */
13769
13770           release_static_tracepoint_marker (tpmarker);
13771         }
13772     }
13773   return sal;
13774 }
13775
13776 /* Returns 1 iff locations A and B are sufficiently same that
13777    we don't need to report breakpoint as changed.  */
13778
13779 static int
13780 locations_are_equal (struct bp_location *a, struct bp_location *b)
13781 {
13782   while (a && b)
13783     {
13784       if (a->address != b->address)
13785         return 0;
13786
13787       if (a->shlib_disabled != b->shlib_disabled)
13788         return 0;
13789
13790       if (a->enabled != b->enabled)
13791         return 0;
13792
13793       a = a->next;
13794       b = b->next;
13795     }
13796
13797   if ((a == NULL) != (b == NULL))
13798     return 0;
13799
13800   return 1;
13801 }
13802
13803 /* Split all locations of B that are bound to PSPACE out of B's
13804    location list to a separate list and return that list's head.  If
13805    PSPACE is NULL, hoist out all locations of B.  */
13806
13807 static struct bp_location *
13808 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
13809 {
13810   struct bp_location head;
13811   struct bp_location *i = b->loc;
13812   struct bp_location **i_link = &b->loc;
13813   struct bp_location *hoisted = &head;
13814
13815   if (pspace == NULL)
13816     {
13817       i = b->loc;
13818       b->loc = NULL;
13819       return i;
13820     }
13821
13822   head.next = NULL;
13823
13824   while (i != NULL)
13825     {
13826       if (i->pspace == pspace)
13827         {
13828           *i_link = i->next;
13829           i->next = NULL;
13830           hoisted->next = i;
13831           hoisted = i;
13832         }
13833       else
13834         i_link = &i->next;
13835       i = *i_link;
13836     }
13837
13838   return head.next;
13839 }
13840
13841 /* Create new breakpoint locations for B (a hardware or software
13842    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
13843    zero, then B is a ranged breakpoint.  Only recreates locations for
13844    FILTER_PSPACE.  Locations of other program spaces are left
13845    untouched.  */
13846
13847 void
13848 update_breakpoint_locations (struct breakpoint *b,
13849                              struct program_space *filter_pspace,
13850                              gdb::array_view<const symtab_and_line> sals,
13851                              gdb::array_view<const symtab_and_line> sals_end)
13852 {
13853   int i;
13854   struct bp_location *existing_locations;
13855
13856   if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
13857     {
13858       /* Ranged breakpoints have only one start location and one end
13859          location.  */
13860       b->enable_state = bp_disabled;
13861       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13862                            "multiple locations found\n"),
13863                          b->number);
13864       return;
13865     }
13866
13867   /* If there's no new locations, and all existing locations are
13868      pending, don't do anything.  This optimizes the common case where
13869      all locations are in the same shared library, that was unloaded.
13870      We'd like to retain the location, so that when the library is
13871      loaded again, we don't loose the enabled/disabled status of the
13872      individual locations.  */
13873   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
13874     return;
13875
13876   existing_locations = hoist_existing_locations (b, filter_pspace);
13877
13878   for (const auto &sal : sals)
13879     {
13880       struct bp_location *new_loc;
13881
13882       switch_to_program_space_and_thread (sal.pspace);
13883
13884       new_loc = add_location_to_breakpoint (b, &sal);
13885
13886       /* Reparse conditions, they might contain references to the
13887          old symtab.  */
13888       if (b->cond_string != NULL)
13889         {
13890           const char *s;
13891
13892           s = b->cond_string;
13893           TRY
13894             {
13895               new_loc->cond = parse_exp_1 (&s, sal.pc,
13896                                            block_for_pc (sal.pc),
13897                                            0);
13898             }
13899           CATCH (e, RETURN_MASK_ERROR)
13900             {
13901               warning (_("failed to reevaluate condition "
13902                          "for breakpoint %d: %s"), 
13903                        b->number, e.message);
13904               new_loc->enabled = 0;
13905             }
13906           END_CATCH
13907         }
13908
13909       if (!sals_end.empty ())
13910         {
13911           CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13912
13913           new_loc->length = end - sals[0].pc + 1;
13914         }
13915     }
13916
13917   /* If possible, carry over 'disable' status from existing
13918      breakpoints.  */
13919   {
13920     struct bp_location *e = existing_locations;
13921     /* If there are multiple breakpoints with the same function name,
13922        e.g. for inline functions, comparing function names won't work.
13923        Instead compare pc addresses; this is just a heuristic as things
13924        may have moved, but in practice it gives the correct answer
13925        often enough until a better solution is found.  */
13926     int have_ambiguous_names = ambiguous_names_p (b->loc);
13927
13928     for (; e; e = e->next)
13929       {
13930         if (!e->enabled && e->function_name)
13931           {
13932             struct bp_location *l = b->loc;
13933             if (have_ambiguous_names)
13934               {
13935                 for (; l; l = l->next)
13936                   if (breakpoint_locations_match (e, l))
13937                     {
13938                       l->enabled = 0;
13939                       break;
13940                     }
13941               }
13942             else
13943               {
13944                 for (; l; l = l->next)
13945                   if (l->function_name
13946                       && strcmp (e->function_name, l->function_name) == 0)
13947                     {
13948                       l->enabled = 0;
13949                       break;
13950                     }
13951               }
13952           }
13953       }
13954   }
13955
13956   if (!locations_are_equal (existing_locations, b->loc))
13957     observer_notify_breakpoint_modified (b);
13958 }
13959
13960 /* Find the SaL locations corresponding to the given LOCATION.
13961    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13962
13963 static std::vector<symtab_and_line>
13964 location_to_sals (struct breakpoint *b, struct event_location *location,
13965                   struct program_space *search_pspace, int *found)
13966 {
13967   struct gdb_exception exception = exception_none;
13968
13969   gdb_assert (b->ops != NULL);
13970
13971   std::vector<symtab_and_line> sals;
13972
13973   TRY
13974     {
13975       sals = b->ops->decode_location (b, location, search_pspace);
13976     }
13977   CATCH (e, RETURN_MASK_ERROR)
13978     {
13979       int not_found_and_ok = 0;
13980
13981       exception = e;
13982
13983       /* For pending breakpoints, it's expected that parsing will
13984          fail until the right shared library is loaded.  User has
13985          already told to create pending breakpoints and don't need
13986          extra messages.  If breakpoint is in bp_shlib_disabled
13987          state, then user already saw the message about that
13988          breakpoint being disabled, and don't want to see more
13989          errors.  */
13990       if (e.error == NOT_FOUND_ERROR
13991           && (b->condition_not_parsed
13992               || (b->loc != NULL
13993                   && search_pspace != NULL
13994                   && b->loc->pspace != search_pspace)
13995               || (b->loc && b->loc->shlib_disabled)
13996               || (b->loc && b->loc->pspace->executing_startup)
13997               || b->enable_state == bp_disabled))
13998         not_found_and_ok = 1;
13999
14000       if (!not_found_and_ok)
14001         {
14002           /* We surely don't want to warn about the same breakpoint
14003              10 times.  One solution, implemented here, is disable
14004              the breakpoint on error.  Another solution would be to
14005              have separate 'warning emitted' flag.  Since this
14006              happens only when a binary has changed, I don't know
14007              which approach is better.  */
14008           b->enable_state = bp_disabled;
14009           throw_exception (e);
14010         }
14011     }
14012   END_CATCH
14013
14014   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
14015     {
14016       for (auto &sal : sals)
14017         resolve_sal_pc (&sal);
14018       if (b->condition_not_parsed && b->extra_string != NULL)
14019         {
14020           char *cond_string, *extra_string;
14021           int thread, task;
14022
14023           find_condition_and_thread (b->extra_string, sals[0].pc,
14024                                      &cond_string, &thread, &task,
14025                                      &extra_string);
14026           gdb_assert (b->cond_string == NULL);
14027           if (cond_string)
14028             b->cond_string = cond_string;
14029           b->thread = thread;
14030           b->task = task;
14031           if (extra_string)
14032             {
14033               xfree (b->extra_string);
14034               b->extra_string = extra_string;
14035             }
14036           b->condition_not_parsed = 0;
14037         }
14038
14039       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14040         sals[0] = update_static_tracepoint (b, sals[0]);
14041
14042       *found = 1;
14043     }
14044   else
14045     *found = 0;
14046
14047   return sals;
14048 }
14049
14050 /* The default re_set method, for typical hardware or software
14051    breakpoints.  Reevaluate the breakpoint and recreate its
14052    locations.  */
14053
14054 static void
14055 breakpoint_re_set_default (struct breakpoint *b)
14056 {
14057   struct program_space *filter_pspace = current_program_space;
14058   std::vector<symtab_and_line> expanded, expanded_end;
14059
14060   int found;
14061   std::vector<symtab_and_line> sals = location_to_sals (b, b->location.get (),
14062                                                         filter_pspace, &found);
14063   if (found)
14064     expanded = std::move (sals);
14065
14066   if (b->location_range_end != NULL)
14067     {
14068       std::vector<symtab_and_line> sals_end
14069         = location_to_sals (b, b->location_range_end.get (),
14070                             filter_pspace, &found);
14071       if (found)
14072         expanded_end = std::move (sals_end);
14073     }
14074
14075   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
14076 }
14077
14078 /* Default method for creating SALs from an address string.  It basically
14079    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14080
14081 static void
14082 create_sals_from_location_default (const struct event_location *location,
14083                                    struct linespec_result *canonical,
14084                                    enum bptype type_wanted)
14085 {
14086   parse_breakpoint_sals (location, canonical);
14087 }
14088
14089 /* Call create_breakpoints_sal for the given arguments.  This is the default
14090    function for the `create_breakpoints_sal' method of
14091    breakpoint_ops.  */
14092
14093 static void
14094 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14095                                 struct linespec_result *canonical,
14096                                 gdb::unique_xmalloc_ptr<char> cond_string,
14097                                 gdb::unique_xmalloc_ptr<char> extra_string,
14098                                 enum bptype type_wanted,
14099                                 enum bpdisp disposition,
14100                                 int thread,
14101                                 int task, int ignore_count,
14102                                 const struct breakpoint_ops *ops,
14103                                 int from_tty, int enabled,
14104                                 int internal, unsigned flags)
14105 {
14106   create_breakpoints_sal (gdbarch, canonical,
14107                           std::move (cond_string),
14108                           std::move (extra_string),
14109                           type_wanted, disposition,
14110                           thread, task, ignore_count, ops, from_tty,
14111                           enabled, internal, flags);
14112 }
14113
14114 /* Decode the line represented by S by calling decode_line_full.  This is the
14115    default function for the `decode_location' method of breakpoint_ops.  */
14116
14117 static std::vector<symtab_and_line>
14118 decode_location_default (struct breakpoint *b,
14119                          const struct event_location *location,
14120                          struct program_space *search_pspace)
14121 {
14122   struct linespec_result canonical;
14123
14124   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
14125                     (struct symtab *) NULL, 0,
14126                     &canonical, multiple_symbols_all,
14127                     b->filter);
14128
14129   /* We should get 0 or 1 resulting SALs.  */
14130   gdb_assert (canonical.lsals.size () < 2);
14131
14132   if (!canonical.lsals.empty ())
14133     {
14134       const linespec_sals &lsal = canonical.lsals[0];
14135       return std::move (lsal.sals);
14136     }
14137   return {};
14138 }
14139
14140 /* Prepare the global context for a re-set of breakpoint B.  */
14141
14142 static struct cleanup *
14143 prepare_re_set_context (struct breakpoint *b)
14144 {
14145   input_radix = b->input_radix;
14146   set_language (b->language);
14147
14148   return make_cleanup (null_cleanup, NULL);
14149 }
14150
14151 /* Reset a breakpoint given it's struct breakpoint * BINT.
14152    The value we return ends up being the return value from catch_errors.
14153    Unused in this case.  */
14154
14155 static int
14156 breakpoint_re_set_one (void *bint)
14157 {
14158   /* Get past catch_errs.  */
14159   struct breakpoint *b = (struct breakpoint *) bint;
14160   struct cleanup *cleanups;
14161
14162   cleanups = prepare_re_set_context (b);
14163   b->ops->re_set (b);
14164   do_cleanups (cleanups);
14165   return 0;
14166 }
14167
14168 /* Re-set breakpoint locations for the current program space.
14169    Locations bound to other program spaces are left untouched.  */
14170
14171 void
14172 breakpoint_re_set (void)
14173 {
14174   struct breakpoint *b, *b_tmp;
14175   enum language save_language;
14176   int save_input_radix;
14177
14178   save_language = current_language->la_language;
14179   save_input_radix = input_radix;
14180
14181   {
14182     scoped_restore_current_pspace_and_thread restore_pspace_thread;
14183
14184     /* Note: we must not try to insert locations until after all
14185        breakpoints have been re-set.  Otherwise, e.g., when re-setting
14186        breakpoint 1, we'd insert the locations of breakpoint 2, which
14187        hadn't been re-set yet, and thus may have stale locations.  */
14188
14189     ALL_BREAKPOINTS_SAFE (b, b_tmp)
14190       {
14191         /* Format possible error msg.  */
14192         char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14193                                     b->number);
14194         struct cleanup *cleanups = make_cleanup (xfree, message);
14195         catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14196         do_cleanups (cleanups);
14197       }
14198     set_language (save_language);
14199     input_radix = save_input_radix;
14200
14201     jit_breakpoint_re_set ();
14202   }
14203
14204   create_overlay_event_breakpoint ();
14205   create_longjmp_master_breakpoint ();
14206   create_std_terminate_master_breakpoint ();
14207   create_exception_master_breakpoint ();
14208
14209   /* Now we can insert.  */
14210   update_global_location_list (UGLL_MAY_INSERT);
14211 }
14212 \f
14213 /* Reset the thread number of this breakpoint:
14214
14215    - If the breakpoint is for all threads, leave it as-is.
14216    - Else, reset it to the current thread for inferior_ptid.  */
14217 void
14218 breakpoint_re_set_thread (struct breakpoint *b)
14219 {
14220   if (b->thread != -1)
14221     {
14222       if (in_thread_list (inferior_ptid))
14223         b->thread = ptid_to_global_thread_id (inferior_ptid);
14224
14225       /* We're being called after following a fork.  The new fork is
14226          selected as current, and unless this was a vfork will have a
14227          different program space from the original thread.  Reset that
14228          as well.  */
14229       b->loc->pspace = current_program_space;
14230     }
14231 }
14232
14233 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14234    If from_tty is nonzero, it prints a message to that effect,
14235    which ends with a period (no newline).  */
14236
14237 void
14238 set_ignore_count (int bptnum, int count, int from_tty)
14239 {
14240   struct breakpoint *b;
14241
14242   if (count < 0)
14243     count = 0;
14244
14245   ALL_BREAKPOINTS (b)
14246     if (b->number == bptnum)
14247     {
14248       if (is_tracepoint (b))
14249         {
14250           if (from_tty && count != 0)
14251             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14252                              bptnum);
14253           return;
14254         }
14255       
14256       b->ignore_count = count;
14257       if (from_tty)
14258         {
14259           if (count == 0)
14260             printf_filtered (_("Will stop next time "
14261                                "breakpoint %d is reached."),
14262                              bptnum);
14263           else if (count == 1)
14264             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14265                              bptnum);
14266           else
14267             printf_filtered (_("Will ignore next %d "
14268                                "crossings of breakpoint %d."),
14269                              count, bptnum);
14270         }
14271       observer_notify_breakpoint_modified (b);
14272       return;
14273     }
14274
14275   error (_("No breakpoint number %d."), bptnum);
14276 }
14277
14278 /* Command to set ignore-count of breakpoint N to COUNT.  */
14279
14280 static void
14281 ignore_command (char *args, int from_tty)
14282 {
14283   char *p = args;
14284   int num;
14285
14286   if (p == 0)
14287     error_no_arg (_("a breakpoint number"));
14288
14289   num = get_number (&p);
14290   if (num == 0)
14291     error (_("bad breakpoint number: '%s'"), args);
14292   if (*p == 0)
14293     error (_("Second argument (specified ignore-count) is missing."));
14294
14295   set_ignore_count (num,
14296                     longest_to_int (value_as_long (parse_and_eval (p))),
14297                     from_tty);
14298   if (from_tty)
14299     printf_filtered ("\n");
14300 }
14301 \f
14302 /* Call FUNCTION on each of the breakpoints
14303    whose numbers are given in ARGS.  */
14304
14305 static void
14306 map_breakpoint_numbers (const char *args,
14307                         gdb::function_view<void (breakpoint *)> function)
14308 {
14309   int num;
14310   struct breakpoint *b, *tmp;
14311
14312   if (args == 0 || *args == '\0')
14313     error_no_arg (_("one or more breakpoint numbers"));
14314
14315   number_or_range_parser parser (args);
14316
14317   while (!parser.finished ())
14318     {
14319       const char *p = parser.cur_tok ();
14320       bool match = false;
14321
14322       num = parser.get_number ();
14323       if (num == 0)
14324         {
14325           warning (_("bad breakpoint number at or near '%s'"), p);
14326         }
14327       else
14328         {
14329           ALL_BREAKPOINTS_SAFE (b, tmp)
14330             if (b->number == num)
14331               {
14332                 match = true;
14333                 function (b);
14334                 break;
14335               }
14336           if (!match)
14337             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14338         }
14339     }
14340 }
14341
14342 static struct bp_location *
14343 find_location_by_number (const char *number)
14344 {
14345   const char *p1;
14346   int bp_num;
14347   int loc_num;
14348   struct breakpoint *b;
14349   struct bp_location *loc;  
14350
14351   p1 = number;
14352   bp_num = get_number_trailer (&p1, '.');
14353   if (bp_num == 0 || p1[0] != '.')
14354     error (_("Bad breakpoint number '%s'"), number);
14355
14356   ALL_BREAKPOINTS (b)
14357     if (b->number == bp_num)
14358       {
14359         break;
14360       }
14361
14362   if (!b || b->number != bp_num)
14363     error (_("Bad breakpoint number '%s'"), number);
14364   
14365   /* Skip the dot.  */
14366   ++p1;
14367   const char *save = p1;
14368   loc_num = get_number (&p1);
14369   if (loc_num == 0)
14370     error (_("Bad breakpoint location number '%s'"), number);
14371
14372   --loc_num;
14373   loc = b->loc;
14374   for (;loc_num && loc; --loc_num, loc = loc->next)
14375     ;
14376   if (!loc)
14377     error (_("Bad breakpoint location number '%s'"), save);
14378     
14379   return loc;  
14380 }
14381
14382
14383 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14384    If from_tty is nonzero, it prints a message to that effect,
14385    which ends with a period (no newline).  */
14386
14387 void
14388 disable_breakpoint (struct breakpoint *bpt)
14389 {
14390   /* Never disable a watchpoint scope breakpoint; we want to
14391      hit them when we leave scope so we can delete both the
14392      watchpoint and its scope breakpoint at that time.  */
14393   if (bpt->type == bp_watchpoint_scope)
14394     return;
14395
14396   bpt->enable_state = bp_disabled;
14397
14398   /* Mark breakpoint locations modified.  */
14399   mark_breakpoint_modified (bpt);
14400
14401   if (target_supports_enable_disable_tracepoint ()
14402       && current_trace_status ()->running && is_tracepoint (bpt))
14403     {
14404       struct bp_location *location;
14405      
14406       for (location = bpt->loc; location; location = location->next)
14407         target_disable_tracepoint (location);
14408     }
14409
14410   update_global_location_list (UGLL_DONT_INSERT);
14411
14412   observer_notify_breakpoint_modified (bpt);
14413 }
14414
14415 static void
14416 disable_command (char *args, int from_tty)
14417 {
14418   if (args == 0)
14419     {
14420       struct breakpoint *bpt;
14421
14422       ALL_BREAKPOINTS (bpt)
14423         if (user_breakpoint_p (bpt))
14424           disable_breakpoint (bpt);
14425     }
14426   else
14427     {
14428       std::string num = extract_arg (&args);
14429
14430       while (!num.empty ())
14431         {
14432           if (num.find ('.') != std::string::npos)
14433             {
14434               struct bp_location *loc = find_location_by_number (num.c_str ());
14435
14436               if (loc)
14437                 {
14438                   if (loc->enabled)
14439                     {
14440                       loc->enabled = 0;
14441                       mark_breakpoint_location_modified (loc);
14442                     }
14443                   if (target_supports_enable_disable_tracepoint ()
14444                       && current_trace_status ()->running && loc->owner
14445                       && is_tracepoint (loc->owner))
14446                     target_disable_tracepoint (loc);
14447                 }
14448               update_global_location_list (UGLL_DONT_INSERT);
14449             }
14450           else
14451             map_breakpoint_numbers
14452               (num.c_str (), [&] (breakpoint *b)
14453                {
14454                  iterate_over_related_breakpoints (b, disable_breakpoint);
14455                });
14456           num = extract_arg (&args);
14457         }
14458     }
14459 }
14460
14461 static void
14462 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14463                         int count)
14464 {
14465   int target_resources_ok;
14466
14467   if (bpt->type == bp_hardware_breakpoint)
14468     {
14469       int i;
14470       i = hw_breakpoint_used_count ();
14471       target_resources_ok = 
14472         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14473                                             i + 1, 0);
14474       if (target_resources_ok == 0)
14475         error (_("No hardware breakpoint support in the target."));
14476       else if (target_resources_ok < 0)
14477         error (_("Hardware breakpoints used exceeds limit."));
14478     }
14479
14480   if (is_watchpoint (bpt))
14481     {
14482       /* Initialize it just to avoid a GCC false warning.  */
14483       enum enable_state orig_enable_state = bp_disabled;
14484
14485       TRY
14486         {
14487           struct watchpoint *w = (struct watchpoint *) bpt;
14488
14489           orig_enable_state = bpt->enable_state;
14490           bpt->enable_state = bp_enabled;
14491           update_watchpoint (w, 1 /* reparse */);
14492         }
14493       CATCH (e, RETURN_MASK_ALL)
14494         {
14495           bpt->enable_state = orig_enable_state;
14496           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14497                              bpt->number);
14498           return;
14499         }
14500       END_CATCH
14501     }
14502
14503   bpt->enable_state = bp_enabled;
14504
14505   /* Mark breakpoint locations modified.  */
14506   mark_breakpoint_modified (bpt);
14507
14508   if (target_supports_enable_disable_tracepoint ()
14509       && current_trace_status ()->running && is_tracepoint (bpt))
14510     {
14511       struct bp_location *location;
14512
14513       for (location = bpt->loc; location; location = location->next)
14514         target_enable_tracepoint (location);
14515     }
14516
14517   bpt->disposition = disposition;
14518   bpt->enable_count = count;
14519   update_global_location_list (UGLL_MAY_INSERT);
14520
14521   observer_notify_breakpoint_modified (bpt);
14522 }
14523
14524
14525 void
14526 enable_breakpoint (struct breakpoint *bpt)
14527 {
14528   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14529 }
14530
14531 /* The enable command enables the specified breakpoints (or all defined
14532    breakpoints) so they once again become (or continue to be) effective
14533    in stopping the inferior.  */
14534
14535 static void
14536 enable_command (char *args, int from_tty)
14537 {
14538   if (args == 0)
14539     {
14540       struct breakpoint *bpt;
14541
14542       ALL_BREAKPOINTS (bpt)
14543         if (user_breakpoint_p (bpt))
14544           enable_breakpoint (bpt);
14545     }
14546   else
14547     {
14548       std::string num = extract_arg (&args);
14549
14550       while (!num.empty ())
14551         {
14552           if (num.find ('.') != std::string::npos)
14553             {
14554               struct bp_location *loc = find_location_by_number (num.c_str ());
14555
14556               if (loc)
14557                 {
14558                   if (!loc->enabled)
14559                     {
14560                       loc->enabled = 1;
14561                       mark_breakpoint_location_modified (loc);
14562                     }
14563                   if (target_supports_enable_disable_tracepoint ()
14564                       && current_trace_status ()->running && loc->owner
14565                       && is_tracepoint (loc->owner))
14566                     target_enable_tracepoint (loc);
14567                 }
14568               update_global_location_list (UGLL_MAY_INSERT);
14569             }
14570           else
14571             map_breakpoint_numbers
14572               (num.c_str (), [&] (breakpoint *b)
14573                {
14574                  iterate_over_related_breakpoints (b, enable_breakpoint);
14575                });
14576           num = extract_arg (&args);
14577         }
14578     }
14579 }
14580
14581 static void
14582 enable_once_command (const char *args, int from_tty)
14583 {
14584   map_breakpoint_numbers
14585     (args, [&] (breakpoint *b)
14586      {
14587        iterate_over_related_breakpoints
14588          (b, [&] (breakpoint *bpt)
14589           {
14590             enable_breakpoint_disp (bpt, disp_disable, 1);
14591           });
14592      });
14593 }
14594
14595 static void
14596 enable_count_command (const char *args, int from_tty)
14597 {
14598   int count;
14599
14600   if (args == NULL)
14601     error_no_arg (_("hit count"));
14602
14603   count = get_number (&args);
14604
14605   map_breakpoint_numbers
14606     (args, [&] (breakpoint *b)
14607      {
14608        iterate_over_related_breakpoints
14609          (b, [&] (breakpoint *bpt)
14610           {
14611             enable_breakpoint_disp (bpt, disp_disable, count);
14612           });
14613      });
14614 }
14615
14616 static void
14617 enable_delete_command (const char *args, int from_tty)
14618 {
14619   map_breakpoint_numbers
14620     (args, [&] (breakpoint *b)
14621      {
14622        iterate_over_related_breakpoints
14623          (b, [&] (breakpoint *bpt)
14624           {
14625             enable_breakpoint_disp (bpt, disp_del, 1);
14626           });
14627      });
14628 }
14629 \f
14630 static void
14631 set_breakpoint_cmd (char *args, int from_tty)
14632 {
14633 }
14634
14635 static void
14636 show_breakpoint_cmd (char *args, int from_tty)
14637 {
14638 }
14639
14640 /* Invalidate last known value of any hardware watchpoint if
14641    the memory which that value represents has been written to by
14642    GDB itself.  */
14643
14644 static void
14645 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14646                                       CORE_ADDR addr, ssize_t len,
14647                                       const bfd_byte *data)
14648 {
14649   struct breakpoint *bp;
14650
14651   ALL_BREAKPOINTS (bp)
14652     if (bp->enable_state == bp_enabled
14653         && bp->type == bp_hardware_watchpoint)
14654       {
14655         struct watchpoint *wp = (struct watchpoint *) bp;
14656
14657         if (wp->val_valid && wp->val)
14658           {
14659             struct bp_location *loc;
14660
14661             for (loc = bp->loc; loc != NULL; loc = loc->next)
14662               if (loc->loc_type == bp_loc_hardware_watchpoint
14663                   && loc->address + loc->length > addr
14664                   && addr + len > loc->address)
14665                 {
14666                   value_free (wp->val);
14667                   wp->val = NULL;
14668                   wp->val_valid = 0;
14669                 }
14670           }
14671       }
14672 }
14673
14674 /* Create and insert a breakpoint for software single step.  */
14675
14676 void
14677 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14678                                struct address_space *aspace, 
14679                                CORE_ADDR next_pc)
14680 {
14681   struct thread_info *tp = inferior_thread ();
14682   struct symtab_and_line sal;
14683   CORE_ADDR pc = next_pc;
14684
14685   if (tp->control.single_step_breakpoints == NULL)
14686     {
14687       tp->control.single_step_breakpoints
14688         = new_single_step_breakpoint (tp->global_num, gdbarch);
14689     }
14690
14691   sal = find_pc_line (pc, 0);
14692   sal.pc = pc;
14693   sal.section = find_pc_overlay (pc);
14694   sal.explicit_pc = 1;
14695   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14696
14697   update_global_location_list (UGLL_INSERT);
14698 }
14699
14700 /* Insert single step breakpoints according to the current state.  */
14701
14702 int
14703 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14704 {
14705   struct regcache *regcache = get_current_regcache ();
14706   std::vector<CORE_ADDR> next_pcs;
14707
14708   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14709
14710   if (!next_pcs.empty ())
14711     {
14712       struct frame_info *frame = get_current_frame ();
14713       struct address_space *aspace = get_frame_address_space (frame);
14714
14715       for (CORE_ADDR pc : next_pcs)
14716         insert_single_step_breakpoint (gdbarch, aspace, pc);
14717
14718       return 1;
14719     }
14720   else
14721     return 0;
14722 }
14723
14724 /* See breakpoint.h.  */
14725
14726 int
14727 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14728                                        struct address_space *aspace,
14729                                        CORE_ADDR pc)
14730 {
14731   struct bp_location *loc;
14732
14733   for (loc = bp->loc; loc != NULL; loc = loc->next)
14734     if (loc->inserted
14735         && breakpoint_location_address_match (loc, aspace, pc))
14736       return 1;
14737
14738   return 0;
14739 }
14740
14741 /* Check whether a software single-step breakpoint is inserted at
14742    PC.  */
14743
14744 int
14745 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
14746                                         CORE_ADDR pc)
14747 {
14748   struct breakpoint *bpt;
14749
14750   ALL_BREAKPOINTS (bpt)
14751     {
14752       if (bpt->type == bp_single_step
14753           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
14754         return 1;
14755     }
14756   return 0;
14757 }
14758
14759 /* Tracepoint-specific operations.  */
14760
14761 /* Set tracepoint count to NUM.  */
14762 static void
14763 set_tracepoint_count (int num)
14764 {
14765   tracepoint_count = num;
14766   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14767 }
14768
14769 static void
14770 trace_command (char *arg_in, int from_tty)
14771 {
14772   const char *arg = arg_in;
14773   struct breakpoint_ops *ops;
14774
14775   event_location_up location = string_to_event_location (&arg,
14776                                                          current_language);
14777   if (location != NULL
14778       && event_location_type (location.get ()) == PROBE_LOCATION)
14779     ops = &tracepoint_probe_breakpoint_ops;
14780   else
14781     ops = &tracepoint_breakpoint_ops;
14782
14783   create_breakpoint (get_current_arch (),
14784                      location.get (),
14785                      NULL, 0, arg, 1 /* parse arg */,
14786                      0 /* tempflag */,
14787                      bp_tracepoint /* type_wanted */,
14788                      0 /* Ignore count */,
14789                      pending_break_support,
14790                      ops,
14791                      from_tty,
14792                      1 /* enabled */,
14793                      0 /* internal */, 0);
14794 }
14795
14796 static void
14797 ftrace_command (char *arg_in, int from_tty)
14798 {
14799   const char *arg = arg_in;
14800   event_location_up location = string_to_event_location (&arg,
14801                                                          current_language);
14802   create_breakpoint (get_current_arch (),
14803                      location.get (),
14804                      NULL, 0, arg, 1 /* parse arg */,
14805                      0 /* tempflag */,
14806                      bp_fast_tracepoint /* type_wanted */,
14807                      0 /* Ignore count */,
14808                      pending_break_support,
14809                      &tracepoint_breakpoint_ops,
14810                      from_tty,
14811                      1 /* enabled */,
14812                      0 /* internal */, 0);
14813 }
14814
14815 /* strace command implementation.  Creates a static tracepoint.  */
14816
14817 static void
14818 strace_command (char *arg_in, int from_tty)
14819 {
14820   const char *arg = arg_in;
14821   struct breakpoint_ops *ops;
14822   event_location_up location;
14823   struct cleanup *back_to;
14824
14825   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14826      or with a normal static tracepoint.  */
14827   if (arg && startswith (arg, "-m") && isspace (arg[2]))
14828     {
14829       ops = &strace_marker_breakpoint_ops;
14830       location = new_linespec_location (&arg);
14831     }
14832   else
14833     {
14834       ops = &tracepoint_breakpoint_ops;
14835       location = string_to_event_location (&arg, current_language);
14836     }
14837
14838   create_breakpoint (get_current_arch (),
14839                      location.get (),
14840                      NULL, 0, arg, 1 /* parse arg */,
14841                      0 /* tempflag */,
14842                      bp_static_tracepoint /* type_wanted */,
14843                      0 /* Ignore count */,
14844                      pending_break_support,
14845                      ops,
14846                      from_tty,
14847                      1 /* enabled */,
14848                      0 /* internal */, 0);
14849 }
14850
14851 /* Set up a fake reader function that gets command lines from a linked
14852    list that was acquired during tracepoint uploading.  */
14853
14854 static struct uploaded_tp *this_utp;
14855 static int next_cmd;
14856
14857 static char *
14858 read_uploaded_action (void)
14859 {
14860   char *rslt;
14861
14862   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
14863
14864   next_cmd++;
14865
14866   return rslt;
14867 }
14868
14869 /* Given information about a tracepoint as recorded on a target (which
14870    can be either a live system or a trace file), attempt to create an
14871    equivalent GDB tracepoint.  This is not a reliable process, since
14872    the target does not necessarily have all the information used when
14873    the tracepoint was originally defined.  */
14874   
14875 struct tracepoint *
14876 create_tracepoint_from_upload (struct uploaded_tp *utp)
14877 {
14878   const char *addr_str;
14879   char small_buf[100];
14880   struct tracepoint *tp;
14881
14882   if (utp->at_string)
14883     addr_str = utp->at_string;
14884   else
14885     {
14886       /* In the absence of a source location, fall back to raw
14887          address.  Since there is no way to confirm that the address
14888          means the same thing as when the trace was started, warn the
14889          user.  */
14890       warning (_("Uploaded tracepoint %d has no "
14891                  "source location, using raw address"),
14892                utp->number);
14893       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14894       addr_str = small_buf;
14895     }
14896
14897   /* There's not much we can do with a sequence of bytecodes.  */
14898   if (utp->cond && !utp->cond_string)
14899     warning (_("Uploaded tracepoint %d condition "
14900                "has no source form, ignoring it"),
14901              utp->number);
14902
14903   event_location_up location = string_to_event_location (&addr_str,
14904                                                          current_language);
14905   if (!create_breakpoint (get_current_arch (),
14906                           location.get (),
14907                           utp->cond_string, -1, addr_str,
14908                           0 /* parse cond/thread */,
14909                           0 /* tempflag */,
14910                           utp->type /* type_wanted */,
14911                           0 /* Ignore count */,
14912                           pending_break_support,
14913                           &tracepoint_breakpoint_ops,
14914                           0 /* from_tty */,
14915                           utp->enabled /* enabled */,
14916                           0 /* internal */,
14917                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14918     return NULL;
14919
14920   /* Get the tracepoint we just created.  */
14921   tp = get_tracepoint (tracepoint_count);
14922   gdb_assert (tp != NULL);
14923
14924   if (utp->pass > 0)
14925     {
14926       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14927                  tp->number);
14928
14929       trace_pass_command (small_buf, 0);
14930     }
14931
14932   /* If we have uploaded versions of the original commands, set up a
14933      special-purpose "reader" function and call the usual command line
14934      reader, then pass the result to the breakpoint command-setting
14935      function.  */
14936   if (!VEC_empty (char_ptr, utp->cmd_strings))
14937     {
14938       command_line_up cmd_list;
14939
14940       this_utp = utp;
14941       next_cmd = 0;
14942
14943       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
14944
14945       breakpoint_set_commands (tp, std::move (cmd_list));
14946     }
14947   else if (!VEC_empty (char_ptr, utp->actions)
14948            || !VEC_empty (char_ptr, utp->step_actions))
14949     warning (_("Uploaded tracepoint %d actions "
14950                "have no source form, ignoring them"),
14951              utp->number);
14952
14953   /* Copy any status information that might be available.  */
14954   tp->hit_count = utp->hit_count;
14955   tp->traceframe_usage = utp->traceframe_usage;
14956
14957   return tp;
14958 }
14959   
14960 /* Print information on tracepoint number TPNUM_EXP, or all if
14961    omitted.  */
14962
14963 static void
14964 info_tracepoints_command (char *args, int from_tty)
14965 {
14966   struct ui_out *uiout = current_uiout;
14967   int num_printed;
14968
14969   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14970
14971   if (num_printed == 0)
14972     {
14973       if (args == NULL || *args == '\0')
14974         uiout->message ("No tracepoints.\n");
14975       else
14976         uiout->message ("No tracepoint matching '%s'.\n", args);
14977     }
14978
14979   default_collect_info ();
14980 }
14981
14982 /* The 'enable trace' command enables tracepoints.
14983    Not supported by all targets.  */
14984 static void
14985 enable_trace_command (char *args, int from_tty)
14986 {
14987   enable_command (args, from_tty);
14988 }
14989
14990 /* The 'disable trace' command disables tracepoints.
14991    Not supported by all targets.  */
14992 static void
14993 disable_trace_command (char *args, int from_tty)
14994 {
14995   disable_command (args, from_tty);
14996 }
14997
14998 /* Remove a tracepoint (or all if no argument).  */
14999 static void
15000 delete_trace_command (const char *arg, int from_tty)
15001 {
15002   struct breakpoint *b, *b_tmp;
15003
15004   dont_repeat ();
15005
15006   if (arg == 0)
15007     {
15008       int breaks_to_delete = 0;
15009
15010       /* Delete all breakpoints if no argument.
15011          Do not delete internal or call-dummy breakpoints, these
15012          have to be deleted with an explicit breakpoint number 
15013          argument.  */
15014       ALL_TRACEPOINTS (b)
15015         if (is_tracepoint (b) && user_breakpoint_p (b))
15016           {
15017             breaks_to_delete = 1;
15018             break;
15019           }
15020
15021       /* Ask user only if there are some breakpoints to delete.  */
15022       if (!from_tty
15023           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15024         {
15025           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15026             if (is_tracepoint (b) && user_breakpoint_p (b))
15027               delete_breakpoint (b);
15028         }
15029     }
15030   else
15031     map_breakpoint_numbers
15032       (arg, [&] (breakpoint *b)
15033        {
15034          iterate_over_related_breakpoints (b, delete_breakpoint);
15035        });
15036 }
15037
15038 /* Helper function for trace_pass_command.  */
15039
15040 static void
15041 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15042 {
15043   tp->pass_count = count;
15044   observer_notify_breakpoint_modified (tp);
15045   if (from_tty)
15046     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15047                      tp->number, count);
15048 }
15049
15050 /* Set passcount for tracepoint.
15051
15052    First command argument is passcount, second is tracepoint number.
15053    If tracepoint number omitted, apply to most recently defined.
15054    Also accepts special argument "all".  */
15055
15056 static void
15057 trace_pass_command (char *args, int from_tty)
15058 {
15059   struct tracepoint *t1;
15060   unsigned int count;
15061
15062   if (args == 0 || *args == 0)
15063     error (_("passcount command requires an "
15064              "argument (count + optional TP num)"));
15065
15066   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15067
15068   args = skip_spaces (args);
15069   if (*args && strncasecmp (args, "all", 3) == 0)
15070     {
15071       struct breakpoint *b;
15072
15073       args += 3;                        /* Skip special argument "all".  */
15074       if (*args)
15075         error (_("Junk at end of arguments."));
15076
15077       ALL_TRACEPOINTS (b)
15078       {
15079         t1 = (struct tracepoint *) b;
15080         trace_pass_set_count (t1, count, from_tty);
15081       }
15082     }
15083   else if (*args == '\0')
15084     {
15085       t1 = get_tracepoint_by_number (&args, NULL);
15086       if (t1)
15087         trace_pass_set_count (t1, count, from_tty);
15088     }
15089   else
15090     {
15091       number_or_range_parser parser (args);
15092       while (!parser.finished ())
15093         {
15094           t1 = get_tracepoint_by_number (&args, &parser);
15095           if (t1)
15096             trace_pass_set_count (t1, count, from_tty);
15097         }
15098     }
15099 }
15100
15101 struct tracepoint *
15102 get_tracepoint (int num)
15103 {
15104   struct breakpoint *t;
15105
15106   ALL_TRACEPOINTS (t)
15107     if (t->number == num)
15108       return (struct tracepoint *) t;
15109
15110   return NULL;
15111 }
15112
15113 /* Find the tracepoint with the given target-side number (which may be
15114    different from the tracepoint number after disconnecting and
15115    reconnecting).  */
15116
15117 struct tracepoint *
15118 get_tracepoint_by_number_on_target (int num)
15119 {
15120   struct breakpoint *b;
15121
15122   ALL_TRACEPOINTS (b)
15123     {
15124       struct tracepoint *t = (struct tracepoint *) b;
15125
15126       if (t->number_on_target == num)
15127         return t;
15128     }
15129
15130   return NULL;
15131 }
15132
15133 /* Utility: parse a tracepoint number and look it up in the list.
15134    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15135    If the argument is missing, the most recent tracepoint
15136    (tracepoint_count) is returned.  */
15137
15138 struct tracepoint *
15139 get_tracepoint_by_number (char **arg,
15140                           number_or_range_parser *parser)
15141 {
15142   struct breakpoint *t;
15143   int tpnum;
15144   char *instring = arg == NULL ? NULL : *arg;
15145
15146   if (parser != NULL)
15147     {
15148       gdb_assert (!parser->finished ());
15149       tpnum = parser->get_number ();
15150     }
15151   else if (arg == NULL || *arg == NULL || ! **arg)
15152     tpnum = tracepoint_count;
15153   else
15154     tpnum = get_number (arg);
15155
15156   if (tpnum <= 0)
15157     {
15158       if (instring && *instring)
15159         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15160                          instring);
15161       else
15162         printf_filtered (_("No previous tracepoint\n"));
15163       return NULL;
15164     }
15165
15166   ALL_TRACEPOINTS (t)
15167     if (t->number == tpnum)
15168     {
15169       return (struct tracepoint *) t;
15170     }
15171
15172   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15173   return NULL;
15174 }
15175
15176 void
15177 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15178 {
15179   if (b->thread != -1)
15180     fprintf_unfiltered (fp, " thread %d", b->thread);
15181
15182   if (b->task != 0)
15183     fprintf_unfiltered (fp, " task %d", b->task);
15184
15185   fprintf_unfiltered (fp, "\n");
15186 }
15187
15188 /* Save information on user settable breakpoints (watchpoints, etc) to
15189    a new script file named FILENAME.  If FILTER is non-NULL, call it
15190    on each breakpoint and only include the ones for which it returns
15191    non-zero.  */
15192
15193 static void
15194 save_breakpoints (const char *filename, int from_tty,
15195                   int (*filter) (const struct breakpoint *))
15196 {
15197   struct breakpoint *tp;
15198   int any = 0;
15199   int extra_trace_bits = 0;
15200
15201   if (filename == 0 || *filename == 0)
15202     error (_("Argument required (file name in which to save)"));
15203
15204   /* See if we have anything to save.  */
15205   ALL_BREAKPOINTS (tp)
15206   {
15207     /* Skip internal and momentary breakpoints.  */
15208     if (!user_breakpoint_p (tp))
15209       continue;
15210
15211     /* If we have a filter, only save the breakpoints it accepts.  */
15212     if (filter && !filter (tp))
15213       continue;
15214
15215     any = 1;
15216
15217     if (is_tracepoint (tp))
15218       {
15219         extra_trace_bits = 1;
15220
15221         /* We can stop searching.  */
15222         break;
15223       }
15224   }
15225
15226   if (!any)
15227     {
15228       warning (_("Nothing to save."));
15229       return;
15230     }
15231
15232   gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
15233
15234   stdio_file fp;
15235
15236   if (!fp.open (expanded_filename.get (), "w"))
15237     error (_("Unable to open file '%s' for saving (%s)"),
15238            expanded_filename.get (), safe_strerror (errno));
15239
15240   if (extra_trace_bits)
15241     save_trace_state_variables (&fp);
15242
15243   ALL_BREAKPOINTS (tp)
15244   {
15245     /* Skip internal and momentary breakpoints.  */
15246     if (!user_breakpoint_p (tp))
15247       continue;
15248
15249     /* If we have a filter, only save the breakpoints it accepts.  */
15250     if (filter && !filter (tp))
15251       continue;
15252
15253     tp->ops->print_recreate (tp, &fp);
15254
15255     /* Note, we can't rely on tp->number for anything, as we can't
15256        assume the recreated breakpoint numbers will match.  Use $bpnum
15257        instead.  */
15258
15259     if (tp->cond_string)
15260       fp.printf ("  condition $bpnum %s\n", tp->cond_string);
15261
15262     if (tp->ignore_count)
15263       fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15264
15265     if (tp->type != bp_dprintf && tp->commands)
15266       {
15267         fp.puts ("  commands\n");
15268         
15269         current_uiout->redirect (&fp);
15270         TRY
15271           {
15272             print_command_lines (current_uiout, tp->commands.get (), 2);
15273           }
15274         CATCH (ex, RETURN_MASK_ALL)
15275           {
15276           current_uiout->redirect (NULL);
15277             throw_exception (ex);
15278           }
15279         END_CATCH
15280
15281         current_uiout->redirect (NULL);
15282         fp.puts ("  end\n");
15283       }
15284
15285     if (tp->enable_state == bp_disabled)
15286       fp.puts ("disable $bpnum\n");
15287
15288     /* If this is a multi-location breakpoint, check if the locations
15289        should be individually disabled.  Watchpoint locations are
15290        special, and not user visible.  */
15291     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15292       {
15293         struct bp_location *loc;
15294         int n = 1;
15295
15296         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15297           if (!loc->enabled)
15298             fp.printf ("disable $bpnum.%d\n", n);
15299       }
15300   }
15301
15302   if (extra_trace_bits && *default_collect)
15303     fp.printf ("set default-collect %s\n", default_collect);
15304
15305   if (from_tty)
15306     printf_filtered (_("Saved to file '%s'.\n"), expanded_filename.get ());
15307 }
15308
15309 /* The `save breakpoints' command.  */
15310
15311 static void
15312 save_breakpoints_command (const char *args, int from_tty)
15313 {
15314   save_breakpoints (args, from_tty, NULL);
15315 }
15316
15317 /* The `save tracepoints' command.  */
15318
15319 static void
15320 save_tracepoints_command (const char *args, int from_tty)
15321 {
15322   save_breakpoints (args, from_tty, is_tracepoint);
15323 }
15324
15325 /* Create a vector of all tracepoints.  */
15326
15327 VEC(breakpoint_p) *
15328 all_tracepoints (void)
15329 {
15330   VEC(breakpoint_p) *tp_vec = 0;
15331   struct breakpoint *tp;
15332
15333   ALL_TRACEPOINTS (tp)
15334   {
15335     VEC_safe_push (breakpoint_p, tp_vec, tp);
15336   }
15337
15338   return tp_vec;
15339 }
15340
15341 \f
15342 /* This help string is used to consolidate all the help string for specifying
15343    locations used by several commands.  */
15344
15345 #define LOCATION_HELP_STRING \
15346 "Linespecs are colon-separated lists of location parameters, such as\n\
15347 source filename, function name, label name, and line number.\n\
15348 Example: To specify the start of a label named \"the_top\" in the\n\
15349 function \"fact\" in the file \"factorial.c\", use\n\
15350 \"factorial.c:fact:the_top\".\n\
15351 \n\
15352 Address locations begin with \"*\" and specify an exact address in the\n\
15353 program.  Example: To specify the fourth byte past the start function\n\
15354 \"main\", use \"*main + 4\".\n\
15355 \n\
15356 Explicit locations are similar to linespecs but use an option/argument\n\
15357 syntax to specify location parameters.\n\
15358 Example: To specify the start of the label named \"the_top\" in the\n\
15359 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15360 -function fact -label the_top\".\n"
15361
15362 /* This help string is used for the break, hbreak, tbreak and thbreak
15363    commands.  It is defined as a macro to prevent duplication.
15364    COMMAND should be a string constant containing the name of the
15365    command.  */
15366
15367 #define BREAK_ARGS_HELP(command) \
15368 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15369 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15370 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15371 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15372 `-probe-dtrace' (for a DTrace probe).\n\
15373 LOCATION may be a linespec, address, or explicit location as described\n\
15374 below.\n\
15375 \n\
15376 With no LOCATION, uses current execution address of the selected\n\
15377 stack frame.  This is useful for breaking on return to a stack frame.\n\
15378 \n\
15379 THREADNUM is the number from \"info threads\".\n\
15380 CONDITION is a boolean expression.\n\
15381 \n" LOCATION_HELP_STRING "\n\
15382 Multiple breakpoints at one place are permitted, and useful if their\n\
15383 conditions are different.\n\
15384 \n\
15385 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15386
15387 /* List of subcommands for "catch".  */
15388 static struct cmd_list_element *catch_cmdlist;
15389
15390 /* List of subcommands for "tcatch".  */
15391 static struct cmd_list_element *tcatch_cmdlist;
15392
15393 void
15394 add_catch_command (const char *name, const char *docstring,
15395                    cmd_sfunc_ftype *sfunc,
15396                    completer_ftype *completer,
15397                    void *user_data_catch,
15398                    void *user_data_tcatch)
15399 {
15400   struct cmd_list_element *command;
15401
15402   command = add_cmd (name, class_breakpoint, docstring,
15403                      &catch_cmdlist);
15404   set_cmd_sfunc (command, sfunc);
15405   set_cmd_context (command, user_data_catch);
15406   set_cmd_completer (command, completer);
15407
15408   command = add_cmd (name, class_breakpoint, docstring,
15409                      &tcatch_cmdlist);
15410   set_cmd_sfunc (command, sfunc);
15411   set_cmd_context (command, user_data_tcatch);
15412   set_cmd_completer (command, completer);
15413 }
15414
15415 static void
15416 save_command (char *arg, int from_tty)
15417 {
15418   printf_unfiltered (_("\"save\" must be followed by "
15419                        "the name of a save subcommand.\n"));
15420   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15421 }
15422
15423 struct breakpoint *
15424 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15425                           void *data)
15426 {
15427   struct breakpoint *b, *b_tmp;
15428
15429   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15430     {
15431       if ((*callback) (b, data))
15432         return b;
15433     }
15434
15435   return NULL;
15436 }
15437
15438 /* Zero if any of the breakpoint's locations could be a location where
15439    functions have been inlined, nonzero otherwise.  */
15440
15441 static int
15442 is_non_inline_function (struct breakpoint *b)
15443 {
15444   /* The shared library event breakpoint is set on the address of a
15445      non-inline function.  */
15446   if (b->type == bp_shlib_event)
15447     return 1;
15448
15449   return 0;
15450 }
15451
15452 /* Nonzero if the specified PC cannot be a location where functions
15453    have been inlined.  */
15454
15455 int
15456 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15457                            const struct target_waitstatus *ws)
15458 {
15459   struct breakpoint *b;
15460   struct bp_location *bl;
15461
15462   ALL_BREAKPOINTS (b)
15463     {
15464       if (!is_non_inline_function (b))
15465         continue;
15466
15467       for (bl = b->loc; bl != NULL; bl = bl->next)
15468         {
15469           if (!bl->shlib_disabled
15470               && bpstat_check_location (bl, aspace, pc, ws))
15471             return 1;
15472         }
15473     }
15474
15475   return 0;
15476 }
15477
15478 /* Remove any references to OBJFILE which is going to be freed.  */
15479
15480 void
15481 breakpoint_free_objfile (struct objfile *objfile)
15482 {
15483   struct bp_location **locp, *loc;
15484
15485   ALL_BP_LOCATIONS (loc, locp)
15486     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15487       loc->symtab = NULL;
15488 }
15489
15490 void
15491 initialize_breakpoint_ops (void)
15492 {
15493   static int initialized = 0;
15494
15495   struct breakpoint_ops *ops;
15496
15497   if (initialized)
15498     return;
15499   initialized = 1;
15500
15501   /* The breakpoint_ops structure to be inherit by all kinds of
15502      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15503      internal and momentary breakpoints, etc.).  */
15504   ops = &bkpt_base_breakpoint_ops;
15505   *ops = base_breakpoint_ops;
15506   ops->re_set = bkpt_re_set;
15507   ops->insert_location = bkpt_insert_location;
15508   ops->remove_location = bkpt_remove_location;
15509   ops->breakpoint_hit = bkpt_breakpoint_hit;
15510   ops->create_sals_from_location = bkpt_create_sals_from_location;
15511   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15512   ops->decode_location = bkpt_decode_location;
15513
15514   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15515   ops = &bkpt_breakpoint_ops;
15516   *ops = bkpt_base_breakpoint_ops;
15517   ops->re_set = bkpt_re_set;
15518   ops->resources_needed = bkpt_resources_needed;
15519   ops->print_it = bkpt_print_it;
15520   ops->print_mention = bkpt_print_mention;
15521   ops->print_recreate = bkpt_print_recreate;
15522
15523   /* Ranged breakpoints.  */
15524   ops = &ranged_breakpoint_ops;
15525   *ops = bkpt_breakpoint_ops;
15526   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15527   ops->resources_needed = resources_needed_ranged_breakpoint;
15528   ops->print_it = print_it_ranged_breakpoint;
15529   ops->print_one = print_one_ranged_breakpoint;
15530   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15531   ops->print_mention = print_mention_ranged_breakpoint;
15532   ops->print_recreate = print_recreate_ranged_breakpoint;
15533
15534   /* Internal breakpoints.  */
15535   ops = &internal_breakpoint_ops;
15536   *ops = bkpt_base_breakpoint_ops;
15537   ops->re_set = internal_bkpt_re_set;
15538   ops->check_status = internal_bkpt_check_status;
15539   ops->print_it = internal_bkpt_print_it;
15540   ops->print_mention = internal_bkpt_print_mention;
15541
15542   /* Momentary breakpoints.  */
15543   ops = &momentary_breakpoint_ops;
15544   *ops = bkpt_base_breakpoint_ops;
15545   ops->re_set = momentary_bkpt_re_set;
15546   ops->check_status = momentary_bkpt_check_status;
15547   ops->print_it = momentary_bkpt_print_it;
15548   ops->print_mention = momentary_bkpt_print_mention;
15549
15550   /* Probe breakpoints.  */
15551   ops = &bkpt_probe_breakpoint_ops;
15552   *ops = bkpt_breakpoint_ops;
15553   ops->insert_location = bkpt_probe_insert_location;
15554   ops->remove_location = bkpt_probe_remove_location;
15555   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15556   ops->decode_location = bkpt_probe_decode_location;
15557
15558   /* Watchpoints.  */
15559   ops = &watchpoint_breakpoint_ops;
15560   *ops = base_breakpoint_ops;
15561   ops->re_set = re_set_watchpoint;
15562   ops->insert_location = insert_watchpoint;
15563   ops->remove_location = remove_watchpoint;
15564   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15565   ops->check_status = check_status_watchpoint;
15566   ops->resources_needed = resources_needed_watchpoint;
15567   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15568   ops->print_it = print_it_watchpoint;
15569   ops->print_mention = print_mention_watchpoint;
15570   ops->print_recreate = print_recreate_watchpoint;
15571   ops->explains_signal = explains_signal_watchpoint;
15572
15573   /* Masked watchpoints.  */
15574   ops = &masked_watchpoint_breakpoint_ops;
15575   *ops = watchpoint_breakpoint_ops;
15576   ops->insert_location = insert_masked_watchpoint;
15577   ops->remove_location = remove_masked_watchpoint;
15578   ops->resources_needed = resources_needed_masked_watchpoint;
15579   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15580   ops->print_it = print_it_masked_watchpoint;
15581   ops->print_one_detail = print_one_detail_masked_watchpoint;
15582   ops->print_mention = print_mention_masked_watchpoint;
15583   ops->print_recreate = print_recreate_masked_watchpoint;
15584
15585   /* Tracepoints.  */
15586   ops = &tracepoint_breakpoint_ops;
15587   *ops = base_breakpoint_ops;
15588   ops->re_set = tracepoint_re_set;
15589   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15590   ops->print_one_detail = tracepoint_print_one_detail;
15591   ops->print_mention = tracepoint_print_mention;
15592   ops->print_recreate = tracepoint_print_recreate;
15593   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15594   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15595   ops->decode_location = tracepoint_decode_location;
15596
15597   /* Probe tracepoints.  */
15598   ops = &tracepoint_probe_breakpoint_ops;
15599   *ops = tracepoint_breakpoint_ops;
15600   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15601   ops->decode_location = tracepoint_probe_decode_location;
15602
15603   /* Static tracepoints with marker (`-m').  */
15604   ops = &strace_marker_breakpoint_ops;
15605   *ops = tracepoint_breakpoint_ops;
15606   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15607   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15608   ops->decode_location = strace_marker_decode_location;
15609
15610   /* Fork catchpoints.  */
15611   ops = &catch_fork_breakpoint_ops;
15612   *ops = base_breakpoint_ops;
15613   ops->insert_location = insert_catch_fork;
15614   ops->remove_location = remove_catch_fork;
15615   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15616   ops->print_it = print_it_catch_fork;
15617   ops->print_one = print_one_catch_fork;
15618   ops->print_mention = print_mention_catch_fork;
15619   ops->print_recreate = print_recreate_catch_fork;
15620
15621   /* Vfork catchpoints.  */
15622   ops = &catch_vfork_breakpoint_ops;
15623   *ops = base_breakpoint_ops;
15624   ops->insert_location = insert_catch_vfork;
15625   ops->remove_location = remove_catch_vfork;
15626   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15627   ops->print_it = print_it_catch_vfork;
15628   ops->print_one = print_one_catch_vfork;
15629   ops->print_mention = print_mention_catch_vfork;
15630   ops->print_recreate = print_recreate_catch_vfork;
15631
15632   /* Exec catchpoints.  */
15633   ops = &catch_exec_breakpoint_ops;
15634   *ops = base_breakpoint_ops;
15635   ops->insert_location = insert_catch_exec;
15636   ops->remove_location = remove_catch_exec;
15637   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15638   ops->print_it = print_it_catch_exec;
15639   ops->print_one = print_one_catch_exec;
15640   ops->print_mention = print_mention_catch_exec;
15641   ops->print_recreate = print_recreate_catch_exec;
15642
15643   /* Solib-related catchpoints.  */
15644   ops = &catch_solib_breakpoint_ops;
15645   *ops = base_breakpoint_ops;
15646   ops->insert_location = insert_catch_solib;
15647   ops->remove_location = remove_catch_solib;
15648   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15649   ops->check_status = check_status_catch_solib;
15650   ops->print_it = print_it_catch_solib;
15651   ops->print_one = print_one_catch_solib;
15652   ops->print_mention = print_mention_catch_solib;
15653   ops->print_recreate = print_recreate_catch_solib;
15654
15655   ops = &dprintf_breakpoint_ops;
15656   *ops = bkpt_base_breakpoint_ops;
15657   ops->re_set = dprintf_re_set;
15658   ops->resources_needed = bkpt_resources_needed;
15659   ops->print_it = bkpt_print_it;
15660   ops->print_mention = bkpt_print_mention;
15661   ops->print_recreate = dprintf_print_recreate;
15662   ops->after_condition_true = dprintf_after_condition_true;
15663   ops->breakpoint_hit = dprintf_breakpoint_hit;
15664 }
15665
15666 /* Chain containing all defined "enable breakpoint" subcommands.  */
15667
15668 static struct cmd_list_element *enablebreaklist = NULL;
15669
15670 void
15671 _initialize_breakpoint (void)
15672 {
15673   struct cmd_list_element *c;
15674
15675   initialize_breakpoint_ops ();
15676
15677   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15678   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
15679   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
15680
15681   breakpoint_objfile_key
15682     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
15683
15684   breakpoint_chain = 0;
15685   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15686      before a breakpoint is set.  */
15687   breakpoint_count = 0;
15688
15689   tracepoint_count = 0;
15690
15691   add_com ("ignore", class_breakpoint, ignore_command, _("\
15692 Set ignore-count of breakpoint number N to COUNT.\n\
15693 Usage is `ignore N COUNT'."));
15694
15695   add_com ("commands", class_breakpoint, commands_command, _("\
15696 Set commands to be executed when the given breakpoints are hit.\n\
15697 Give a space-separated breakpoint list as argument after \"commands\".\n\
15698 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
15699 (e.g. `5-7').\n\
15700 With no argument, the targeted breakpoint is the last one set.\n\
15701 The commands themselves follow starting on the next line.\n\
15702 Type a line containing \"end\" to indicate the end of them.\n\
15703 Give \"silent\" as the first line to make the breakpoint silent;\n\
15704 then no output is printed when it is hit, except what the commands print."));
15705
15706   c = add_com ("condition", class_breakpoint, condition_command, _("\
15707 Specify breakpoint number N to break only if COND is true.\n\
15708 Usage is `condition N COND', where N is an integer and COND is an\n\
15709 expression to be evaluated whenever breakpoint N is reached."));
15710   set_cmd_completer (c, condition_completer);
15711
15712   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15713 Set a temporary breakpoint.\n\
15714 Like \"break\" except the breakpoint is only temporary,\n\
15715 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15716 by using \"enable delete\" on the breakpoint number.\n\
15717 \n"
15718 BREAK_ARGS_HELP ("tbreak")));
15719   set_cmd_completer (c, location_completer);
15720
15721   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15722 Set a hardware assisted breakpoint.\n\
15723 Like \"break\" except the breakpoint requires hardware support,\n\
15724 some target hardware may not have this support.\n\
15725 \n"
15726 BREAK_ARGS_HELP ("hbreak")));
15727   set_cmd_completer (c, location_completer);
15728
15729   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15730 Set a temporary hardware assisted breakpoint.\n\
15731 Like \"hbreak\" except the breakpoint is only temporary,\n\
15732 so it will be deleted when hit.\n\
15733 \n"
15734 BREAK_ARGS_HELP ("thbreak")));
15735   set_cmd_completer (c, location_completer);
15736
15737   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15738 Enable some breakpoints.\n\
15739 Give breakpoint numbers (separated by spaces) as arguments.\n\
15740 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15741 This is used to cancel the effect of the \"disable\" command.\n\
15742 With a subcommand you can enable temporarily."),
15743                   &enablelist, "enable ", 1, &cmdlist);
15744
15745   add_com_alias ("en", "enable", class_breakpoint, 1);
15746
15747   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15748 Enable some breakpoints.\n\
15749 Give breakpoint numbers (separated by spaces) as arguments.\n\
15750 This is used to cancel the effect of the \"disable\" command.\n\
15751 May be abbreviated to simply \"enable\".\n"),
15752                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15753
15754   add_cmd ("once", no_class, enable_once_command, _("\
15755 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15756 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15757            &enablebreaklist);
15758
15759   add_cmd ("delete", no_class, enable_delete_command, _("\
15760 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15761 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15762            &enablebreaklist);
15763
15764   add_cmd ("count", no_class, enable_count_command, _("\
15765 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15766 If a breakpoint is hit while enabled in this fashion,\n\
15767 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15768            &enablebreaklist);
15769
15770   add_cmd ("delete", no_class, enable_delete_command, _("\
15771 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15772 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15773            &enablelist);
15774
15775   add_cmd ("once", no_class, enable_once_command, _("\
15776 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15777 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15778            &enablelist);
15779
15780   add_cmd ("count", no_class, enable_count_command, _("\
15781 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15782 If a breakpoint is hit while enabled in this fashion,\n\
15783 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15784            &enablelist);
15785
15786   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15787 Disable some breakpoints.\n\
15788 Arguments are breakpoint numbers with spaces in between.\n\
15789 To disable all breakpoints, give no argument.\n\
15790 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15791                   &disablelist, "disable ", 1, &cmdlist);
15792   add_com_alias ("dis", "disable", class_breakpoint, 1);
15793   add_com_alias ("disa", "disable", class_breakpoint, 1);
15794
15795   add_cmd ("breakpoints", class_alias, disable_command, _("\
15796 Disable some breakpoints.\n\
15797 Arguments are breakpoint numbers with spaces in between.\n\
15798 To disable all breakpoints, give no argument.\n\
15799 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15800 This command may be abbreviated \"disable\"."),
15801            &disablelist);
15802
15803   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15804 Delete some breakpoints or auto-display expressions.\n\
15805 Arguments are breakpoint numbers with spaces in between.\n\
15806 To delete all breakpoints, give no argument.\n\
15807 \n\
15808 Also a prefix command for deletion of other GDB objects.\n\
15809 The \"unset\" command is also an alias for \"delete\"."),
15810                   &deletelist, "delete ", 1, &cmdlist);
15811   add_com_alias ("d", "delete", class_breakpoint, 1);
15812   add_com_alias ("del", "delete", class_breakpoint, 1);
15813
15814   add_cmd ("breakpoints", class_alias, delete_command, _("\
15815 Delete some breakpoints or auto-display expressions.\n\
15816 Arguments are breakpoint numbers with spaces in between.\n\
15817 To delete all breakpoints, give no argument.\n\
15818 This command may be abbreviated \"delete\"."),
15819            &deletelist);
15820
15821   add_com ("clear", class_breakpoint, clear_command, _("\
15822 Clear breakpoint at specified location.\n\
15823 Argument may be a linespec, explicit, or address location as described below.\n\
15824 \n\
15825 With no argument, clears all breakpoints in the line that the selected frame\n\
15826 is executing in.\n"
15827 "\n" LOCATION_HELP_STRING "\n\
15828 See also the \"delete\" command which clears breakpoints by number."));
15829   add_com_alias ("cl", "clear", class_breakpoint, 1);
15830
15831   c = add_com ("break", class_breakpoint, break_command, _("\
15832 Set breakpoint at specified location.\n"
15833 BREAK_ARGS_HELP ("break")));
15834   set_cmd_completer (c, location_completer);
15835
15836   add_com_alias ("b", "break", class_run, 1);
15837   add_com_alias ("br", "break", class_run, 1);
15838   add_com_alias ("bre", "break", class_run, 1);
15839   add_com_alias ("brea", "break", class_run, 1);
15840
15841   if (dbx_commands)
15842     {
15843       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15844 Break in function/address or break at a line in the current file."),
15845                              &stoplist, "stop ", 1, &cmdlist);
15846       add_cmd ("in", class_breakpoint, stopin_command,
15847                _("Break in function or address."), &stoplist);
15848       add_cmd ("at", class_breakpoint, stopat_command,
15849                _("Break at a line in the current file."), &stoplist);
15850       add_com ("status", class_info, info_breakpoints_command, _("\
15851 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15852 The \"Type\" column indicates one of:\n\
15853 \tbreakpoint     - normal breakpoint\n\
15854 \twatchpoint     - watchpoint\n\
15855 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15856 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15857 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15858 address and file/line number respectively.\n\
15859 \n\
15860 Convenience variable \"$_\" and default examine address for \"x\"\n\
15861 are set to the address of the last breakpoint listed unless the command\n\
15862 is prefixed with \"server \".\n\n\
15863 Convenience variable \"$bpnum\" contains the number of the last\n\
15864 breakpoint set."));
15865     }
15866
15867   add_info ("breakpoints", info_breakpoints_command, _("\
15868 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15869 The \"Type\" column indicates one of:\n\
15870 \tbreakpoint     - normal breakpoint\n\
15871 \twatchpoint     - watchpoint\n\
15872 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15873 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15874 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15875 address and file/line number respectively.\n\
15876 \n\
15877 Convenience variable \"$_\" and default examine address for \"x\"\n\
15878 are set to the address of the last breakpoint listed unless the command\n\
15879 is prefixed with \"server \".\n\n\
15880 Convenience variable \"$bpnum\" contains the number of the last\n\
15881 breakpoint set."));
15882
15883   add_info_alias ("b", "breakpoints", 1);
15884
15885   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15886 Status of all breakpoints, or breakpoint number NUMBER.\n\
15887 The \"Type\" column indicates one of:\n\
15888 \tbreakpoint     - normal breakpoint\n\
15889 \twatchpoint     - watchpoint\n\
15890 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15891 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15892 \tuntil          - internal breakpoint used by the \"until\" command\n\
15893 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15894 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15895 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15896 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15897 address and file/line number respectively.\n\
15898 \n\
15899 Convenience variable \"$_\" and default examine address for \"x\"\n\
15900 are set to the address of the last breakpoint listed unless the command\n\
15901 is prefixed with \"server \".\n\n\
15902 Convenience variable \"$bpnum\" contains the number of the last\n\
15903 breakpoint set."),
15904            &maintenanceinfolist);
15905
15906   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15907 Set catchpoints to catch events."),
15908                   &catch_cmdlist, "catch ",
15909                   0/*allow-unknown*/, &cmdlist);
15910
15911   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15912 Set temporary catchpoints to catch events."),
15913                   &tcatch_cmdlist, "tcatch ",
15914                   0/*allow-unknown*/, &cmdlist);
15915
15916   add_catch_command ("fork", _("Catch calls to fork."),
15917                      catch_fork_command_1,
15918                      NULL,
15919                      (void *) (uintptr_t) catch_fork_permanent,
15920                      (void *) (uintptr_t) catch_fork_temporary);
15921   add_catch_command ("vfork", _("Catch calls to vfork."),
15922                      catch_fork_command_1,
15923                      NULL,
15924                      (void *) (uintptr_t) catch_vfork_permanent,
15925                      (void *) (uintptr_t) catch_vfork_temporary);
15926   add_catch_command ("exec", _("Catch calls to exec."),
15927                      catch_exec_command_1,
15928                      NULL,
15929                      CATCH_PERMANENT,
15930                      CATCH_TEMPORARY);
15931   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15932 Usage: catch load [REGEX]\n\
15933 If REGEX is given, only stop for libraries matching the regular expression."),
15934                      catch_load_command_1,
15935                      NULL,
15936                      CATCH_PERMANENT,
15937                      CATCH_TEMPORARY);
15938   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15939 Usage: catch unload [REGEX]\n\
15940 If REGEX is given, only stop for libraries matching the regular expression."),
15941                      catch_unload_command_1,
15942                      NULL,
15943                      CATCH_PERMANENT,
15944                      CATCH_TEMPORARY);
15945
15946   c = add_com ("watch", class_breakpoint, watch_command, _("\
15947 Set a watchpoint for an expression.\n\
15948 Usage: watch [-l|-location] EXPRESSION\n\
15949 A watchpoint stops execution of your program whenever the value of\n\
15950 an expression changes.\n\
15951 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15952 the memory to which it refers."));
15953   set_cmd_completer (c, expression_completer);
15954
15955   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15956 Set a read watchpoint for an expression.\n\
15957 Usage: rwatch [-l|-location] EXPRESSION\n\
15958 A watchpoint stops execution of your program whenever the value of\n\
15959 an expression is read.\n\
15960 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15961 the memory to which it refers."));
15962   set_cmd_completer (c, expression_completer);
15963
15964   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15965 Set a watchpoint for an expression.\n\
15966 Usage: awatch [-l|-location] EXPRESSION\n\
15967 A watchpoint stops execution of your program whenever the value of\n\
15968 an expression is either read or written.\n\
15969 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15970 the memory to which it refers."));
15971   set_cmd_completer (c, expression_completer);
15972
15973   add_info ("watchpoints", info_watchpoints_command, _("\
15974 Status of specified watchpoints (all watchpoints if no argument)."));
15975
15976   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15977      respond to changes - contrary to the description.  */
15978   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15979                             &can_use_hw_watchpoints, _("\
15980 Set debugger's willingness to use watchpoint hardware."), _("\
15981 Show debugger's willingness to use watchpoint hardware."), _("\
15982 If zero, gdb will not use hardware for new watchpoints, even if\n\
15983 such is available.  (However, any hardware watchpoints that were\n\
15984 created before setting this to nonzero, will continue to use watchpoint\n\
15985 hardware.)"),
15986                             NULL,
15987                             show_can_use_hw_watchpoints,
15988                             &setlist, &showlist);
15989
15990   can_use_hw_watchpoints = 1;
15991
15992   /* Tracepoint manipulation commands.  */
15993
15994   c = add_com ("trace", class_breakpoint, trace_command, _("\
15995 Set a tracepoint at specified location.\n\
15996 \n"
15997 BREAK_ARGS_HELP ("trace") "\n\
15998 Do \"help tracepoints\" for info on other tracepoint commands."));
15999   set_cmd_completer (c, location_completer);
16000
16001   add_com_alias ("tp", "trace", class_alias, 0);
16002   add_com_alias ("tr", "trace", class_alias, 1);
16003   add_com_alias ("tra", "trace", class_alias, 1);
16004   add_com_alias ("trac", "trace", class_alias, 1);
16005
16006   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16007 Set a fast tracepoint at specified location.\n\
16008 \n"
16009 BREAK_ARGS_HELP ("ftrace") "\n\
16010 Do \"help tracepoints\" for info on other tracepoint commands."));
16011   set_cmd_completer (c, location_completer);
16012
16013   c = add_com ("strace", class_breakpoint, strace_command, _("\
16014 Set a static tracepoint at location or marker.\n\
16015 \n\
16016 strace [LOCATION] [if CONDITION]\n\
16017 LOCATION may be a linespec, explicit, or address location (described below) \n\
16018 or -m MARKER_ID.\n\n\
16019 If a marker id is specified, probe the marker with that name.  With\n\
16020 no LOCATION, uses current execution address of the selected stack frame.\n\
16021 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16022 This collects arbitrary user data passed in the probe point call to the\n\
16023 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16024 by printing the $_sdata variable like any other convenience variable.\n\
16025 \n\
16026 CONDITION is a boolean expression.\n\
16027 \n" LOCATION_HELP_STRING "\n\
16028 Multiple tracepoints at one place are permitted, and useful if their\n\
16029 conditions are different.\n\
16030 \n\
16031 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16032 Do \"help tracepoints\" for info on other tracepoint commands."));
16033   set_cmd_completer (c, location_completer);
16034
16035   add_info ("tracepoints", info_tracepoints_command, _("\
16036 Status of specified tracepoints (all tracepoints if no argument).\n\
16037 Convenience variable \"$tpnum\" contains the number of the\n\
16038 last tracepoint set."));
16039
16040   add_info_alias ("tp", "tracepoints", 1);
16041
16042   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16043 Delete specified tracepoints.\n\
16044 Arguments are tracepoint numbers, separated by spaces.\n\
16045 No argument means delete all tracepoints."),
16046            &deletelist);
16047   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16048
16049   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16050 Disable specified tracepoints.\n\
16051 Arguments are tracepoint numbers, separated by spaces.\n\
16052 No argument means disable all tracepoints."),
16053            &disablelist);
16054   deprecate_cmd (c, "disable");
16055
16056   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16057 Enable specified tracepoints.\n\
16058 Arguments are tracepoint numbers, separated by spaces.\n\
16059 No argument means enable all tracepoints."),
16060            &enablelist);
16061   deprecate_cmd (c, "enable");
16062
16063   add_com ("passcount", class_trace, trace_pass_command, _("\
16064 Set the passcount for a tracepoint.\n\
16065 The trace will end when the tracepoint has been passed 'count' times.\n\
16066 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16067 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16068
16069   add_prefix_cmd ("save", class_breakpoint, save_command,
16070                   _("Save breakpoint definitions as a script."),
16071                   &save_cmdlist, "save ",
16072                   0/*allow-unknown*/, &cmdlist);
16073
16074   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16075 Save current breakpoint definitions as a script.\n\
16076 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16077 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16078 session to restore them."),
16079                &save_cmdlist);
16080   set_cmd_completer (c, filename_completer);
16081
16082   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16083 Save current tracepoint definitions as a script.\n\
16084 Use the 'source' command in another debug session to restore them."),
16085                &save_cmdlist);
16086   set_cmd_completer (c, filename_completer);
16087
16088   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16089   deprecate_cmd (c, "save tracepoints");
16090
16091   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16092 Breakpoint specific settings\n\
16093 Configure various breakpoint-specific variables such as\n\
16094 pending breakpoint behavior"),
16095                   &breakpoint_set_cmdlist, "set breakpoint ",
16096                   0/*allow-unknown*/, &setlist);
16097   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16098 Breakpoint specific settings\n\
16099 Configure various breakpoint-specific variables such as\n\
16100 pending breakpoint behavior"),
16101                   &breakpoint_show_cmdlist, "show breakpoint ",
16102                   0/*allow-unknown*/, &showlist);
16103
16104   add_setshow_auto_boolean_cmd ("pending", no_class,
16105                                 &pending_break_support, _("\
16106 Set debugger's behavior regarding pending breakpoints."), _("\
16107 Show debugger's behavior regarding pending breakpoints."), _("\
16108 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16109 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16110 an error.  If auto, an unrecognized breakpoint location results in a\n\
16111 user-query to see if a pending breakpoint should be created."),
16112                                 NULL,
16113                                 show_pending_break_support,
16114                                 &breakpoint_set_cmdlist,
16115                                 &breakpoint_show_cmdlist);
16116
16117   pending_break_support = AUTO_BOOLEAN_AUTO;
16118
16119   add_setshow_boolean_cmd ("auto-hw", no_class,
16120                            &automatic_hardware_breakpoints, _("\
16121 Set automatic usage of hardware breakpoints."), _("\
16122 Show automatic usage of hardware breakpoints."), _("\
16123 If set, the debugger will automatically use hardware breakpoints for\n\
16124 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16125 a warning will be emitted for such breakpoints."),
16126                            NULL,
16127                            show_automatic_hardware_breakpoints,
16128                            &breakpoint_set_cmdlist,
16129                            &breakpoint_show_cmdlist);
16130
16131   add_setshow_boolean_cmd ("always-inserted", class_support,
16132                            &always_inserted_mode, _("\
16133 Set mode for inserting breakpoints."), _("\
16134 Show mode for inserting breakpoints."), _("\
16135 When this mode is on, breakpoints are inserted immediately as soon as\n\
16136 they're created, kept inserted even when execution stops, and removed\n\
16137 only when the user deletes them.  When this mode is off (the default),\n\
16138 breakpoints are inserted only when execution continues, and removed\n\
16139 when execution stops."),
16140                                 NULL,
16141                                 &show_always_inserted_mode,
16142                                 &breakpoint_set_cmdlist,
16143                                 &breakpoint_show_cmdlist);
16144
16145   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16146                         condition_evaluation_enums,
16147                         &condition_evaluation_mode_1, _("\
16148 Set mode of breakpoint condition evaluation."), _("\
16149 Show mode of breakpoint condition evaluation."), _("\
16150 When this is set to \"host\", breakpoint conditions will be\n\
16151 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16152 breakpoint conditions will be downloaded to the target (if the target\n\
16153 supports such feature) and conditions will be evaluated on the target's side.\n\
16154 If this is set to \"auto\" (default), this will be automatically set to\n\
16155 \"target\" if it supports condition evaluation, otherwise it will\n\
16156 be set to \"gdb\""),
16157                            &set_condition_evaluation_mode,
16158                            &show_condition_evaluation_mode,
16159                            &breakpoint_set_cmdlist,
16160                            &breakpoint_show_cmdlist);
16161
16162   add_com ("break-range", class_breakpoint, break_range_command, _("\
16163 Set a breakpoint for an address range.\n\
16164 break-range START-LOCATION, END-LOCATION\n\
16165 where START-LOCATION and END-LOCATION can be one of the following:\n\
16166   LINENUM, for that line in the current file,\n\
16167   FILE:LINENUM, for that line in that file,\n\
16168   +OFFSET, for that number of lines after the current line\n\
16169            or the start of the range\n\
16170   FUNCTION, for the first line in that function,\n\
16171   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16172   *ADDRESS, for the instruction at that address.\n\
16173 \n\
16174 The breakpoint will stop execution of the inferior whenever it executes\n\
16175 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16176 range (including START-LOCATION and END-LOCATION)."));
16177
16178   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16179 Set a dynamic printf at specified location.\n\
16180 dprintf location,format string,arg1,arg2,...\n\
16181 location may be a linespec, explicit, or address location.\n"
16182 "\n" LOCATION_HELP_STRING));
16183   set_cmd_completer (c, location_completer);
16184
16185   add_setshow_enum_cmd ("dprintf-style", class_support,
16186                         dprintf_style_enums, &dprintf_style, _("\
16187 Set the style of usage for dynamic printf."), _("\
16188 Show the style of usage for dynamic printf."), _("\
16189 This setting chooses how GDB will do a dynamic printf.\n\
16190 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16191 console, as with the \"printf\" command.\n\
16192 If the value is \"call\", the print is done by calling a function in your\n\
16193 program; by default printf(), but you can choose a different function or\n\
16194 output stream by setting dprintf-function and dprintf-channel."),
16195                         update_dprintf_commands, NULL,
16196                         &setlist, &showlist);
16197
16198   dprintf_function = xstrdup ("printf");
16199   add_setshow_string_cmd ("dprintf-function", class_support,
16200                           &dprintf_function, _("\
16201 Set the function to use for dynamic printf"), _("\
16202 Show the function to use for dynamic printf"), NULL,
16203                           update_dprintf_commands, NULL,
16204                           &setlist, &showlist);
16205
16206   dprintf_channel = xstrdup ("");
16207   add_setshow_string_cmd ("dprintf-channel", class_support,
16208                           &dprintf_channel, _("\
16209 Set the channel to use for dynamic printf"), _("\
16210 Show the channel to use for dynamic printf"), NULL,
16211                           update_dprintf_commands, NULL,
16212                           &setlist, &showlist);
16213
16214   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16215                            &disconnected_dprintf, _("\
16216 Set whether dprintf continues after GDB disconnects."), _("\
16217 Show whether dprintf continues after GDB disconnects."), _("\
16218 Use this to let dprintf commands continue to hit and produce output\n\
16219 even if GDB disconnects or detaches from the target."),
16220                            NULL,
16221                            NULL,
16222                            &setlist, &showlist);
16223
16224   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16225 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16226 (target agent only) This is useful for formatted output in user-defined commands."));
16227
16228   automatic_hardware_breakpoints = 1;
16229
16230   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16231   observer_attach_thread_exit (remove_threaded_breakpoints);
16232 }